Synch to No Gnus 200601190601.
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;;      Shuhei KOBAYASHI <shuhei-k@jaist.ac.jp>
9 ;;      Keiichi Suzuki   <kei-suzu@mail.wbs.ne.jp>
10 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
11 ;;      Katsumi Yamaoka  <yamaoka@jpl.org>
12 ;;      Kiyokazu SUTO    <suto@merry.xmath.ous.ac.jp>
13 ;; Keywords: mail, news, MIME
14
15 ;; This file is part of GNU Emacs.
16
17 ;; GNU Emacs is free software; you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation; either version 2, or (at your option)
20 ;; any later version.
21
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 ;; GNU General Public License for more details.
26
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
29 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
30 ;; Boston, MA 02110-1301, USA.
31
32 ;;; Commentary:
33
34 ;; This mode provides mail-sending facilities from within Emacs.  It
35 ;; consists mainly of large chunks of code from the sendmail.el,
36 ;; gnus-msg.el and rnewspost.el files.
37
38 ;;; Code:
39
40 (eval-when-compile
41   (require 'cl)
42   (require 'smtp)
43   (defvar gnus-message-group-art)
44   (defvar gnus-list-identifiers) ; gnus-sum is required where necessary
45   (require 'hashcash))
46 (require 'canlock)
47 (require 'mailheader)
48 (require 'nnheader)
49 ;; This is apparently necessary even though things are autoloaded.
50 ;; Because we dynamically bind mail-abbrev-mode-regexp, we'd better
51 ;; require mailabbrev here.
52 (if (featurep 'xemacs)
53     (require 'mail-abbrevs)
54   (require 'mailabbrev))
55 (require 'mime-edit)
56 (eval-when-compile (require 'static))
57
58 ;; Avoid byte-compile warnings.
59 (eval-when-compile
60   (require 'mail-parse)
61   (require 'mml))
62
63 (require 'rfc822)
64
65 (defgroup message '((user-mail-address custom-variable)
66                     (user-full-name custom-variable))
67   "Mail and news message composing."
68   :link '(custom-manual "(message)Top")
69   :group 'mail
70   :group 'news)
71
72 (put 'user-mail-address 'custom-type 'string)
73 (put 'user-full-name 'custom-type 'string)
74
75 (defgroup message-various nil
76   "Various Message Variables."
77   :link '(custom-manual "(message)Various Message Variables")
78   :group 'message)
79
80 (defgroup message-buffers nil
81   "Message Buffers."
82   :link '(custom-manual "(message)Message Buffers")
83   :group 'message)
84
85 (defgroup message-sending nil
86   "Message Sending."
87   :link '(custom-manual "(message)Sending Variables")
88   :group 'message)
89
90 (defgroup message-interface nil
91   "Message Interface."
92   :link '(custom-manual "(message)Interface")
93   :group 'message)
94
95 (defgroup message-forwarding nil
96   "Message Forwarding."
97   :link '(custom-manual "(message)Forwarding")
98   :group 'message-interface)
99
100 (defgroup message-insertion nil
101   "Message Insertion."
102   :link '(custom-manual "(message)Insertion")
103   :group 'message)
104
105 (defgroup message-headers nil
106   "Message Headers."
107   :link '(custom-manual "(message)Message Headers")
108   :group 'message)
109
110 (defgroup message-news nil
111   "Composing News Messages."
112   :group 'message)
113
114 (defgroup message-mail nil
115   "Composing Mail Messages."
116   :group 'message)
117
118 (defgroup message-faces nil
119   "Faces used for message composing."
120   :group 'message
121   :group 'faces)
122
123 (defgroup message-frames nil
124   "Message frames"
125   :group 'message)
126
127 (defcustom message-directory "~/Mail/"
128   "*Directory from which all other mail file variables are derived."
129   :group 'message-various
130   :type 'directory)
131
132 (defcustom message-max-buffers 10
133   "*How many buffers to keep before starting to kill them off."
134   :group 'message-buffers
135   :type 'integer)
136
137 (defcustom message-send-rename-function nil
138   "Function called to rename the buffer after sending it."
139   :group 'message-buffers
140   :type '(choice function (const nil)))
141
142 (defcustom message-fcc-handler-function 'message-output
143   "*A function called to save outgoing articles.
144 This function will be called with the name of the file to store the
145 article in.  The default function is `message-output' which saves in Unix
146 mailbox format."
147   :type '(radio (function-item message-output)
148                 (function :tag "Other"))
149   :group 'message-sending)
150
151 (defcustom message-encode-function 'message-maybe-encode
152   "*A function called to encode messages."
153   :group 'message-sending
154   :type 'function)
155
156 (defcustom message-8bit-encoding-list '(8bit binary)
157   "*8bit encoding type in Content-Transfer-Encoding field."
158   :group 'message-sending
159   :type '(repeat (symbol :tag "Type")))
160
161 (defcustom message-fcc-externalize-attachments nil
162   "If non-nil, attachments are included as external parts in Fcc copies."
163   :version "22.1"
164   :type 'boolean
165   :group 'message-sending)
166
167 (defcustom message-courtesy-message
168   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
169   "*This is inserted at the start of a mailed copy of a posted message.
170 If the string contains the format spec \"%s\", the Newsgroups
171 the article has been posted to will be inserted there.
172 If this variable is nil, no such courtesy message will be added."
173   :group 'message-sending
174   :type '(radio string (const nil)))
175
176 (defcustom message-ignored-bounced-headers
177   "^\\(Received\\|Return-Path\\|Delivered-To\\):"
178   "*Regexp that matches headers to be removed in resent bounced mail."
179   :group 'message-interface
180   :type 'regexp)
181
182 (defcustom message-bounce-setup-function 'message-bounce-setup-for-mime-edit
183   "Function to setup a re-sending bounced message."
184   :group 'message-sending
185   :type 'function)
186
187 ;;; Start of variables adopted from `message-utils.el'.
188
189 (defcustom message-subject-trailing-was-query 'ask
190   "*What to do with trailing \"(was: <old subject>)\" in subject lines.
191 If nil, leave the subject unchanged.  If it is the symbol `ask', query
192 the user what do do.  In this case, the subject is matched against
193 `message-subject-trailing-was-ask-regexp'.  If
194 `message-subject-trailing-was-query' is t, always strip the trailing
195 old subject.  In this case, `message-subject-trailing-was-regexp' is
196 used."
197   :version "22.1"
198   :type '(choice (const :tag "never" nil)
199                  (const :tag "always strip" t)
200                  (const ask))
201   :link '(custom-manual "(message)Message Headers")
202   :group 'message-various)
203
204 (defcustom message-subject-trailing-was-ask-regexp
205   "[ \t]*\\([[(]+[Ww][Aa][Ss][ \t]*.*[\])]+\\)"
206   "*Regexp matching \"(was: <old subject>)\" in the subject line.
207
208 The function `message-strip-subject-trailing-was' uses this regexp if
209 `message-subject-trailing-was-query' is set to the symbol `ask'.  If
210 the variable is t instead of `ask', use
211 `message-subject-trailing-was-regexp' instead.
212
213 It is okay to create some false positives here, as the user is asked."
214   :version "22.1"
215   :group 'message-various
216   :link '(custom-manual "(message)Message Headers")
217   :type 'regexp)
218
219 (defcustom message-subject-trailing-was-regexp
220   "[ \t]*\\((*[Ww][Aa][Ss]:[ \t]*.*)\\)"
221   "*Regexp matching \"(was: <old subject>)\" in the subject line.
222
223 If `message-subject-trailing-was-query' is set to t, the subject is
224 matched against `message-subject-trailing-was-regexp' in
225 `message-strip-subject-trailing-was'.  You should use a regexp creating very
226 few false positives here."
227   :version "22.1"
228   :group 'message-various
229   :link '(custom-manual "(message)Message Headers")
230   :type 'regexp)
231
232 ;;; marking inserted text
233
234 (defcustom message-mark-insert-begin
235   "--8<---------------cut here---------------start------------->8---\n"
236   "How to mark the beginning of some inserted text."
237   :version "22.1"
238   :type 'string
239   :link '(custom-manual "(message)Insertion Variables")
240   :group 'message-various)
241
242 (defcustom message-mark-insert-end
243   "--8<---------------cut here---------------end--------------->8---\n"
244   "How to mark the end of some inserted text."
245   :version "22.1"
246   :type 'string
247   :link '(custom-manual "(message)Insertion Variables")
248   :group 'message-various)
249
250 (defcustom message-archive-header "X-No-Archive: Yes\n"
251   "Header to insert when you don't want your article to be archived.
252 Archives \(such as groups.google.com\) respect this header."
253   :version "22.1"
254   :type 'string
255   :link '(custom-manual "(message)Header Commands")
256   :group 'message-various)
257
258 (defcustom message-archive-note
259   "X-No-Archive: Yes - save http://groups.google.com/"
260   "Note to insert why you wouldn't want this posting archived.
261 If nil, don't insert any text in the body."
262   :version "22.1"
263   :type '(radio string (const nil))
264   :link '(custom-manual "(message)Header Commands")
265   :group 'message-various)
266
267 ;;; Crossposts and Followups
268 ;; inspired by JoH-followup-to by Jochem Huhman <joh  at gmx.de>
269 ;; new suggestions by R. Weikusat <rw at another.de>
270
271 (defvar message-cross-post-old-target nil
272   "Old target for cross-posts or follow-ups.")
273 (make-variable-buffer-local 'message-cross-post-old-target)
274
275 (defcustom message-cross-post-default t
276   "When non-nil `message-cross-post-followup-to' will perform a crosspost.
277 If nil, `message-cross-post-followup-to' will only do a followup.  Note that
278 you can explicitly override this setting by calling
279 `message-cross-post-followup-to' with a prefix."
280   :version "22.1"
281   :type 'boolean
282   :group 'message-various)
283
284 (defcustom message-cross-post-note "Crosspost & Followup-To: "
285   "Note to insert before signature to notify of xpost and follow-up."
286   :version "22.1"
287   :type 'string
288   :group 'message-various)
289
290 (defcustom message-followup-to-note "Followup-To: "
291   "Note to insert before signature to notify of follow-up only."
292   :version "22.1"
293   :type 'string
294   :group 'message-various)
295
296 (defcustom message-cross-post-note-function 'message-cross-post-insert-note
297   "Function to use to insert note about Crosspost or Followup-To.
298 The function will be called with four arguments.  The function should not only
299 insert a note, but also ensure old notes are deleted.  See the documentation
300 for `message-cross-post-insert-note'."
301   :version "22.1"
302   :type 'function
303   :group 'message-various)
304
305 ;;; End of variables adopted from `message-utils.el'.
306
307 ;;;###autoload
308 (defcustom message-from-style 'default
309   "*Specifies how \"From\" headers look.
310
311 If nil, they contain just the return address like:
312         king@grassland.com
313 If `parens', they look like:
314         king@grassland.com (Elvis Parsley)
315 If `angles', they look like:
316         Elvis Parsley <king@grassland.com>
317
318 Otherwise, most addresses look like `angles', but they look like
319 `parens' if `angles' would need quoting and `parens' would not."
320   :type '(choice (const :tag "simple" nil)
321                  (const parens)
322                  (const angles)
323                  (const default))
324   :group 'message-headers)
325
326 (defcustom message-insert-canlock t
327   "Whether to insert a Cancel-Lock header in news postings."
328   :version "22.1"
329   :group 'message-headers
330   :type 'boolean)
331
332 (defcustom message-syntax-checks
333   (if message-insert-canlock '((sender . disabled)) nil)
334   ;; Guess this one shouldn't be easy to customize...
335   "*Controls what syntax checks should not be performed on outgoing posts.
336 To disable checking of long signatures, for instance, add
337  `(signature . disabled)' to this list.
338
339 Don't touch this variable unless you really know what you're doing.
340
341 Checks include `subject-cmsg', `multiple-headers', `sendsys',
342 `message-id', `from', `long-lines', `control-chars', `size',
343 `new-text', `quoting-style', `redirected-followup', `signature',
344 `approved', `sender', `empty', `empty-headers', `message-id', `from',
345 `subject', `shorten-followup-to', `existing-newsgroups',
346 `buffer-file-name', `unchanged', `newsgroups', `reply-to',
347 `continuation-headers', `long-header-lines', `invisible-text' and
348 `illegible-text'."
349   :group 'message-news
350   :type '(repeat sexp))                 ; Fixme: improve this
351
352 (defcustom message-required-headers '((optional . References)
353                                       From)
354   "*Headers to be generated or prompted for when sending a message.
355 Also see `message-required-news-headers' and
356 `message-required-mail-headers'."
357   :version "22.1"
358   :group 'message-news
359   :group 'message-headers
360   :link '(custom-manual "(message)Message Headers")
361   :type '(repeat sexp))
362
363 (defcustom message-draft-headers '(References From)
364   "*Headers to be generated when saving a draft message."
365   :version "22.1"
366   :group 'message-news
367   :group 'message-headers
368   :link '(custom-manual "(message)Message Headers")
369   :type '(repeat sexp))
370
371 (defcustom message-required-news-headers
372   '(From Newsgroups Subject Date Message-ID
373          (optional . Organization)
374          (optional . User-Agent))
375   "*Headers to be generated or prompted for when posting an article.
376 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
377 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
378 User-Agent are optional.  If don't you want message to insert some
379 header, remove it from this list."
380   :group 'message-news
381   :group 'message-headers
382   :link '(custom-manual "(message)Message Headers")
383   :type '(repeat sexp))
384
385 (defcustom message-required-mail-headers
386   '(From Subject Date (optional . In-Reply-To) Message-ID
387          (optional . User-Agent))
388   "*Headers to be generated or prompted for when mailing a message.
389 It is recommended that From, Date, To, Subject and Message-ID be
390 included.  Organization and User-Agent are optional."
391   :group 'message-mail
392   :group 'message-headers
393   :link '(custom-manual "(message)Message Headers")
394   :type '(repeat sexp))
395
396 (defcustom message-deletable-headers '(Message-ID Date Lines)
397   "Headers to be deleted if they already exist and were generated by message previously."
398   :group 'message-headers
399   :link '(custom-manual "(message)Message Headers")
400   :type 'sexp)
401
402 (defcustom message-ignored-news-headers
403   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
404   "*Regexp of headers to be removed unconditionally before posting."
405   :group 'message-news
406   :group 'message-headers
407   :link '(custom-manual "(message)Message Headers")
408   :type '(repeat :value-to-internal (lambda (widget value)
409                                       (custom-split-regexp-maybe value))
410                  :match (lambda (widget value)
411                           (or (stringp value)
412                               (widget-editable-list-match widget value)))
413                  regexp))
414
415 (defcustom message-ignored-mail-headers
416   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:\\|^X-Gnus-Agent-Meta-Information:"
417   "*Regexp of headers to be removed unconditionally before mailing."
418   :group 'message-mail
419   :group 'message-headers
420   :link '(custom-manual "(message)Mail Headers")
421   :type 'regexp)
422
423 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:\\|^Cancel-Lock:\\|^Cancel-Key:\\|^X-Hashcash:\\|^X-Payment:\\|^Approved:"
424   "*Header lines matching this regexp will be deleted before posting.
425 It's best to delete old Path and Date headers before posting to avoid
426 any confusion."
427   :group 'message-interface
428   :link '(custom-manual "(message)Superseding")
429   :type '(repeat :value-to-internal (lambda (widget value)
430                                       (custom-split-regexp-maybe value))
431                  :match (lambda (widget value)
432                           (or (stringp value)
433                               (widget-editable-list-match widget value)))
434                  regexp))
435
436 (defcustom message-supersede-setup-function
437   'message-supersede-setup-for-mime-edit
438   "Function to setup a supersede message."
439   :group 'message-sending
440   :type 'function)
441
442 (defcustom message-subject-re-regexp
443   "^[ \t]*\\([Rr][Ee]\\(\\[[0-9]*\\]\\)*:[ \t]*\\)*[ \t]*"
444   "*Regexp matching \"Re: \" in the subject line."
445   :group 'message-various
446   :link '(custom-manual "(message)Message Headers")
447   :type 'regexp)
448
449 ;;; Some sender agents encode the whole subject including leading "Re: ".
450 ;;; And if followup agent does not decode it for some reason (e.g. unknown
451 ;;; charset) and just add a new "Re: " in front of the encoded-word, the
452 ;;; result will contain multiple "Re: "'s.
453 (defcustom message-subject-encoded-re-regexp
454   (concat
455    "^[ \t]*"
456    (regexp-quote "=?")
457    "[-!#$%&'*+0-9A-Z^_`a-z{|}~]+" ; charset
458    (regexp-quote "?")
459    "\\("
460    "[Bb]" (regexp-quote "?") ; B encoding
461    "\\(\\(CQk\\|CSA\\|IAk\\|ICA\\)[Jg]\\)*" ; \([ \t][ \t][ \t]\)*
462    "\\("
463    "[Uc][km]U6" ; [Rr][Ee]:
464    "\\|"
465    "\\(C[VX]\\|I[FH]\\)J[Fl]O[g-v]" ; [ \t][Rr][Ee]:
466    "\\|"
467    "\\(CQl\\|CSB\\|IAl\\|ICB\\)[Sy][RZ]T[o-r]" ; [ \t][ \t][Rr][Ee]:
468    "\\)"
469    "\\|"
470    "[Qb]" (regexp-quote "?") ; Q encoding
471    "\\(_\\|=09\\|=20\\)*"
472    "\\([Rr]\\|=[57]2\\)\\([Ee]\\|=[46]5\\)\\(:\\|=3[Aa]\\)"
473    "\\)"
474    )
475   "*Regexp matching \"Re: \" in the subject line.
476 Unlike `message-subject-re-regexp', this regexp matches \"Re: \" within
477 an encoded-word."
478   :group 'message-various
479   :link '(custom-manual "(message)Message Headers")
480   :type 'regexp)
481
482 (defcustom message-use-subject-re t
483   "*If t, remove any (buggy) \"Re: \"'s from the subject of the precursor
484 and add a new \"Re: \".  If it is nil, use the subject \"as-is\".  If it
485 is the symbol `guess', try to detect \"Re: \" within an encoded-word."
486   :group 'message-various
487   :type '(choice (const :tag "off" nil)
488                  (const :tag "on" t)
489                  (const guess)))
490
491 ;;;###autoload
492 (defcustom message-signature-separator "^-- *$"
493   "Regexp matching the signature separator."
494   :type 'regexp
495   :link '(custom-manual "(message)Various Message Variables")
496   :group 'message-various)
497
498 (defcustom message-signature-separator-for-insertion "-- \n"
499   "*Signature separator. This value will be inserted as signature separator
500 when composing message. Default value is \"-- \\n\". Notice: Changing this
501 value may go against RFC-1036 and draft-ietf-usefor-article-05.txt. "
502   :type 'string
503   :group 'message-insertion)
504
505 (defcustom message-elide-ellipsis "\n[...]\n\n"
506   "*The string which is inserted for elided text."
507   :type 'string
508   :link '(custom-manual "(message)Insertion Variables")
509   :group 'message-various)
510
511 (defcustom message-interactive t
512   "Non-nil means when sending a message wait for and display errors.
513 nil means let mailer mail back a message to report errors."
514   :group 'message-sending
515   :group 'message-mail
516   :link '(custom-manual "(message)Sending Variables")
517   :type 'boolean)
518
519 (defcustom message-generate-new-buffers 'unique
520   "*Non-nil means create a new message buffer whenever `message-setup' is called.
521 If this is a function, call that function with three parameters:  The type,
522 the to address and the group name.  (Any of these may be nil.)  The function
523 should return the new buffer name."
524   :group 'message-buffers
525   :link '(custom-manual "(message)Message Buffers")
526   :type '(choice (const :tag "off" nil)
527                  (const :tag "unique" unique)
528                  (const :tag "unsent" unsent)
529                  (function fun)))
530
531 (defcustom message-kill-buffer-on-exit nil
532   "*Non-nil means that the message buffer will be killed after sending a message."
533   :group 'message-buffers
534   :link '(custom-manual "(message)Message Buffers")
535   :type 'boolean)
536
537 (defcustom message-kill-buffer-query-function 'yes-or-no-p
538   "*Function used to prompt user whether to kill the message buffer.
539 If it is t, the buffer will be killed unconditionally."
540   :type '(radio (function-item yes-or-no-p)
541                 (function-item y-or-n-p)
542                 (function-item nnheader-Y-or-n-p)
543                 (function :tag "Other" t))
544   :group 'message-buffers)
545
546 (defcustom message-kill-buffer-and-remove-file t
547   "*Non-nil means that the associated file will be removed before
548 removing the message buffer.  However, it is treated as nil when the
549 command `message-mimic-kill-buffer' is used."
550   :group 'message-buffers
551   :type 'boolean)
552
553 (defcustom message-kill-buffer-query t
554   "*Non-nil means that killing a modified message buffer has to be confirmed.
555 This is used by `message-kill-buffer'."
556   :version "23.0" ;; No Gnus
557   :group 'message-buffers
558   :type 'boolean)
559
560 (eval-when-compile
561   (defvar gnus-local-organization))
562 (defcustom message-user-organization
563   (or (and (boundp 'gnus-local-organization)
564            (stringp gnus-local-organization)
565            gnus-local-organization)
566       (getenv "ORGANIZATION")
567       t)
568   "*String to be used as an Organization header.
569 If t, use `message-user-organization-file'."
570   :group 'message-headers
571   :type '(choice string
572                  (const :tag "consult file" t)))
573
574 ;;;###autoload
575 (defcustom message-user-organization-file "/usr/lib/news/organization"
576   "*Local news organization file."
577   :type 'file
578   :link '(custom-manual "(message)News Headers")
579   :group 'message-headers)
580
581 (defcustom message-forward-start-separator
582   (concat (mime-make-tag "message" "rfc822") "\n")
583   "*Delimiter inserted before forwarded messages."
584   :group 'message-forwarding
585   :type 'string)
586
587 (defcustom message-forward-end-separator
588   (concat (mime-make-tag "text" "plain") "\n")
589   "*Delimiter inserted after forwarded messages."
590   :group 'message-forwarding
591   :type 'string)
592
593 (defcustom message-included-forward-headers
594   "^From:\\|^Newsgroups:\\|^Subject:\\|^Date:\\|^\\(Mail-\\)?Followup-To:\\|^\\(Mail-\\)?Reply-To:\\|^Mail-Copies-To:\\|^Organization:\\|^Summary:\\|^Keywords:\\|^To:\\|^Cc:\\|^Posted-To:\\|^Apparently-To:\\|^Gnus-Warning:\\|^Resent-\\|^Message-ID:\\|^References:\\|^Content-\\|^MIME-Version:"
595   "*Regexp matching headers to be included in forwarded messages."
596   :group 'message-forwarding
597   :type 'regexp)
598
599 (defcustom message-make-forward-subject-function
600   #'message-forward-subject-name-subject
601   "*List of functions called to generate subject headers for forwarded messages.
602 The subject generated by the previous function is passed into each
603 successive function.
604
605 The provided functions are:
606
607 * `message-forward-subject-author-subject' Source of article (author or
608       newsgroup), in brackets followed by the subject
609 * `message-forward-subject-name-subject' Source of article (name of author
610       or newsgroup), in brackets followed by the subject
611 * `message-forward-subject-fwd' Subject of article with 'Fwd:' prepended
612       to it."
613   :group 'message-forwarding
614   :link '(custom-manual "(message)Forwarding")
615   :type '(radio (function-item message-forward-subject-author-subject)
616                 (function-item message-forward-subject-fwd)
617                 (function-item message-forward-subject-name-subject)
618                 (repeat :tag "List of functions" function)))
619
620 (defcustom message-forward-as-mime t
621   "*Non-nil means forward messages as an inline/rfc822 MIME section.
622 Otherwise, directly inline the old message in the forwarded message."
623   :version "21.1"
624   :group 'message-forwarding
625   :link '(custom-manual "(message)Forwarding")
626   :type 'boolean)
627
628 (defcustom message-forward-show-mml 'best
629   "*Non-nil means show forwarded messages as MML (decoded from MIME).
630 Otherwise, forwarded messages are unchanged.
631 Can also be the symbol `best' to indicate that MML should be
632 used, except when it is a bad idea to use MML.  One example where
633 it is a bad idea is when forwarding a signed or encrypted
634 message, because converting MIME to MML would invalidate the
635 digital signature."
636   :version "21.1"
637   :group 'message-forwarding
638   :type '(choice (const :tag "use MML" t)
639                  (const :tag "don't use MML " nil)
640                  (const :tag "use MML when appropriate" best)))
641
642 (defcustom message-forward-before-signature t
643   "*Non-nil means put forwarded message before signature, else after."
644   :group 'message-forwarding
645   :type 'boolean)
646
647 (defcustom message-wash-forwarded-subjects nil
648   "*Non-nil means try to remove as much cruft as possible from the subject.
649 Done before generating the new subject of a forward."
650   :group 'message-forwarding
651   :link '(custom-manual "(message)Forwarding")
652   :type 'boolean)
653
654 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:\\|^>?From "
655   "*All headers that match this regexp will be deleted when resending a message."
656   :group 'message-interface
657   :link '(custom-manual "(message)Resending")
658   :type '(repeat :value-to-internal (lambda (widget value)
659                                       (custom-split-regexp-maybe value))
660                  :match (lambda (widget value)
661                           (or (stringp value)
662                               (widget-editable-list-match widget value)))
663                  regexp))
664
665 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
666   "*All headers that match this regexp will be deleted when forwarding a message."
667   :version "21.1"
668   :group 'message-forwarding
669   :type '(repeat :value-to-internal (lambda (widget value)
670                                       (custom-split-regexp-maybe value))
671                  :match (lambda (widget value)
672                           (or (stringp value)
673                               (widget-editable-list-match widget value)))
674                  regexp))
675
676 (defcustom message-ignored-cited-headers "."
677   "*Delete these headers from the messages you yank."
678   :group 'message-insertion
679   :link '(custom-manual "(message)Insertion Variables")
680   :type 'regexp)
681
682 (defcustom message-cite-prefix-regexp
683   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
684       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>|}+]\\)+"
685     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
686     (let (non-word-constituents)
687       (with-syntax-table text-mode-syntax-table
688         (setq non-word-constituents
689               (concat
690                (if (string-match "\\w" "-")  "" "-")
691                (if (string-match "\\w" "_")  "" "_")
692                (if (string-match "\\w" ".")  "" "."))))
693       (if (equal non-word-constituents "")
694           "\\([ \t]*\\(\\w\\)+>+\\|[ \t]*[]>|}+]\\)+"
695         (concat "\\([ \t]*\\(\\w\\|["
696                 non-word-constituents
697                 "]\\)+>+\\|[ \t]*[]>|}+]\\)+"))))
698   "*Regexp matching the longest possible citation prefix on a line."
699   :version "22.1"
700   :group 'message-insertion
701   :link '(custom-manual "(message)Insertion Variables")
702   :type 'regexp)
703
704 (defcustom message-cancel-message "I am canceling my own article.\n"
705   "Message to be inserted in the cancel message."
706   :group 'message-interface
707   :link '(custom-manual "(message)Canceling News")
708   :type 'string)
709
710 ;; Useful to set in site-init.el
711 ;;;###autoload
712 (defcustom message-send-mail-function
713   (let ((program (if (boundp 'sendmail-program)
714                      ;; see paths.el
715                      sendmail-program)))
716     (cond
717      ((and program
718            (string-match "/" program) ;; Skip path
719            (file-executable-p program))
720       'message-send-mail-with-sendmail)
721      ((and program
722            (executable-find program))
723       'message-send-mail-with-sendmail)
724      (t
725       'smtpmail-send-it)))
726   "Function to call to send the current buffer as mail.
727 The headers should be delimited by a line whose contents match the
728 variable `mail-header-separator'.
729
730 Valid values include `message-send-mail-with-sendmail' (the default),
731 `message-send-mail-with-mh', `message-send-mail-with-qmail',
732 `message-send-mail-with-smtp', `message-smtpmail-send-it',
733 `smtpmail-send-it' and `feedmail-send-it'.
734
735 See also `send-mail-function'."
736   :type '(radio (function-item message-send-mail-with-sendmail)
737                 (function-item message-send-mail-with-mh)
738                 (function-item message-send-mail-with-qmail)
739                 (function-item message-send-mail-with-smtp)
740                 (function-item message-smtpmail-send-it)
741                 (function-item smtpmail-send-it)
742                 (function-item feedmail-send-it)
743                 (function :tag "Other"))
744   :group 'message-sending
745   :link '(custom-manual "(message)Mail Variables")
746   :group 'message-mail)
747
748 ;; 1997-09-29 by MORIOKA Tomohiko
749 (defcustom message-send-news-function 'message-send-news-with-gnus
750   "Function to call to send the current buffer as news.
751 The headers should be delimited by a line whose contents match the
752 variable `mail-header-separator'."
753   :group 'message-sending
754   :group 'message-news
755   :link '(custom-manual "(message)News Variables")
756   :type 'function)
757
758 (defcustom message-reply-to-function nil
759   "If non-nil, function that should return a list of headers.
760 This function should pick out addresses from the To, Cc, and From headers
761 and respond with new To and Cc headers."
762   :group 'message-interface
763   :link '(custom-manual "(message)Reply")
764   :type '(choice function (const nil)))
765
766 (defcustom message-wide-reply-to-function nil
767   "If non-nil, function that should return a list of headers.
768 This function should pick out addresses from the To, Cc, and From headers
769 and respond with new To and Cc headers."
770   :group 'message-interface
771   :link '(custom-manual "(message)Wide Reply")
772   :type '(choice function (const nil)))
773
774 (defcustom message-followup-to-function nil
775   "If non-nil, function that should return a list of headers.
776 This function should pick out addresses from the To, Cc, and From headers
777 and respond with new To and Cc headers."
778   :group 'message-interface
779   :link '(custom-manual "(message)Followup")
780   :type '(choice function (const nil)))
781
782 (defcustom message-extra-wide-headers nil
783   "If non-nil, a list of additional address headers.
784 These are used when composing a wide reply."
785   :group 'message-sending
786   :type '(repeat string))
787
788 (defcustom message-use-followup-to 'ask
789   "*Specifies what to do with Followup-To header.
790 If nil, always ignore the header.  If it is t, use its value, but
791 query before using the \"poster\" value.  If it is the symbol `ask',
792 always query the user whether to use the value.  If it is the symbol
793 `use', always use the value."
794   :group 'message-interface
795   :link '(custom-manual "(message)Followup")
796   :type '(choice (const :tag "ignore" nil)
797                  (const :tag "use & query" t)
798                  (const :tag "maybe" t)
799                  (const :tag "always" use)
800                  (const :tag "ask" ask)))
801
802 (defcustom message-use-mail-copies-to 'ask
803   "*Specifies what to do with Mail-Copies-To header.
804 If nil, always ignore the header.  If it is t, use its value, but
805 query before using the value other than \"always\" or \"never\".
806 If it is the symbol `ask', always query the user whether to use
807 the value.  If it is the symbol `use', always use the value."
808   :group 'message-interface
809   :link '(custom-manual "(message)Mailing Lists")
810   :type '(choice (const :tag "ignore" nil)
811                  (const :tag "maybe" t)
812                  (const :tag "always" use)
813                  (const :tag "ask" ask)))
814
815 ;;; XXX: 'ask and 'use are not implemented yet.
816 (defcustom message-use-mail-reply-to 'ask
817   "*Specifies what to do with Mail-Reply-To/Reply-To header.
818 If nil, always ignore the header.  If it is t or the symbol `use', use
819 its value.  If it is the symbol `ask', always query the user whether to
820 use the value.  Note that if \"Reply-To\" is marked as \"broken\", its value
821 is never used."
822   :group 'message-interface
823   :type '(choice (const :tag "ignore" nil)
824                  (const :tag "maybe" t)
825                  (const :tag "always" use)
826                  (const :tag "ask" ask)))
827
828 (defcustom message-use-mail-followup-to 'use
829   "*Specifies what to do with Mail-Followup-To header.
830 If nil, always ignore the header.  If it is the symbol `ask', always
831 query the user whether to use the value.  If it is t or the symbol
832 `use', always use the value."
833   :version "22.1"
834   :group 'message-interface
835   :type '(choice (const :tag "ignore" nil)
836                  (const :tag "maybe" t)
837                  (const :tag "always" use)
838                  (const :tag "ask" ask)))
839
840 (defcustom message-subscribed-address-functions nil
841   "*Specifies functions for determining list subscription.
842 If nil, do not attempt to determine list subscription with functions.
843 If non-nil, this variable contains a list of functions which return
844 regular expressions to match lists.  These functions can be used in
845 conjunction with `message-subscribed-regexps' and
846 `message-subscribed-addresses'."
847   :version "22.1"
848   :group 'message-interface
849   :link '(custom-manual "(message)Mailing Lists")
850   :type '(repeat sexp))
851
852 (defcustom message-subscribed-address-file nil
853   "*A file containing addresses the user is subscribed to.
854 If nil, do not look at any files to determine list subscriptions.  If
855 non-nil, each line of this file should be a mailing list address."
856   :version "22.1"
857   :group 'message-interface
858   :link '(custom-manual "(message)Mailing Lists")
859   :type '(radio file (const nil)))
860
861 (defcustom message-subscribed-addresses nil
862   "*Specifies a list of addresses the user is subscribed to.
863 If nil, do not use any predefined list subscriptions.  This list of
864 addresses can be used in conjunction with
865 `message-subscribed-address-functions' and `message-subscribed-regexps'."
866   :version "22.1"
867   :group 'message-interface
868   :link '(custom-manual "(message)Mailing Lists")
869   :type '(repeat string))
870
871 (defcustom message-subscribed-regexps nil
872   "*Specifies a list of addresses the user is subscribed to.
873 If nil, do not use any predefined list subscriptions.  This list of
874 regular expressions can be used in conjunction with
875 `message-subscribed-address-functions' and `message-subscribed-addresses'."
876   :version "22.1"
877   :group 'message-interface
878   :link '(custom-manual "(message)Mailing Lists")
879   :type '(repeat regexp))
880
881 (defcustom message-allow-no-recipients 'ask
882   "Specifies what to do when there are no recipients other than Gcc/Fcc.
883 If it is the symbol `always', the posting is allowed.  If it is the
884 symbol `never', the posting is not allowed.  If it is the symbol
885 `ask', you are prompted."
886   :version "22.1"
887   :group 'message-interface
888   :link '(custom-manual "(message)Message Headers")
889   :type '(choice (const always)
890                  (const never)
891                  (const ask)))
892
893 (defcustom message-sendmail-f-is-evil nil
894   "*Non-nil means don't add \"-f username\" to the sendmail command line.
895 Doing so would be even more evil than leaving it out."
896   :group 'message-sending
897   :link '(custom-manual "(message)Mail Variables")
898   :type 'boolean)
899
900 (defcustom message-sendmail-envelope-from nil
901   "*Envelope-from when sending mail with sendmail.
902 If this is nil, use `user-mail-address'.  If it is the symbol
903 `header', use the From: header of the message."
904   :version "22.1"
905   :type '(choice (string :tag "From name")
906                  (const :tag "Use From: header from message" header)
907                  (const :tag "Use `user-mail-address'" nil))
908   :link '(custom-manual "(message)Mail Variables")
909   :group 'message-sending)
910
911 ;; qmail-related stuff
912 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
913   "Location of the qmail-inject program."
914   :group 'message-sending
915   :link '(custom-manual "(message)Mail Variables")
916   :type 'file)
917
918 (defcustom message-qmail-inject-args nil
919   "Arguments passed to qmail-inject programs.
920 This should be a list of strings, one string for each argument.  It
921 may also be a function.
922
923 For e.g., if you wish to set the envelope sender address so that bounces
924 go to the right place or to deal with listserv's usage of that address, you
925 might set this variable to '(\"-f\" \"you@some.where\")."
926   :group 'message-sending
927   :link '(custom-manual "(message)Mail Variables")
928   :type '(choice (function)
929                  (repeat string)))
930
931 (eval-when-compile
932   (defvar gnus-post-method)
933   (defvar gnus-select-method))
934 (defcustom message-post-method
935   (cond ((and (boundp 'gnus-post-method)
936               (listp gnus-post-method)
937               gnus-post-method)
938          gnus-post-method)
939         ((boundp 'gnus-select-method)
940          gnus-select-method)
941         (t '(nnspool "")))
942   "*Method used to post news.
943 Note that when posting from inside Gnus, for instance, this
944 variable isn't used."
945   :group 'message-news
946   :group 'message-sending
947   ;; This should be the `gnus-select-method' widget, but that might
948   ;; create a dependence to `gnus.el'.
949   :type 'sexp)
950
951 ;; FIXME: This should be a temporary workaround until someone implements a
952 ;; proper solution.  If a crash happens while replying, the auto-save file
953 ;; will *not* have a `References:' header if `message-generate-headers-first'
954 ;; is nil.  See: http://article.gmane.org/gmane.emacs.gnus.general/51138
955 (defcustom message-generate-headers-first '(references)
956   "Which headers should be generated before starting to compose a message.
957 If t, generate all required headers.  This can also be a list of headers to
958 generate.  The variables `message-required-news-headers' and
959 `message-required-mail-headers' specify which headers to generate.
960
961 Note that the variable `message-deletable-headers' specifies headers which
962 are to be deleted and then re-generated before sending, so this variable
963 will not have a visible effect for those headers."
964   :group 'message-headers
965   :link '(custom-manual "(message)Message Headers")
966   :type '(choice (const :tag "None" nil)
967                  (const :tag "References" '(references))
968                  (const :tag "All" t)
969                  (repeat (sexp :tag "Header"))))
970
971 (defcustom message-setup-hook '(turn-on-mime-edit)
972   "Normal hook, run each time a new outgoing message is initialized.
973 The function `message-setup' runs this hook."
974   :group 'message-various
975   :link '(custom-manual "(message)Various Message Variables")
976   :type 'hook)
977
978 (defcustom message-cancel-hook nil
979   "Hook run when cancelling articles."
980   :group 'message-various
981   :link '(custom-manual "(message)Various Message Variables")
982   :type 'hook)
983
984 (defcustom message-signature-setup-hook nil
985   "Normal hook, run each time a new outgoing message is initialized.
986 It is run after the headers have been inserted and before
987 the signature is inserted."
988   :group 'message-various
989   :link '(custom-manual "(message)Various Message Variables")
990   :type 'hook)
991
992 (defcustom message-bounce-setup-hook nil
993   "Normal hook, run each time a re-sending bounced message is initialized.
994 The function `message-bounce' runs this hook."
995   :group 'message-various
996   :type 'hook)
997
998 (defcustom message-supersede-setup-hook nil
999   "Normal hook, run each time a supersede message is initialized.
1000 The function `message-supersede' runs this hook."
1001   :group 'message-various
1002   :type 'hook)
1003
1004 (defcustom message-mode-hook nil
1005   "Hook run in message mode buffers."
1006   :group 'message-various
1007   :type 'hook)
1008
1009 (defcustom message-header-hook '((lambda () (mime-encode-header-in-buffer t)))
1010   "Hook run in a message mode buffer narrowed to the headers."
1011   :group 'message-various
1012   :type 'hook)
1013
1014 (defcustom message-header-setup-hook nil
1015   "Hook called narrowed to the headers when setting up a message buffer."
1016   :group 'message-various
1017   :link '(custom-manual "(message)Various Message Variables")
1018   :type 'hook)
1019
1020 (defcustom message-minibuffer-local-map
1021   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
1022     (set-keymap-parent map minibuffer-local-map)
1023     map)
1024   "Keymap for `message-read-from-minibuffer'."
1025   :version "22.1"
1026   :group 'message-various)
1027
1028 ;;;###autoload
1029 (defcustom message-citation-line-function 'message-insert-citation-line
1030   "*Function called to insert the \"Whomever writes:\" line.
1031
1032 Note that Gnus provides a feature where the reader can click on
1033 `writes:' to hide the cited text.  If you change this line too much,
1034 people who read your message will have to change their Gnus
1035 configuration.  See the variable `gnus-cite-attribution-suffix'."
1036   :type 'function
1037   :link '(custom-manual "(message)Insertion Variables")
1038   :group 'message-insertion)
1039
1040 ;;;###autoload
1041 (defcustom message-yank-prefix "> "
1042   "*Prefix inserted on the lines of yanked messages.
1043 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
1044 See also `message-yank-cited-prefix' and `message-yank-empty-prefix'."
1045   :type 'string
1046   :link '(custom-manual "(message)Insertion Variables")
1047   :group 'message-insertion)
1048
1049 (defcustom message-yank-cited-prefix ">"
1050   "*Prefix inserted on cited lines of yanked messages.
1051 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
1052 See also `message-yank-prefix' and `message-yank-empty-prefix'."
1053   :version "22.1"
1054   :type 'string
1055   :link '(custom-manual "(message)Insertion Variables")
1056   :group 'message-insertion)
1057
1058 (defcustom message-yank-empty-prefix ">"
1059   "*Prefix inserted on empty lines of yanked messages.
1060 See also `message-yank-prefix' and `message-yank-cited-prefix'."
1061   :version "22.1"
1062   :type 'string
1063   :link '(custom-manual "(message)Insertion Variables")
1064   :group 'message-insertion)
1065
1066 (defcustom message-indentation-spaces 3
1067   "*Number of spaces to insert at the beginning of each cited line.
1068 Used by `message-yank-original' via `message-yank-cite'."
1069   :group 'message-insertion
1070   :link '(custom-manual "(message)Insertion Variables")
1071   :type 'integer)
1072
1073 ;;;###autoload
1074 (defcustom message-cite-function 'message-cite-original
1075   "*Function for citing an original message.
1076 Predefined functions include `message-cite-original' and
1077 `message-cite-original-without-signature'.
1078 Note that these functions use `mail-citation-hook' if that is non-nil."
1079   :type '(radio (function-item message-cite-original)
1080                 (function-item message-cite-original-without-signature)
1081                 (function-item mu-cite-original)
1082                 (function-item sc-cite-original)
1083                 (function :tag "Other"))
1084   :link '(custom-manual "(message)Insertion Variables")
1085   :group 'message-insertion)
1086
1087 ;;;###autoload
1088 (defcustom message-indent-citation-function 'message-indent-citation
1089   "*Function for modifying a citation just inserted in the mail buffer.
1090 This can also be a list of functions.  Each function can find the
1091 citation between (point) and (mark t).  And each function should leave
1092 point and mark around the citation text as modified."
1093   :type 'function
1094   :link '(custom-manual "(message)Insertion Variables")
1095   :group 'message-insertion)
1096
1097 ;;;###autoload
1098 (defcustom message-suspend-font-lock-when-citing nil
1099   "Non-nil means suspend font-lock'ing while citing an original message.
1100 Some lazy demand-driven fontification tools (or Emacs itself) have a
1101 bug that they often miss a buffer to be fontified.  It will mostly
1102 occur when Emacs prompts user for any inputs in the minibuffer.
1103 Setting this option to non-nil may help you to avoid unpleasant errors
1104 even if it is an add-hoc expedient."
1105   :type 'boolean
1106   :group 'message-insertion)
1107
1108 (defcustom message-yank-add-new-references t
1109   "Non-nil means new IDs will be added to \"References\" field when an
1110 article is yanked by the command `message-yank-original' interactively.
1111 If it is a symbol `message-id-only', only an ID from \"Message-ID\" field
1112 is used, otherwise IDs extracted from \"References\", \"In-Reply-To\" and
1113 \"Message-ID\" fields are used."
1114   :type '(radio
1115           (const :tag "Do not add anything" nil)
1116           (const :tag "From Message-Id, References and In-Reply-To fields" t)
1117           (const :tag "From only Message-Id field." message-id-only))
1118   :group 'message-insertion)
1119
1120 (defcustom message-list-references-add-position nil
1121   "Integer value means position for adding to \"References\" field when
1122 an article is yanked by the command `message-yank-original' interactively."
1123   :type '(radio (const :tag "Add to last" nil)
1124                 (integer :tag "Position from last ID"))
1125   :group 'message-insertion)
1126
1127 ;;;###autoload
1128 (defcustom message-signature t
1129   "*String to be inserted at the end of the message buffer.
1130 If t, the `message-signature-file' file will be inserted instead.
1131 If a function, the result from the function will be used instead.
1132 If a form, the result from the form will be used instead."
1133   :type 'sexp
1134   :link '(custom-manual "(message)Insertion Variables")
1135   :group 'message-insertion)
1136
1137 ;;;###autoload
1138 (defcustom message-signature-file "~/.signature"
1139   "*Name of file containing the text inserted at end of message buffer.
1140 Ignored if the named file doesn't exist.
1141 If nil, don't insert a signature."
1142   :type '(choice file (const :tags "None" nil))
1143   :link '(custom-manual "(message)Insertion Variables")
1144   :group 'message-insertion)
1145
1146 ;;;###autoload
1147 (defcustom message-signature-insert-empty-line t
1148   "*If non-nil, insert an empty line before the signature separator."
1149   :version "22.1"
1150   :type 'boolean
1151   :link '(custom-manual "(message)Insertion Variables")
1152   :group 'message-insertion)
1153
1154 (defcustom message-distribution-function nil
1155   "*Function called to return a Distribution header."
1156   :group 'message-news
1157   :group 'message-headers
1158   :link '(custom-manual "(message)News Headers")
1159   :type '(choice function (const nil)))
1160
1161 (defcustom message-expires 14
1162   "Number of days before your article expires."
1163   :group 'message-news
1164   :group 'message-headers
1165   :link '(custom-manual "(message)News Headers")
1166   :type 'integer)
1167
1168 (defcustom message-user-path nil
1169   "If nil, use the NNTP server name in the Path header.
1170 If stringp, use this; if non-nil, use no host name (user name only)."
1171   :group 'message-news
1172   :group 'message-headers
1173   :link '(custom-manual "(message)News Headers")
1174   :type '(choice (const :tag "nntp" nil)
1175                  (string :tag "name")
1176                  (sexp :tag "none" :format "%t" t)))
1177
1178 (defvar message-reply-buffer nil)
1179 (defvar message-reply-headers nil
1180   "The headers of the current replied article.
1181 It is a vector of the following headers:
1182 \[number subject from date id references chars lines xref extra].")
1183 (defvar message-sent-message-via nil)
1184 (defvar message-checksum nil)
1185 (defvar message-send-actions nil
1186   "A list of actions to be performed upon successful sending of a message.")
1187 (defvar message-exit-actions nil
1188   "A list of actions to be performed upon exiting after sending a message.")
1189 (defvar message-kill-actions nil
1190   "A list of actions to be performed before killing a message buffer.")
1191 (defvar message-postpone-actions nil
1192   "A list of actions to be performed after postponing a message.")
1193 (defvar message-original-frame nil)
1194 (defvar message-parameter-alist nil)
1195 (defvar message-startup-parameter-alist nil)
1196
1197 (define-widget 'message-header-lines 'text
1198   "All header lines must be LFD terminated."
1199   :format "%{%t%}:%n%v"
1200   :valid-regexp "^\\'"
1201   :error "All header lines must be newline terminated")
1202
1203 (defcustom message-default-headers ""
1204   "*A string containing header lines to be inserted in outgoing messages.
1205 It is inserted before you edit the message, so you can edit or delete
1206 these lines."
1207   :group 'message-headers
1208   :link '(custom-manual "(message)Message Headers")
1209   :type 'message-header-lines)
1210
1211 (defcustom message-default-mail-headers ""
1212   "*A string of header lines to be inserted in outgoing mails."
1213   :group 'message-headers
1214   :group 'message-mail
1215   :link '(custom-manual "(message)Mail Headers")
1216   :type 'message-header-lines)
1217
1218 (defcustom message-default-news-headers ""
1219   "*A string of header lines to be inserted in outgoing news articles."
1220   :group 'message-headers
1221   :group 'message-news
1222   :link '(custom-manual "(message)News Headers")
1223   :type 'message-header-lines)
1224
1225 ;; Note: could use /usr/ucb/mail instead of sendmail;
1226 ;; options -t, and -v if not interactive.
1227 (defcustom message-mailer-swallows-blank-line
1228   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
1229                          system-configuration)
1230            (file-readable-p "/etc/sendmail.cf")
1231            (let ((buffer (get-buffer-create " *temp*")))
1232              (unwind-protect
1233                  (save-excursion
1234                    (set-buffer buffer)
1235                    (insert-file-contents "/etc/sendmail.cf")
1236                    (goto-char (point-min))
1237                    (let ((case-fold-search nil))
1238                      (re-search-forward "^OR\\>" nil t)))
1239                (kill-buffer buffer))))
1240       ;; According to RFC822, "The field-name must be composed of printable
1241       ;; ASCII characters (i. e., characters that have decimal values between
1242       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
1243       ;; space, or colon.
1244       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
1245   "*Set this non-nil if the system's mailer runs the header and body together.
1246 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
1247 The value should be an expression to test whether the problem will
1248 actually occur."
1249   :group 'message-sending
1250   :link '(custom-manual "(message)Mail Variables")
1251   :type 'sexp)
1252
1253 ;;; XXX: This symbol is overloaded!  See below.
1254 (defvar message-user-agent nil
1255   "String of the form of PRODUCT/VERSION.  Used for User-Agent header field.")
1256
1257 ;;;###autoload
1258 (define-mail-user-agent 'message-user-agent
1259   'message-mail 'message-send-and-exit
1260   'message-kill-buffer 'message-send-hook)
1261
1262 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
1263   "If non-nil, delete the deletable headers before feeding to mh.")
1264
1265 (defvar message-send-method-alist
1266   '((news message-news-p message-send-via-news)
1267     (mail message-mail-p message-send-via-mail))
1268   "Alist of ways to send outgoing messages.
1269 Each element has the form
1270
1271   \(TYPE PREDICATE FUNCTION)
1272
1273 where TYPE is a symbol that names the method; PREDICATE is a function
1274 called without any parameters to determine whether the message is
1275 a message of type TYPE; and FUNCTION is a function to be called if
1276 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
1277 the prefix.")
1278
1279 (defcustom message-mail-alias-type 'abbrev
1280   "*What alias expansion type to use in Message buffers.
1281 The default is `abbrev', which uses mailabbrev.  nil switches
1282 mail aliases off."
1283   :group 'message
1284   :link '(custom-manual "(message)Mail Aliases")
1285   :type '(choice (const :tag "Use Mailabbrev" abbrev)
1286                  (const :tag "No expansion" nil)))
1287
1288 (defcustom message-auto-save-directory
1289   (file-name-as-directory (nnheader-concat message-directory "drafts"))
1290   "*Directory where Message auto-saves buffers if Gnus isn't running.
1291 If nil, Message won't auto-save."
1292   :group 'message-buffers
1293   :link '(custom-manual "(message)Various Message Variables")
1294   :type '(choice directory (const :tag "Don't auto-save" nil)))
1295
1296 (defcustom message-default-charset
1297   (and (featurep 'xemacs) (not (featurep 'mule)) 'iso-8859-1)
1298   "Default charset used in non-MULE XEmacsen."
1299   :version "21.1"
1300   :group 'message
1301   :link '(custom-manual "(message)Various Message Variables")
1302   :type 'symbol)
1303
1304 (defcustom message-dont-reply-to-names
1305   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
1306   "*A regexp specifying addresses to prune when doing wide replies.
1307 A value of nil means exclude your own user name only."
1308   :version "21.1"
1309   :group 'message
1310   :link '(custom-manual "(message)Wide Reply")
1311   :type '(choice (const :tag "Yourself" nil)
1312                  regexp))
1313
1314 (defvar message-shoot-gnksa-feet nil
1315   "*A list of GNKSA feet you are allowed to shoot.
1316 Gnus gives you all the opportunity you could possibly want for
1317 shooting yourself in the foot.  Also, Gnus allows you to shoot the
1318 feet of Good Net-Keeping Seal of Approval.  The following are foot
1319 candidates:
1320 `empty-article'     Allow you to post an empty article;
1321 `quoted-text-only'  Allow you to post quoted text only;
1322 `multiple-copies'   Allow you to post multiple copies;
1323 `cancel-messages'   Allow you to cancel or supersede messages from
1324                     your other email addresses.")
1325
1326 (defsubst message-gnksa-enable-p (feature)
1327   (or (not (listp message-shoot-gnksa-feet))
1328       (memq feature message-shoot-gnksa-feet)))
1329
1330 (defcustom message-hidden-headers "^References:"
1331   "Regexp of headers to be hidden when composing new messages.
1332 This can also be a list of regexps to match headers.  Or a list
1333 starting with `not' and followed by regexps."
1334   :version "22.1"
1335   :group 'message
1336   :link '(custom-manual "(message)Message Headers")
1337   :type '(choice
1338           :format "%{%t%}: %[Value Type%] %v"
1339           (regexp :menu-tag "regexp" :format "regexp\n%t: %v")
1340           (repeat :menu-tag "(regexp ...)" :format "(regexp ...)\n%v%i"
1341                   (regexp :format "%t: %v"))
1342           (cons :menu-tag "(not regexp ...)" :format "(not regexp ...)\n%v"
1343                 (const not)
1344                 (repeat :format "%v%i"
1345                         (regexp :format "%t: %v")))))
1346
1347 (defcustom message-cite-articles-with-x-no-archive t
1348   "If non-nil, cite text from articles that has X-No-Archive set."
1349   :group 'message
1350   :type 'boolean)
1351
1352 ;;; Internal variables.
1353 ;;; Well, not really internal.
1354
1355 (defvar message-mode-syntax-table
1356   (let ((table (copy-syntax-table text-mode-syntax-table)))
1357     (modify-syntax-entry ?% ". " table)
1358     (modify-syntax-entry ?> ". " table)
1359     (modify-syntax-entry ?< ". " table)
1360     table)
1361   "Syntax table used while in Message mode.")
1362
1363 (defface message-header-to
1364   '((((class color)
1365       (background dark))
1366      (:foreground "green2" :bold t))
1367     (((class color)
1368       (background light))
1369      (:foreground "MidnightBlue" :bold t))
1370     (t
1371      (:bold t :italic t)))
1372   "Face used for displaying From headers."
1373   :group 'message-faces)
1374 ;; backward-compatibility alias
1375 (put 'message-header-to-face 'face-alias 'message-header-to)
1376
1377 (defface message-header-cc
1378   '((((class color)
1379       (background dark))
1380      (:foreground "green4" :bold t))
1381     (((class color)
1382       (background light))
1383      (:foreground "MidnightBlue"))
1384     (t
1385      (:bold t)))
1386   "Face used for displaying Cc headers."
1387   :group 'message-faces)
1388 ;; backward-compatibility alias
1389 (put 'message-header-cc-face 'face-alias 'message-header-cc)
1390
1391 (defface message-header-subject
1392   '((((class color)
1393       (background dark))
1394      (:foreground "green3"))
1395     (((class color)
1396       (background light))
1397      (:foreground "navy blue" :bold t))
1398     (t
1399      (:bold t)))
1400   "Face used for displaying subject headers."
1401   :group 'message-faces)
1402 ;; backward-compatibility alias
1403 (put 'message-header-subject-face 'face-alias 'message-header-subject)
1404
1405 (defface message-header-newsgroups
1406   '((((class color)
1407       (background dark))
1408      (:foreground "yellow" :bold t :italic t))
1409     (((class color)
1410       (background light))
1411      (:foreground "blue4" :bold t :italic t))
1412     (t
1413      (:bold t :italic t)))
1414   "Face used for displaying newsgroups headers."
1415   :group 'message-faces)
1416 ;; backward-compatibility alias
1417 (put 'message-header-newsgroups-face 'face-alias 'message-header-newsgroups)
1418
1419 (defface message-header-other
1420   '((((class color)
1421       (background dark))
1422      (:foreground "#b00000"))
1423     (((class color)
1424       (background light))
1425      (:foreground "steel blue"))
1426     (t
1427      (:bold t :italic t)))
1428   "Face used for displaying newsgroups headers."
1429   :group 'message-faces)
1430 ;; backward-compatibility alias
1431 (put 'message-header-other-face 'face-alias 'message-header-other)
1432
1433 (defface message-header-name
1434   '((((class color)
1435       (background dark))
1436      (:foreground "DarkGreen"))
1437     (((class color)
1438       (background light))
1439      (:foreground "cornflower blue"))
1440     (t
1441      (:bold t)))
1442   "Face used for displaying header names."
1443   :group 'message-faces)
1444 ;; backward-compatibility alias
1445 (put 'message-header-name-face 'face-alias 'message-header-name)
1446
1447 (defface message-header-xheader
1448   '((((class color)
1449       (background dark))
1450      (:foreground "blue"))
1451     (((class color)
1452       (background light))
1453      (:foreground "blue"))
1454     (t
1455      (:bold t)))
1456   "Face used for displaying X-Header headers."
1457   :group 'message-faces)
1458 ;; backward-compatibility alias
1459 (put 'message-header-xheader-face 'face-alias 'message-header-xheader)
1460
1461 (defface message-separator
1462   '((((class color)
1463       (background dark))
1464      (:foreground "blue3"))
1465     (((class color)
1466       (background light))
1467      (:foreground "brown"))
1468     (t
1469      (:bold t)))
1470   "Face used for displaying the separator."
1471   :group 'message-faces)
1472 ;; backward-compatibility alias
1473 (put 'message-separator-face 'face-alias 'message-separator)
1474
1475 (defface message-cited-text
1476   '((((class color)
1477       (background dark))
1478      (:foreground "red"))
1479     (((class color)
1480       (background light))
1481      (:foreground "red"))
1482     (t
1483      (:bold t)))
1484   "Face used for displaying cited text names."
1485   :group 'message-faces)
1486 ;; backward-compatibility alias
1487 (put 'message-cited-text-face 'face-alias 'message-cited-text)
1488
1489 (defface message-mml
1490   '((((class color)
1491       (background dark))
1492      (:foreground "ForestGreen"))
1493     (((class color)
1494       (background light))
1495      (:foreground "ForestGreen"))
1496     (t
1497      (:bold t)))
1498   "Face used for displaying MML."
1499   :group 'message-faces)
1500 ;; backward-compatibility alias
1501 (put 'message-mml-face 'face-alias 'message-mml)
1502
1503 (defun message-font-lock-make-header-matcher (regexp)
1504   (let ((form
1505          `(lambda (limit)
1506             (let ((start (point)))
1507               (save-restriction
1508                 (widen)
1509                 (goto-char (point-min))
1510                 (if (re-search-forward
1511                      (concat "^" (regexp-quote mail-header-separator) "$")
1512                      nil t)
1513                     (setq limit (min limit (match-beginning 0))))
1514                 (goto-char start))
1515               (and (< start limit)
1516                    (re-search-forward ,regexp limit t))))))
1517     (if (featurep 'bytecomp)
1518         (byte-compile form)
1519       form)))
1520
1521 (defvar message-font-lock-keywords
1522   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
1523     `((,(message-font-lock-make-header-matcher
1524          (concat "^\\([Tt]o:\\)" content))
1525        (1 'message-header-name)
1526        (2 'message-header-to nil t))
1527       (,(message-font-lock-make-header-matcher
1528          (concat "^\\([GBF]?[Cc][Cc]:\\|[Rr]eply-[Tt]o:\\|"
1529                  "[Mm]ail-[Cc]opies-[Tt]o:\\|"
1530                  "[Mm]ail-[Rr]eply-[Tt]o:\\|"
1531                  "[Mm]ail-[Ff]ollowup-[Tt]o:\\)" content))
1532        (1 'message-header-name)
1533        (2 'message-header-cc nil t))
1534       (,(message-font-lock-make-header-matcher
1535          (concat "^\\([Ss]ubject:\\)" content))
1536        (1 'message-header-name)
1537        (2 'message-header-subject nil t))
1538       (,(message-font-lock-make-header-matcher
1539          (concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content))
1540        (1 'message-header-name)
1541        (2 'message-header-newsgroups nil t))
1542       (,(message-font-lock-make-header-matcher
1543          (concat "^\\([A-Z][^: \n\t]+:\\)" content))
1544        (1 'message-header-name)
1545        (2 'message-header-other nil t))
1546       (,(message-font-lock-make-header-matcher
1547          (concat "^\\(X-[A-Za-z0-9-]+:\\|In-Reply-To:\\)" content))
1548        (1 'message-header-name)
1549        (2 'message-header-name))
1550       ,@(if (and mail-header-separator
1551                  (not (equal mail-header-separator "")))
1552             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
1553                1 'message-separator))
1554           nil)
1555       ((lambda (limit)
1556          (re-search-forward (concat "^\\("
1557                                     message-cite-prefix-regexp
1558                                     "\\).*")
1559                             limit t))
1560        (0 'message-cited-text))
1561       (,mime-edit-tag-regexp
1562        (0 'message-mml))))
1563   "Additional expressions to highlight in Message mode.")
1564
1565 ;; XEmacs does it like this.  For Emacs, we have to set the
1566 ;; `font-lock-defaults' buffer-local variable.
1567 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
1568
1569 (defvar message-face-alist
1570   '((bold . message-bold-region)
1571     (underline . underline-region)
1572     (default . (lambda (b e)
1573                  (message-unbold-region b e)
1574                  (ununderline-region b e))))
1575   "Alist of mail and news faces for facemenu.
1576 The cdr of each entry is a function for applying the face to a region.")
1577
1578 (defcustom message-send-hook nil
1579   "Hook run before sending messages.
1580 This hook is run quite early when sending."
1581   :group 'message-various
1582   :options '(ispell-message)
1583   :link '(custom-manual "(message)Various Message Variables")
1584   :type 'hook)
1585
1586 (defcustom message-send-mail-hook nil
1587   "Hook run before sending mail messages.
1588 This hook is run very late -- just before the message is sent as
1589 mail."
1590   :group 'message-various
1591   :link '(custom-manual "(message)Various Message Variables")
1592   :type 'hook)
1593
1594 (defcustom message-send-news-hook nil
1595   "Hook run before sending news messages.
1596 This hook is run very late -- just before the message is sent as
1597 news."
1598   :group 'message-various
1599   :link '(custom-manual "(message)Various Message Variables")
1600   :type 'hook)
1601
1602 (defcustom message-sent-hook nil
1603   "Hook run after sending messages."
1604   :group 'message-various
1605   :type 'hook)
1606
1607 (defcustom message-use-multi-frames nil
1608   "Make new frame when sending messages."
1609   :group 'message-frames
1610   :type 'boolean)
1611
1612 (defcustom message-delete-frame-on-exit nil
1613   "Delete frame after sending messages."
1614   :group 'message-frames
1615   :type '(choice (const :tag "off" nil)
1616                  (const :tag "always" t)
1617                  (const :tag "ask" ask)))
1618
1619 (defvar message-draft-coding-system
1620   nnheader-auto-save-coding-system
1621   "*Coding system to compose mail.
1622 If you'd like to make it possible to share draft files between XEmacs
1623 and Emacs, you may use `iso-2022-7bit' for this value at your own risk.
1624 Note that the coding-system `iso-2022-7bit' isn't suitable to all data.")
1625
1626 (defcustom message-send-mail-partially-limit 1000000
1627   "The limitation of messages sent as message/partial.
1628 The lower bound of message size in characters, beyond which the message
1629 should be sent in several parts.  If it is nil, the size is unlimited."
1630   :version "21.1"
1631   :group 'message-buffers
1632   :link '(custom-manual "(message)Mail Variables")
1633   :type '(choice (const :tag "unlimited" nil)
1634                  (integer 1000000)))
1635
1636 (defcustom message-alternative-emails nil
1637   "*Regexp matching alternative email addresses.
1638 The first address in the To, Cc or From headers of the original
1639 article matching this variable is used as the From field of
1640 outgoing messages.
1641
1642 This variable has precedence over posting styles and anything that runs
1643 off `message-setup-hook'."
1644   :group 'message-headers
1645   :link '(custom-manual "(message)Message Headers")
1646   :type '(choice (const :tag "Always use primary" nil)
1647                  regexp))
1648
1649 (defcustom message-hierarchical-addresses nil
1650   "A list of hierarchical mail address definitions.
1651
1652 Inside each entry, the first address is the \"top\" address, and
1653 subsequent addresses are subaddresses; this is used to indicate that
1654 mail sent to the first address will automatically be delivered to the
1655 subaddresses.  So if the first address appears in the recipient list
1656 for a message, the subaddresses will be removed (if present) before
1657 the mail is sent.  All addresses in this structure should be
1658 downcased."
1659   :version "22.1"
1660   :group 'message-headers
1661   :type '(repeat (repeat string)))
1662
1663 (defcustom message-mail-user-agent nil
1664   "Like `mail-user-agent'.
1665 Except if it is nil, use Gnus native MUA; if it is t, use
1666 `mail-user-agent'."
1667   :version "22.1"
1668   :type '(radio (const :tag "Gnus native"
1669                        :format "%t\n"
1670                        nil)
1671                 (const :tag "`mail-user-agent'"
1672                        :format "%t\n"
1673                        t)
1674                 (function-item :tag "Default Emacs mail"
1675                                :format "%t\n"
1676                                sendmail-user-agent)
1677                 (function-item :tag "Emacs interface to MH"
1678                                :format "%t\n"
1679                                mh-e-user-agent)
1680                 (function :tag "Other"))
1681   :version "21.1"
1682   :group 'message)
1683
1684 (defcustom message-wide-reply-confirm-recipients nil
1685   "Whether to confirm a wide reply to multiple email recipients.
1686 If this variable is nil, don't ask whether to reply to all recipients.
1687 If this variable is non-nil, pose the question \"Reply to all
1688 recipients?\" before a wide reply to multiple recipients.  If the user
1689 answers yes, reply to all recipients as usual.  If the user answers
1690 no, only reply back to the author."
1691   :version "22.1"
1692   :group 'message-headers
1693   :link '(custom-manual "(message)Wide Reply")
1694   :type 'boolean)
1695
1696 (defcustom message-user-fqdn nil
1697   "*Domain part of Message-Ids."
1698   :version "22.1"
1699   :group 'message-headers
1700   :link '(custom-manual "(message)News Headers")
1701   :type '(radio (const :format "%v  " nil)
1702                 (string :format "FQDN: %v")))
1703
1704 (defcustom message-use-idna (and (condition-case nil (require 'idna)
1705                                    (file-error))
1706                                  (mm-coding-system-p 'utf-8)
1707                                  (executable-find idna-program)
1708                                  (string= (idna-to-ascii "räksmörgÃ¥s")
1709                                           "xn--rksmrgs-5wao1o")
1710                                  t)
1711   "Whether to encode non-ASCII in domain names into ASCII according to IDNA.
1712 GNU Libidn, and in particular the elisp package \"idna.el\" and
1713 the external program \"idn\", must be installed for this
1714 functionality to work."
1715   :version "22.1"
1716   :group 'message-headers
1717   :link '(custom-manual "(message)IDNA")
1718   :type '(choice (const :tag "Ask" ask)
1719                  (const :tag "Never" nil)
1720                  (const :tag "Always" t)))
1721
1722 (defcustom message-generate-hashcash nil
1723   "*Whether to generate X-Hashcash: headers.
1724 You must have the \"hashcash\" binary installed, see `hashcash-path'."
1725   :group 'message-headers
1726   :link '(custom-manual "(message)Mail Headers")
1727   :type 'boolean)
1728
1729 ;;; Internal variables.
1730
1731 (defvar message-sending-message "Sending...")
1732 (defvar message-buffer-list nil)
1733 (defvar message-this-is-news nil)
1734 (defvar message-this-is-mail nil)
1735 (defvar message-draft-article nil)
1736 (defvar message-mime-part nil)
1737 (defvar message-posting-charset nil)
1738 (defvar message-inserted-headers nil)
1739
1740 ;; Byte-compiler warning
1741 (eval-when-compile
1742   (defvar gnus-active-hashtb)
1743   (defvar gnus-read-active-file))
1744
1745 ;;; Regexp matching the delimiter of messages in UNIX mail format
1746 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1747 ;;; of rmail.el's rmail-unix-mail-delimiter.
1748 (defvar message-unix-mail-delimiter
1749   (let ((time-zone-regexp
1750          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1751                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1752                  "\\|"
1753                  "\\) *")))
1754     (concat
1755      "From "
1756
1757      ;; Many things can happen to an RFC 822 mailbox before it is put into
1758      ;; a `From' line.  The leading phrase can be stripped, e.g.
1759      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1760      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1761      ;; can be removed, e.g.
1762      ;;         From: joe@y.z (Joe      K
1763      ;;                 User)
1764      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1765      ;;         From: Joe User
1766      ;;                 <joe@y.z>
1767      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1768      ;; The mailbox can be removed or be replaced by white space, e.g.
1769      ;;         From: "Joe User"{space}{tab}
1770      ;;                 <joe@y.z>
1771      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1772      ;; where {space} and {tab} represent the Ascii space and tab characters.
1773      ;; We want to match the results of any of these manglings.
1774      ;; The following regexp rejects names whose first characters are
1775      ;; obviously bogus, but after that anything goes.
1776      "\\([^\0-\b\n-\r\^?].*\\)?"
1777
1778      ;; The time the message was sent.
1779      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1780      "\\([^\0-\r \^?]+\\) +"            ; month
1781      "\\([0-3]?[0-9]\\) +"              ; day of month
1782      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1783
1784      ;; Perhaps a time zone, specified by an abbreviation, or by a
1785      ;; numeric offset.
1786      time-zone-regexp
1787
1788      ;; The year.
1789      " \\([0-9][0-9]+\\) *"
1790
1791      ;; On some systems the time zone can appear after the year, too.
1792      time-zone-regexp
1793
1794      ;; Old uucp cruft.
1795      "\\(remote from .*\\)?"
1796
1797      "\n"))
1798   "Regexp matching the delimiter of messages in UNIX mail format.")
1799
1800 (defvar message-unsent-separator
1801   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1802           "^ *---+ +Returned message +---+ *$\\|"
1803           "^Start of returned message$\\|"
1804           "^ *---+ +Original message +---+ *$\\|"
1805           "^ *--+ +begin message +--+ *$\\|"
1806           "^ *---+ +Original message follows +---+ *$\\|"
1807           "^ *---+ +Undelivered message follows +---+ *$\\|"
1808           "^|? *---+ +Message text follows: +---+ *|?$")
1809   "A regexp that matches the separator before the text of a failed message.")
1810
1811 (defvar message-field-fillers
1812   '((To message-fill-field-address)
1813     (Cc message-fill-field-address)
1814     (From message-fill-field-address))
1815   "Alist of header names/filler functions.")
1816
1817 (defvar message-header-format-alist
1818   `((From)
1819     (Newsgroups)
1820     (To)
1821     (Cc)
1822     (Subject)
1823     (In-Reply-To)
1824     (Fcc)
1825     (Bcc)
1826     (Date)
1827     (Organization)
1828     (Distribution)
1829     (Lines)
1830     (Expires)
1831     (Message-ID)
1832     (References . message-shorten-references)
1833     (User-Agent))
1834   "Alist used for formatting headers.")
1835
1836 (defvar message-options nil
1837   "Some saved answers when sending message.")
1838
1839 (defvar message-send-mail-real-function nil
1840   "Internal send mail function.")
1841
1842 (defvar message-bogus-system-names "^localhost\\."
1843   "The regexp of bogus system names.")
1844
1845 (defcustom message-valid-fqdn-regexp
1846   (concat "[a-z0-9][-.a-z0-9]+\\." ;; [hostname.subdomain.]domain.
1847           ;; valid TLDs:
1848           "\\([a-z][a-z]" ;; two letter country TDLs
1849           "\\|biz\\|com\\|edu\\|gov\\|int\\|mil\\|net\\|org"
1850           "\\|aero\\|coop\\|info\\|name\\|museum"
1851           "\\|arpa\\|pro\\|uucp\\|bitnet\\|bofh" ;; old style?
1852           "\\)")
1853   "Regular expression that matches a valid FQDN."
1854   ;; see also: gnus-button-valid-fqdn-regexp
1855   :version "22.1"
1856   :group 'message-headers
1857   :type 'regexp)
1858
1859 (eval-and-compile
1860   (autoload 'gnus-alive-p "gnus-util")
1861   (autoload 'gnus-delay-article "gnus-delay")
1862   (autoload 'gnus-extract-address-components "gnus-util")
1863   (autoload 'gnus-find-method-for-group "gnus")
1864   (autoload 'gnus-group-decoded-name "gnus-group")
1865   (autoload 'gnus-group-name-charset "gnus-group")
1866   (autoload 'gnus-group-name-decode "gnus-group")
1867   (autoload 'gnus-groups-from-server "gnus")
1868   (autoload 'gnus-make-local-hook "gnus-util")
1869   (autoload 'gnus-open-server "gnus-int")
1870   (autoload 'gnus-output-to-mail "gnus-util")
1871   (autoload 'gnus-output-to-rmail "gnus-util")
1872   (autoload 'gnus-request-post "gnus-int")
1873   (autoload 'gnus-server-string "gnus")
1874   (autoload 'idna-to-ascii "idna")
1875   (autoload 'message-setup-toolbar "messagexmas")
1876   (autoload 'mh-new-draft-name "mh-comp")
1877   (autoload 'mh-send-letter "mh-comp")
1878   (autoload 'mu-cite-original "mu-cite")
1879   (autoload 'nndraft-request-associate-buffer "nndraft")
1880   (autoload 'nndraft-request-expire-articles "nndraft")
1881   (autoload 'nnvirtual-find-group-art "nnvirtual")
1882   (autoload 'rmail-dont-reply-to "mail-utils")
1883   (autoload 'rmail-msg-is-pruned "rmail")
1884   (autoload 'rmail-msg-restore-non-pruned-header "rmail")
1885   (autoload 'rmail-output "rmailout"))
1886
1887 \f
1888
1889 ;;;
1890 ;;; Utility functions.
1891 ;;;
1892 (defun message-eval-parameter (parameter)
1893   (condition-case ()
1894       (if (symbolp parameter)
1895           (if (functionp parameter)
1896               (funcall parameter)
1897             (eval parameter))
1898         parameter)
1899     (error nil)))
1900
1901 (defsubst message-get-parameter (key &optional alist)
1902   (unless alist
1903     (setq alist message-parameter-alist))
1904   (cdr (assq key alist)))
1905
1906 (defmacro message-get-parameter-with-eval (key &optional alist)
1907   `(message-eval-parameter (message-get-parameter ,key ,alist)))
1908
1909 (defmacro message-y-or-n-p (question show &rest text)
1910   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1911   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1912
1913 (defmacro message-delete-line (&optional n)
1914   "Delete the current line (and the next N lines)."
1915   `(delete-region (progn (beginning-of-line) (point))
1916                   (progn (forward-line ,(or n 1)) (point))))
1917
1918 (defun message-mark-active-p ()
1919   "Non-nil means the mark and region are currently active in this buffer."
1920   mark-active)
1921
1922 (defun message-unquote-tokens (elems)
1923   "Remove double quotes (\") from strings in list ELEMS."
1924   (mapcar (lambda (item)
1925             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1926               (setq item (concat (match-string 1 item)
1927                                  (match-string 2 item))))
1928             item)
1929           elems))
1930
1931 (defun message-tokenize-header (header &optional separator)
1932   "Split HEADER into a list of header elements.
1933 SEPARATOR is a string of characters to be used as separators.  \",\"
1934 is used by default."
1935   (if (not header)
1936       nil
1937     (let ((regexp (format "[%s]+" (or separator ",")))
1938           (first t)
1939           beg quoted elems paren)
1940       (with-temp-buffer
1941         (set-buffer-multibyte t)
1942         (setq beg (point-min))
1943         (insert header)
1944         (goto-char (point-min))
1945         (while (not (eobp))
1946           (if first
1947               (setq first nil)
1948             (forward-char 1))
1949           (cond ((and (> (point) beg)
1950                       (or (eobp)
1951                           (and (looking-at regexp)
1952                                (not quoted)
1953                                (not paren))))
1954                  (push (buffer-substring beg (point)) elems)
1955                  (setq beg (match-end 0)))
1956                 ((eq (char-after) ?\")
1957                  (setq quoted (not quoted)))
1958                 ((and (eq (char-after) ?\()
1959                       (not quoted))
1960                  (setq paren t))
1961                 ((and (eq (char-after) ?\))
1962                       (not quoted))
1963                  (setq paren nil))))
1964         (nreverse elems)))))
1965
1966 (defun message-mail-file-mbox-p (file)
1967   "Say whether FILE looks like a Unix mbox file."
1968   (when (and (file-exists-p file)
1969              (file-readable-p file)
1970              (file-regular-p file))
1971     (with-temp-buffer
1972       (nnheader-insert-file-contents file)
1973       (goto-char (point-min))
1974       (looking-at message-unix-mail-delimiter))))
1975
1976 (defun message-fetch-field (header &optional not-all)
1977   "The same as `mail-fetch-field', only remove all newlines.
1978 The buffer is expected to be narrowed to just the header of the message;
1979 see `message-narrow-to-headers-or-head'."
1980   (let* ((inhibit-point-motion-hooks t)
1981          (value (mail-fetch-field header nil (not not-all))))
1982     (when value
1983       (while (string-match "\n[\t ]+" value)
1984         (setq value (replace-match " " t t value)))
1985       value)))
1986
1987 (defun message-field-value (header &optional not-all)
1988   "The same as `message-fetch-field', only narrow to the headers first."
1989   (save-excursion
1990     (save-restriction
1991       (message-narrow-to-headers-or-head)
1992       (message-fetch-field header not-all))))
1993
1994 (defun message-narrow-to-field ()
1995   "Narrow the buffer to the header on the current line."
1996   (beginning-of-line)
1997   (while (looking-at "[ \t]")
1998     (forward-line -1))
1999   (narrow-to-region
2000    (point)
2001    (progn
2002      (forward-line 1)
2003      (if (re-search-forward "^[^ \n\t]" nil t)
2004          (point-at-bol)
2005        (point-max))))
2006   (goto-char (point-min)))
2007
2008 (defun message-add-header (&rest headers)
2009   "Add the HEADERS to the message header, skipping those already present."
2010   (while headers
2011     (let (hclean)
2012       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
2013         (error "Invalid header `%s'" (car headers)))
2014       (setq hclean (match-string 1 (car headers)))
2015       (save-restriction
2016         (message-narrow-to-headers)
2017         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
2018           (goto-char (point-max))
2019           (if (string-match "\n$" (car headers))
2020               (insert (car headers))
2021             (insert (car headers) ?\n)))))
2022     (setq headers (cdr headers))))
2023
2024 (defmacro message-with-reply-buffer (&rest forms)
2025   "Evaluate FORMS in the reply buffer, if it exists."
2026   `(let ((buffer (message-eval-parameter message-reply-buffer)))
2027      (when (and buffer
2028                 (buffer-name buffer))
2029        (save-excursion
2030          (set-buffer buffer)
2031          ,@forms))))
2032
2033 (put 'message-with-reply-buffer 'lisp-indent-function 0)
2034 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
2035
2036 (defun message-fetch-reply-field (header)
2037   "Fetch field HEADER from the message we're replying to."
2038   (message-with-reply-buffer
2039     (save-restriction
2040       (mail-narrow-to-head)
2041       (message-fetch-field header))))
2042
2043 (defun message-strip-list-identifiers (subject)
2044   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
2045   (require 'gnus-sum)                   ; for gnus-list-identifiers
2046   (let ((regexp (if (stringp gnus-list-identifiers)
2047                     gnus-list-identifiers
2048                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
2049     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
2050                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
2051         (concat (substring subject 0 (match-beginning 1))
2052                 (or (match-string 3 subject)
2053                     (match-string 5 subject))
2054                 (substring subject
2055                            (match-end 1)))
2056       subject)))
2057
2058 (defun message-strip-subject-re (subject)
2059   "Remove \"Re:\" from subject lines in string SUBJECT."
2060   (if (string-match message-subject-re-regexp subject)
2061       (substring subject (match-end 0))
2062     subject))
2063
2064 ;;; Start of functions adopted from `message-utils.el'.
2065
2066 (defun message-strip-subject-trailing-was (subject)
2067   "Remove trailing \"(was: <old subject>)\" from SUBJECT lines.
2068 Leading \"Re: \" is not stripped by this function.  Use the function
2069 `message-strip-subject-re' for this."
2070   (let* ((query message-subject-trailing-was-query)
2071          (new) (found))
2072     (setq found
2073           (string-match
2074            (if (eq query 'ask)
2075                message-subject-trailing-was-ask-regexp
2076              message-subject-trailing-was-regexp)
2077            subject))
2078     (if found
2079         (setq new (substring subject 0 (match-beginning 0))))
2080     (if (or (not found) (eq query nil))
2081         subject
2082       (if (eq query 'ask)
2083           (if (message-y-or-n-p
2084                "Strip `(was: <old subject>)' in subject? " t
2085                (concat
2086                 "Strip `(was: <old subject>)' in subject "
2087                 "and use the new one instead?\n\n"
2088                 "Current subject is:   \""
2089                 subject "\"\n\n"
2090                 "New subject would be: \""
2091                 new "\"\n\n"
2092                 "See the variable `message-subject-trailing-was-query' "
2093                 "to get rid of this query."
2094                 ))
2095               new subject)
2096         new))))
2097
2098 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
2099
2100 (defun message-change-subject (new-subject)
2101   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
2102   ;; <URL:http://www.landfield.com/usefor/drafts/draft-ietf-usefor-useage--1.02.unpaged>
2103   (interactive
2104    (list
2105     (read-from-minibuffer "New subject: ")))
2106   (cond ((and (not (or (null new-subject) ; new subject not empty
2107                        (zerop (string-width new-subject))
2108                        (string-match "^[ \t]*$" new-subject))))
2109          (save-excursion
2110            (let ((old-subject
2111                   (save-restriction
2112                     (message-narrow-to-headers)
2113                     (message-fetch-field "Subject"))))
2114              (cond ((not old-subject)
2115                     (error "No current subject"))
2116                    ((not (string-match
2117                           (concat "^[ \t]*"
2118                                   (regexp-quote new-subject)
2119                                   " \t]*$")
2120                           old-subject))  ; yes, it really is a new subject
2121                     ;; delete eventual Re: prefix
2122                     (setq old-subject
2123                           (message-strip-subject-re old-subject))
2124                     (message-goto-subject)
2125                     (message-delete-line)
2126                     (insert (concat "Subject: "
2127                                     new-subject
2128                                     " (was: "
2129                                     old-subject ")\n")))))))))
2130
2131 (defun message-mark-inserted-region (beg end &optional verbatim)
2132   "Mark some region in the current article with enclosing tags.
2133 See `message-mark-insert-begin' and `message-mark-insert-end'.
2134 If VERBATIM, use slrn style verbatim marks (\"#v+\" and \"#v-\")."
2135   (interactive "r\nP")
2136   (save-excursion
2137     ;; add to the end of the region first, otherwise end would be invalid
2138     (goto-char end)
2139     (insert (if verbatim "#v-\n" message-mark-insert-end))
2140     (goto-char beg)
2141     (insert (if verbatim "#v+\n" message-mark-insert-begin))))
2142
2143 (defun message-mark-insert-file (file &optional verbatim)
2144   "Insert FILE at point, marking it with enclosing tags.
2145 See `message-mark-insert-begin' and `message-mark-insert-end'.
2146 If VERBATIM, use slrn style verbatim marks (\"#v+\" and \"#v-\")."
2147   (interactive "fFile to insert: \nP")
2148     ;; reverse insertion to get correct result.
2149   (let ((p (point)))
2150     (insert (if verbatim "#v-\n" message-mark-insert-end))
2151     (goto-char p)
2152     (insert-file-contents file)
2153     (goto-char p)
2154     (insert (if verbatim "#v+\n" message-mark-insert-begin))))
2155
2156 (defun message-add-archive-header ()
2157   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
2158 The note can be customized using `message-archive-note'.  When called with a
2159 prefix argument, ask for a text to insert.  If you don't want the note in the
2160 body, set  `message-archive-note' to nil."
2161   (interactive)
2162   (if current-prefix-arg
2163       (setq message-archive-note
2164             (read-from-minibuffer "Reason for No-Archive: "
2165                                   (cons message-archive-note 0))))
2166     (save-excursion
2167       (if (message-goto-signature)
2168           (re-search-backward message-signature-separator))
2169       (when message-archive-note
2170         (insert message-archive-note)
2171         (newline))
2172       (message-add-header message-archive-header)
2173       (message-sort-headers)))
2174
2175 (defun message-cross-post-followup-to-header (target-group)
2176   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
2177 With prefix-argument just set Follow-Up, don't cross-post."
2178   (interactive
2179    (list ; Completion based on Gnus
2180     (completing-read "Followup To: "
2181                      (if (boundp 'gnus-newsrc-alist)
2182                          gnus-newsrc-alist)
2183                      nil nil '("poster" . 0)
2184                      (if (boundp 'gnus-group-history)
2185                          'gnus-group-history))))
2186   (message-remove-header "Follow[Uu]p-[Tt]o" t)
2187   (message-goto-newsgroups)
2188   (beginning-of-line)
2189   ;; if we already did a crosspost before, kill old target
2190   (if (and message-cross-post-old-target
2191            (re-search-forward
2192             (regexp-quote (concat "," message-cross-post-old-target))
2193             nil t))
2194       (replace-match ""))
2195   ;; unless (followup is to poster or user explicitly asked not
2196   ;; to cross-post, or target-group is already in Newsgroups)
2197   ;; add target-group to Newsgroups line.
2198   (cond ((and (or
2199                ;; def: cross-post, req:no
2200                (and message-cross-post-default (not current-prefix-arg))
2201                ;; def: no-cross-post, req:yes
2202                (and (not message-cross-post-default) current-prefix-arg))
2203               (not (string-match "poster" target-group))
2204               (not (string-match (regexp-quote target-group)
2205                                  (message-fetch-field "Newsgroups"))))
2206          (end-of-line)
2207          (insert (concat "," target-group))))
2208   (end-of-line) ; ensure Followup: comes after Newsgroups:
2209   ;; unless new followup would be identical to Newsgroups line
2210   ;; make a new Followup-To line
2211   (if (not (string-match (concat "^[ \t]*"
2212                                  target-group
2213                                  "[ \t]*$")
2214                          (message-fetch-field "Newsgroups")))
2215       (insert (concat "\nFollowup-To: " target-group)))
2216   (setq message-cross-post-old-target target-group))
2217
2218 (defun message-cross-post-insert-note (target-group cross-post in-old
2219                                                     old-groups)
2220   "Insert a in message body note about a set Followup or Crosspost.
2221 If there have been previous notes, delete them.  TARGET-GROUP specifies the
2222 group to Followup-To.  When CROSS-POST is t, insert note about
2223 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
2224 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
2225 been made to before the user asked for a Crosspost."
2226   ;; start scanning body for previous uses
2227   (message-goto-signature)
2228   (let ((head (re-search-backward
2229                (concat "^" mail-header-separator)
2230                nil t))) ; just search in body
2231     (message-goto-signature)
2232     (while (re-search-backward
2233             (concat "^" (regexp-quote message-cross-post-note) ".*")
2234             head t)
2235       (message-delete-line))
2236     (message-goto-signature)
2237     (while (re-search-backward
2238             (concat "^" (regexp-quote message-followup-to-note) ".*")
2239             head t)
2240       (message-delete-line))
2241     ;; insert new note
2242     (if (message-goto-signature)
2243         (re-search-backward message-signature-separator))
2244     (if (or in-old
2245             (not cross-post)
2246             (string-match "^[ \t]*poster[ \t]*$" target-group))
2247         (insert (concat message-followup-to-note target-group "\n"))
2248       (insert (concat message-cross-post-note target-group "\n")))))
2249
2250 (defun message-cross-post-followup-to (target-group)
2251   "Crossposts message and set Followup-To to TARGET-GROUP.
2252 With prefix-argument just set Follow-Up, don't cross-post."
2253   (interactive
2254    (list ; Completion based on Gnus
2255     (completing-read "Followup To: "
2256                      (if (boundp 'gnus-newsrc-alist)
2257                          gnus-newsrc-alist)
2258                      nil nil '("poster" . 0)
2259                      (if (boundp 'gnus-group-history)
2260                          'gnus-group-history))))
2261   (cond ((not (or (null target-group) ; new subject not empty
2262                   (zerop (string-width target-group))
2263                   (string-match "^[ \t]*$" target-group)))
2264          (save-excursion
2265            (let* ((old-groups (message-fetch-field "Newsgroups"))
2266                   (in-old (string-match
2267                            (regexp-quote target-group)
2268                            (or old-groups ""))))
2269              ;; check whether target exactly matches old Newsgroups
2270              (cond ((not old-groups)
2271                     (error "No current newsgroup"))
2272                    ((or (not in-old)
2273                         (not (string-match
2274                               (concat "^[ \t]*"
2275                                       (regexp-quote target-group)
2276                                       "[ \t]*$")
2277                               old-groups)))
2278                     ;; yes, Newsgroups line must change
2279                     (message-cross-post-followup-to-header target-group)
2280                     ;; insert note whether we do cross-post or followup-to
2281                     (funcall message-cross-post-note-function
2282                              target-group
2283                              (if (or (and message-cross-post-default
2284                                           (not current-prefix-arg))
2285                                      (and (not message-cross-post-default)
2286                                           current-prefix-arg)) t)
2287                              in-old old-groups))))))))
2288
2289 ;;; Reduce To: to Cc: or Bcc: header
2290
2291 (defun message-reduce-to-to-cc ()
2292  "Replace contents of To: header with contents of Cc: or Bcc: header."
2293  (interactive)
2294  (let ((cc-content
2295         (save-restriction (message-narrow-to-headers)
2296                           (message-fetch-field "cc")))
2297        (bcc nil))
2298    (if (and (not cc-content)
2299             (setq cc-content
2300                   (save-restriction
2301                     (message-narrow-to-headers)
2302                     (message-fetch-field "bcc"))))
2303        (setq bcc t))
2304    (cond (cc-content
2305           (save-excursion
2306             (message-goto-to)
2307             (message-delete-line)
2308             (insert (concat "To: " cc-content "\n"))
2309             (save-restriction
2310               (message-narrow-to-headers)
2311               (message-remove-header (if bcc
2312                                          "bcc"
2313                                        "cc"))))))))
2314
2315 ;;; End of functions adopted from `message-utils.el'.
2316
2317 (defun message-remove-header (header &optional is-regexp first reverse)
2318   "Remove HEADER in the narrowed buffer.
2319 If IS-REGEXP, HEADER is a regular expression.
2320 If FIRST, only remove the first instance of the header.
2321 Return the number of headers removed."
2322   (goto-char (point-min))
2323   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
2324         (number 0)
2325         (case-fold-search t)
2326         last)
2327     (while (and (not (eobp))
2328                 (not last))
2329       (if (if reverse
2330               (not (looking-at regexp))
2331             (looking-at regexp))
2332           (progn
2333             (incf number)
2334             (when first
2335               (setq last t))
2336             (delete-region
2337              (point)
2338              ;; There might be a continuation header, so we have to search
2339              ;; until we find a new non-continuation line.
2340              (progn
2341                (forward-line 1)
2342                (if (re-search-forward "^[^ \t]" nil t)
2343                    (goto-char (match-beginning 0))
2344                  (point-max)))))
2345         (forward-line 1)
2346         (if (re-search-forward "^[^ \t]" nil t)
2347             (goto-char (match-beginning 0))
2348           (goto-char (point-max)))))
2349     number))
2350
2351 (defun message-remove-first-header (header)
2352   "Remove the first instance of HEADER if there is more than one."
2353   (let ((count 0)
2354         (regexp (concat "^" (regexp-quote header) ":")))
2355     (save-excursion
2356       (goto-char (point-min))
2357       (while (re-search-forward regexp nil t)
2358         (incf count)))
2359     (while (> count 1)
2360       (message-remove-header header nil t)
2361       (decf count))))
2362
2363 (defun message-narrow-to-headers ()
2364   "Narrow the buffer to the head of the message."
2365   (widen)
2366   (narrow-to-region
2367    (goto-char (point-min))
2368    (if (re-search-forward
2369         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2370        (match-beginning 0)
2371      (point-max)))
2372   (goto-char (point-min)))
2373
2374 (defun message-narrow-to-head-1 ()
2375   "Like `message-narrow-to-head'.  Don't widen."
2376   (narrow-to-region
2377    (goto-char (point-min))
2378    (if (search-forward "\n\n" nil 1)
2379        (1- (point))
2380      (point-max)))
2381   (goto-char (point-min)))
2382
2383 (defun message-narrow-to-head ()
2384   "Narrow the buffer to the head of the message.
2385 Point is left at the beginning of the narrowed-to region."
2386   (widen)
2387   (message-narrow-to-head-1))
2388
2389 (defun message-narrow-to-headers-or-head ()
2390   "Narrow the buffer to the head of the message."
2391   (widen)
2392   (narrow-to-region
2393    (goto-char (point-min))
2394    (cond
2395     ((re-search-forward
2396       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2397      (match-beginning 0))
2398     ((search-forward "\n\n" nil t)
2399      (1- (point)))
2400     (t
2401      (point-max))))
2402   (goto-char (point-min)))
2403
2404 (defun message-news-p ()
2405   "Say whether the current buffer contains a news message."
2406   (and (not message-this-is-mail)
2407        (or message-this-is-news
2408            (save-excursion
2409              (save-restriction
2410                (message-narrow-to-headers)
2411                (and (message-fetch-field "newsgroups")
2412                     (not (message-fetch-field "posted-to"))))))))
2413
2414 (defun message-mail-p ()
2415   "Say whether the current buffer contains a mail message."
2416   (and (not message-this-is-news)
2417        (or message-this-is-mail
2418            (save-excursion
2419              (save-restriction
2420                (message-narrow-to-headers)
2421                (or (message-fetch-field "to")
2422                    (message-fetch-field "cc")
2423                    (message-fetch-field "bcc")))))))
2424
2425 (defun message-subscribed-p ()
2426   "Say whether we need to insert a MFT header."
2427   (or message-subscribed-regexps
2428       message-subscribed-addresses
2429       message-subscribed-address-file
2430       message-subscribed-address-functions))
2431
2432 (defun message-next-header ()
2433   "Go to the beginning of the next header."
2434   (beginning-of-line)
2435   (or (eobp) (forward-char 1))
2436   (not (if (re-search-forward "^[^ \t]" nil t)
2437            (beginning-of-line)
2438          (goto-char (point-max)))))
2439
2440 (defun message-sort-headers-1 ()
2441   "Sort the buffer as headers using `message-rank' text props."
2442   (goto-char (point-min))
2443   (require 'sort)
2444   (sort-subr
2445    nil 'message-next-header
2446    (lambda ()
2447      (message-next-header)
2448      (unless (bobp)
2449        (forward-char -1)))
2450    (lambda ()
2451      (or (get-text-property (point) 'message-rank)
2452          10000))))
2453
2454 (defun message-sort-headers ()
2455   "Sort the headers of the current message according to `message-header-format-alist'."
2456   (interactive)
2457   (save-excursion
2458     (save-restriction
2459       (let ((max (1+ (length message-header-format-alist)))
2460             rank)
2461         (message-narrow-to-headers)
2462         (while (re-search-forward "^[^ \n]+:" nil t)
2463           (put-text-property
2464            (match-beginning 0) (1+ (match-beginning 0))
2465            'message-rank
2466            (if (setq rank (length (memq (assq (intern (buffer-substring
2467                                                        (match-beginning 0)
2468                                                        (1- (match-end 0))))
2469                                               message-header-format-alist)
2470                                         message-header-format-alist)))
2471                (- max rank)
2472              (1+ max)))))
2473       (message-sort-headers-1))))
2474
2475 (defun message-kill-address ()
2476   "Kill the address under point."
2477   (interactive)
2478   (let ((start (point)))
2479     (message-skip-to-next-address)
2480     (kill-region start (point))))
2481
2482
2483 (defun message-info (&optional arg)
2484   "Display the Message manual.
2485
2486 Prefixed with one \\[universal-argument], display the Emacs MIME manual.
2487 Prefixed with two \\[universal-argument]'s, display the PGG manual."
2488   (interactive "p")
2489   (cond ((eq arg 16) (Info-goto-node "(pgg)Top"))
2490         ((eq arg  4) (Info-goto-node "(emacs-mime)Top"))
2491         (t           (Info-goto-node "(message)Top"))))
2492
2493 \f
2494
2495 ;;;
2496 ;;; Message mode
2497 ;;;
2498
2499 ;;; Set up keymap.
2500
2501 (defvar message-mode-map nil)
2502
2503 (unless message-mode-map
2504   (setq message-mode-map (make-keymap))
2505   (set-keymap-parent message-mode-map text-mode-map)
2506   (define-key message-mode-map "\C-c?" 'describe-mode)
2507
2508   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2509   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2510   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2511   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2512   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2513   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2514   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2515   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
2516   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2517   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2518   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2519   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2520   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2521   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2522   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2523   (define-key message-mode-map "\C-c\C-f\C-i"
2524     'message-insert-or-toggle-importance)
2525   (define-key message-mode-map "\C-c\C-f\C-a"
2526     'message-generate-unsubscribed-mail-followup-to)
2527
2528   ;; modify headers (and insert notes in body)
2529   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2530   ;;
2531   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2532   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2533   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2534   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2535   ;; mark inserted text
2536   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2537   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2538
2539   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2540   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2541   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
2542
2543   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2544   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2545   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2546   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2547   (define-key message-mode-map "\C-c\C-f\C-e" 'message-insert-expires)
2548
2549   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2550   (define-key message-mode-map "\C-c\M-n"
2551     'message-insert-disposition-notification-to)
2552
2553   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2554   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2555   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2556   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2557   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2558   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2559   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2560   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2561
2562   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2563   (define-key message-mode-map "\C-c\C-s" 'message-send)
2564   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2565   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2566   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2567
2568   (define-key message-mode-map "\C-c\M-k" 'message-kill-address)
2569   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2570   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2571   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2572   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2573   (define-key message-mode-map [remap split-line]  'message-split-line)
2574
2575   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2576   (define-key message-mode-map "\t" 'message-tab)
2577   (define-key message-mode-map "\M-;" 'comment-region)
2578
2579   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
2580
2581 (easy-menu-define
2582   message-mode-menu message-mode-map "Message Menu."
2583   `("Message"
2584     ["Yank Original" message-yank-original t]
2585     ["Fill Yanked Message" message-fill-yanked-message t]
2586     ["Insert Signature" message-insert-signature t]
2587     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2588     ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2589     ["Elide Region" message-elide-region
2590      :active (message-mark-active-p)
2591      ,@(if (featurep 'xemacs) nil
2592          '(:help "Replace text in region with an ellipsis"))]
2593     ["Delete Outside Region" message-delete-not-region
2594      :active (message-mark-active-p)
2595      ,@(if (featurep 'xemacs) nil
2596          '(:help "Delete all quoted text outside region"))]
2597     ["Kill To Signature" message-kill-to-signature t]
2598     ["Newline and Reformat" message-newline-and-reformat t]
2599     ["Rename buffer" message-rename-buffer t]
2600     ["Spellcheck" ispell-message
2601      ,@(if (featurep 'xemacs) '(t)
2602          '(:help "Spellcheck this message"))]
2603     ["Attach file as MIME" mime-edit-insert-file
2604      ,@(if (featurep 'xemacs) '(t)
2605          '(:help "Attach a file at point"))]
2606     "----"
2607     ["Insert Region Marked" message-mark-inserted-region
2608      :active (message-mark-active-p)
2609      ,@(if (featurep 'xemacs) nil
2610          '(:help "Mark region with enclosing tags"))]
2611     ["Insert File Marked..." message-mark-insert-file
2612      ,@(if (featurep 'xemacs) '(t)
2613          '(:help "Insert file at point marked with enclosing tags"))]
2614     "----"
2615     ["Send Message" message-send-and-exit
2616      ,@(if (featurep 'xemacs) '(t)
2617          '(:help "Send this message"))]
2618     ["Postpone Message" message-dont-send
2619      ,@(if (featurep 'xemacs) '(t)
2620          '(:help "File this draft message and exit"))]
2621     ["Send at Specific Time..." gnus-delay-article
2622      ,@(if (featurep 'xemacs) '(t)
2623          '(:help "Ask, then arrange to send message at that time"))]
2624     ["Kill Message" message-kill-buffer
2625      ,@(if (featurep 'xemacs) '(t)
2626          '(:help "Delete this message without sending"))]
2627     "----"
2628     ["Message manual" message-info
2629      ,@(if (featurep 'xemacs) '(t)
2630          '(:help "Display the Message manual"))]))
2631
2632 (easy-menu-define
2633   message-mode-field-menu message-mode-map ""
2634   `("Field"
2635     ["To" message-goto-to t]
2636     ["From" message-goto-from t]
2637     ["Subject" message-goto-subject t]
2638     ["Change subject..." message-change-subject t]
2639     ["Cc" message-goto-cc t]
2640     ["Bcc" message-goto-bcc t]
2641     ["Fcc" message-goto-fcc t]
2642     ["Reply-To" message-goto-reply-to t]
2643     ["Flag As Important" message-insert-importance-high
2644      ,@(if (featurep 'xemacs) '(t)
2645          '(:help "Mark this message as important"))]
2646     ["Flag As Unimportant" message-insert-importance-low
2647      ,@(if (featurep 'xemacs) '(t)
2648          '(:help "Mark this message as unimportant"))]
2649     ["Request Receipt"
2650      message-insert-disposition-notification-to
2651      ,@(if (featurep 'xemacs) '(t)
2652          '(:help "Request a receipt notification"))]
2653     "----"
2654     ;; (typical) news stuff
2655     ["Summary" message-goto-summary t]
2656     ["Keywords" message-goto-keywords t]
2657     ["Newsgroups" message-goto-newsgroups t]
2658     ["Fetch Newsgroups" message-insert-newsgroups t]
2659     ["Followup-To" message-goto-followup-to t]
2660     ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2661     ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2662     ["Distribution" message-goto-distribution t]
2663     ["Expires" message-insert-expires t ]
2664     ["X-No-Archive" message-add-archive-header t ]
2665     "----"
2666     ;; (typical) mailing-lists stuff
2667     ["Fetch To" message-insert-to
2668      ,@(if (featurep 'xemacs) '(t)
2669          '(:help "Insert a To header that points to the author."))]
2670     ["Fetch To and Cc" message-insert-wide-reply
2671      ,@(if (featurep 'xemacs) '(t)
2672          '(:help
2673            "Insert To and Cc headers as if you were doing a wide reply."))]
2674     "----"
2675     ["Send to list only" message-to-list-only t]
2676     ["Mail-Followup-To" message-goto-mail-followup-to t]
2677     ["Mail-Reply-To" message-goto-mail-reply-to t]
2678     ["Mail-Copies-To" message-goto-mail-copies-to t]
2679     ["Unsubscribed list post" message-generate-unsubscribed-mail-followup-to
2680      ,@(if (featurep 'xemacs) '(t)
2681          '(:help "Insert a reasonable `Mail-Followup-To:' header."))]
2682     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2683     "----"
2684     ["Sort Headers" message-sort-headers t]
2685     ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2686     ["Goto Body" message-goto-body t]
2687     ["Goto Signature" message-goto-signature t]))
2688
2689 (defvar message-tool-bar-map nil)
2690
2691 (eval-when-compile
2692   (defvar facemenu-add-face-function)
2693   (defvar facemenu-remove-face-function))
2694
2695 ;;; Forbidden properties
2696 ;;
2697 ;; We use `after-change-functions' to keep special text properties
2698 ;; that interfer with the normal function of message mode out of the
2699 ;; buffer.
2700
2701 (defcustom message-strip-special-text-properties t
2702   "Strip special properties from the message buffer.
2703
2704 Emacs has a number of special text properties which can break message
2705 composing in various ways.  If this option is set, message will strip
2706 these properties from the message composition buffer.  However, some
2707 packages requires these properties to be present in order to work.
2708 If you use one of these packages, turn this option off, and hope the
2709 message composition doesn't break too bad."
2710   :version "22.1"
2711   :group 'message-various
2712   :link '(custom-manual "(message)Various Message Variables")
2713   :type 'boolean)
2714
2715 (defconst message-forbidden-properties
2716   ;; No reason this should be clutter up customize.  We make it a
2717   ;; property list (rather than a list of property symbols), to be
2718   ;; directly useful for `remove-text-properties'.
2719   '(field nil read-only nil invisible nil intangible nil
2720           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2721           insert-behind-hooks nil point-entered nil point-left nil)
2722   ;; Other special properties:
2723   ;; category, face, display: probably doesn't do any harm.
2724   ;; fontified: is used by font-lock.
2725   ;; syntax-table, local-map: I dunno.
2726   ;; We need to add XEmacs names to the list.
2727   "Property list of with properties forbidden in message buffers.
2728 The values of the properties are ignored, only the property names are used.")
2729
2730 (defun message-tamago-not-in-use-p (pos)
2731   "Return t when tamago version 4 is not in use at the cursor position.
2732 Tamago version 4 is a popular input method for writing Japanese text.
2733 It uses the properties `intangible', `invisible', `modification-hooks'
2734 and `read-only' when translating ascii or kana text to kanji text.
2735 These properties are essential to work, so we should never strip them."
2736   (not (and (boundp 'egg-modefull-mode)
2737             (symbol-value 'egg-modefull-mode)
2738             (or (memq (get-text-property pos 'intangible)
2739                       '(its-part-1 its-part-2))
2740                 (get-text-property pos 'egg-end)
2741                 (get-text-property pos 'egg-lang)
2742                 (get-text-property pos 'egg-start)))))
2743
2744 (defun message-strip-forbidden-properties (begin end &optional old-length)
2745   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2746 This function is intended to be called from `after-change-functions'.
2747 See also `message-forbidden-properties'."
2748   (when (and message-strip-special-text-properties
2749              (message-tamago-not-in-use-p begin)
2750              ;; Check whether the invisible MIME part is not inserted.
2751              (not (text-property-any begin end 'mime-edit-invisible t)))
2752     (let ((buffer-read-only nil)
2753           (inhibit-read-only t))
2754       (remove-text-properties begin end message-forbidden-properties))))
2755
2756 ;;;###autoload
2757 (define-derived-mode message-mode text-mode "Message"
2758   "Major mode for editing mail and news to be sent.
2759 Like Text Mode but with these additional commands:\\<message-mode-map>
2760 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2761 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2762 C-c C-f  move to a header field (and create it if there isn't):
2763          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2764          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2765          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2766          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2767          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2768          C-c C-f C-o  move to From (\"Originator\")
2769          C-c C-f C-f  move to Followup-To
2770          C-c C-f C-m  move to Mail-Followup-To
2771          C-c C-f c    move to Mail-Copies-To
2772          C-c C-f C-e  move to Expires
2773          C-c C-f C-i  cycle through Importance values
2774          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2775          C-c C-f x    crossposting with FollowUp-To header and note in body
2776          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2777          C-c C-f a    Insert X-No-Archive: header and a note in the body
2778 C-c C-t  `message-insert-to' (add a To header to a news followup)
2779 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2780 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2781 C-c C-b  `message-goto-body' (move to beginning of message text).
2782 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2783 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2784 C-c C-y  `message-yank-original' (insert current message, if any).
2785 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2786 C-c C-e  `message-elide-region' (elide the text between point and mark).
2787 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2788 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2789 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2790 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2791 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2792 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2793 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2794 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2795   (setq local-abbrev-table text-mode-abbrev-table)
2796   (set (make-local-variable 'message-reply-buffer) nil)
2797   (set (make-local-variable 'message-inserted-headers) nil)
2798   (set (make-local-variable 'message-send-actions) nil)
2799   (set (make-local-variable 'message-exit-actions) nil)
2800   (set (make-local-variable 'message-kill-actions) nil)
2801   (set (make-local-variable 'message-postpone-actions) nil)
2802   (set (make-local-variable 'message-draft-article) nil)
2803   (setq buffer-offer-save t)
2804   (set (make-local-variable 'facemenu-add-face-function)
2805        (lambda (face end)
2806          (let ((face-fun (cdr (assq face message-face-alist))))
2807            (if face-fun
2808                (funcall face-fun (point) end)
2809              (error "Face %s not configured for %s mode" face mode-name)))
2810          ""))
2811   (set (make-local-variable 'facemenu-remove-face-function) t)
2812   (set (make-local-variable 'message-reply-headers) nil)
2813   (make-local-variable 'message-user-agent)
2814   (make-local-variable 'message-post-method)
2815   (set (make-local-variable 'message-sent-message-via) nil)
2816   (set (make-local-variable 'message-checksum) nil)
2817   (make-local-variable 'message-parameter-alist)
2818   (setq message-parameter-alist
2819         (copy-sequence message-startup-parameter-alist))
2820   (message-setup-fill-variables)
2821   ;; Allow using comment commands to add/remove quoting.
2822   ;; (set (make-local-variable 'comment-start) message-yank-prefix)
2823   (when message-yank-prefix
2824     (set (make-local-variable 'comment-start) message-yank-prefix)
2825     (set (make-local-variable 'comment-start-skip)
2826          (concat "^" (regexp-quote message-yank-prefix) "[ \t]*")))
2827   (if (featurep 'xemacs)
2828       (message-setup-toolbar)
2829     (set (make-local-variable 'font-lock-defaults)
2830          '(message-font-lock-keywords t))
2831     (if (boundp 'tool-bar-map)
2832         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2833   (easy-menu-add message-mode-menu message-mode-map)
2834   (easy-menu-add message-mode-field-menu message-mode-map)
2835   (gnus-make-local-hook 'after-change-functions)
2836   ;; Mmmm... Forbidden properties...
2837   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2838             nil 'local)
2839   ;; Allow mail alias things.
2840   (when (eq message-mail-alias-type 'abbrev)
2841     (if (fboundp 'mail-abbrevs-setup)
2842         (mail-abbrevs-setup)
2843       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2844           (mail-aliases-setup))))
2845   (unless buffer-file-name
2846     (message-set-auto-save-file-name))
2847   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2848
2849 (defun message-setup-fill-variables ()
2850   "Setup message fill variables."
2851   (set (make-local-variable 'fill-paragraph-function)
2852        'message-fill-paragraph)
2853   (make-local-variable 'paragraph-separate)
2854   (make-local-variable 'paragraph-start)
2855   (make-local-variable 'adaptive-fill-regexp)
2856   (unless (boundp 'adaptive-fill-first-line-regexp)
2857     (setq adaptive-fill-first-line-regexp nil))
2858   (make-local-variable 'adaptive-fill-first-line-regexp)
2859   (let ((quote-prefix-regexp
2860          ;; User should change message-cite-prefix-regexp if
2861          ;; message-yank-prefix is set to an abnormal value.
2862          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2863     (setq paragraph-start
2864           (concat
2865            (regexp-quote mail-header-separator) "$\\|"
2866            "[ \t]*$\\|"                 ; blank lines
2867            "-- $\\|"                    ; signature delimiter
2868            "---+$\\|"                   ; delimiters for forwarded messages
2869            page-delimiter "$\\|"        ; spoiler warnings
2870            ".*wrote:$\\|"               ; attribution lines
2871            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
2872            mime-edit-tag-regexp))       ; MIME-Edit tags
2873     (setq paragraph-separate paragraph-start)
2874     (setq adaptive-fill-regexp
2875           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2876     (setq adaptive-fill-first-line-regexp
2877           (concat quote-prefix-regexp "\\|"
2878                   adaptive-fill-first-line-regexp)))
2879   (make-local-variable 'auto-fill-inhibit-regexp)
2880   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2881   (setq auto-fill-inhibit-regexp nil)
2882   (make-local-variable 'normal-auto-fill-function)
2883   (setq normal-auto-fill-function 'message-do-auto-fill)
2884   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2885   ;; In that case, ensure that it uses the right function.  The real
2886   ;; solution would be not to use `define-derived-mode', and run
2887   ;; `text-mode-hook' ourself at the end of the mode.
2888   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2889   (when auto-fill-function
2890     (setq auto-fill-function normal-auto-fill-function)))
2891
2892 \f
2893
2894 ;;;
2895 ;;; Message mode commands
2896 ;;;
2897
2898 ;;; Movement commands
2899
2900 (defun message-goto-to ()
2901   "Move point to the To header."
2902   (interactive)
2903   (message-position-on-field "To"))
2904
2905 (defun message-goto-from ()
2906   "Move point to the From header."
2907   (interactive)
2908   (message-position-on-field "From"))
2909
2910 (defun message-goto-subject ()
2911   "Move point to the Subject header."
2912   (interactive)
2913   (message-position-on-field "Subject"))
2914
2915 (defun message-goto-cc ()
2916   "Move point to the Cc header."
2917   (interactive)
2918   (message-position-on-field "Cc" "To"))
2919
2920 (defun message-goto-bcc ()
2921   "Move point to the Bcc  header."
2922   (interactive)
2923   (message-position-on-field "Bcc" "Cc" "To"))
2924
2925 (defun message-goto-fcc ()
2926   "Move point to the Fcc header."
2927   (interactive)
2928   (message-position-on-field "Fcc" "To" "Newsgroups"))
2929
2930 (defun message-goto-reply-to ()
2931   "Move point to the Reply-To header."
2932   (interactive)
2933   (message-position-on-field "Reply-To" "Subject"))
2934
2935 (defun message-goto-mail-reply-to ()
2936   "Move point to the Mail-Reply-To header."
2937   (interactive)
2938   (message-position-on-field "Mail-Reply-To" "Subject"))
2939
2940 (defun message-goto-mail-copies-to ()
2941   "Move point to the Mail-Copies-To header.  If the header is newly created,
2942 a string \"never\" is inserted in default."
2943   (interactive)
2944   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2945     (insert "never")
2946     (backward-char 5)))
2947
2948 (defun message-goto-newsgroups ()
2949   "Move point to the Newsgroups header."
2950   (interactive)
2951   (message-position-on-field "Newsgroups"))
2952
2953 (defun message-goto-distribution ()
2954   "Move point to the Distribution header."
2955   (interactive)
2956   (message-position-on-field "Distribution"))
2957
2958 (defun message-goto-followup-to ()
2959   "Move point to the Followup-To header."
2960   (interactive)
2961   (message-position-on-field "Followup-To" "Newsgroups"))
2962
2963 (defun message-goto-mail-followup-to ()
2964   "Move point to the Mail-Followup-To header.
2965 If the header is newly created and To field contains only one address,
2966 the address is inserted by default."
2967   (interactive)
2968   (unless (message-position-on-field "Mail-Followup-To" "To")
2969     (let ((start (point))
2970           addresses)
2971       (save-restriction
2972         (message-narrow-to-headers)
2973         (setq addresses (split-string (mail-strip-quoted-names
2974                                        (or (std11-fetch-field "to") ""))
2975                                       "[ \f\t\n\r\v,]+"))
2976         (when (eq 1 (length addresses))
2977           (goto-char start)
2978           (insert (car addresses))
2979           (goto-char start))))))
2980
2981 (defun message-goto-keywords ()
2982   "Move point to the Keywords header."
2983   (interactive)
2984   (message-position-on-field "Keywords" "Subject"))
2985
2986 (defun message-goto-summary ()
2987   "Move point to the Summary header."
2988   (interactive)
2989   (message-position-on-field "Summary" "Subject"))
2990
2991 (defun message-goto-body (&optional interactivep)
2992   "Move point to the beginning of the message body."
2993   (interactive (list t))
2994   (when (and interactivep
2995              (looking-at "[ \t]*\n"))
2996     (expand-abbrev))
2997   (goto-char (point-min))
2998   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2999       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
3000
3001 (defun message-goto-eoh ()
3002   "Move point to the end of the headers."
3003   (interactive)
3004   (message-goto-body)
3005   (forward-line -1))
3006
3007 (defun message-in-body-p ()
3008   "Return t if point is in the message body."
3009   (let ((body (save-excursion (message-goto-body) (point))))
3010     (>= (point) body)))
3011
3012 (defun message-goto-signature ()
3013   "Move point to the beginning of the message signature.
3014 If there is no signature in the article, go to the end and
3015 return nil."
3016   (interactive)
3017   (goto-char (point-min))
3018   (if (re-search-forward message-signature-separator nil t)
3019       (forward-line 1)
3020     (goto-char (point-max))
3021     nil))
3022
3023 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
3024   "Insert a reasonable MFT header in a post to an unsubscribed list.
3025 When making original posts to a mailing list you are not subscribed to,
3026 you have to type in a MFT header by hand.  The contents, usually, are
3027 the addresses of the list and your own address.  This function inserts
3028 such a header automatically.  It fetches the contents of the To: header
3029 in the current mail buffer, and appends the current `user-mail-address'.
3030
3031 If the optional argument INCLUDE-CC is non-nil, the addresses in the
3032 Cc: header are also put into the MFT."
3033
3034   (interactive "P")
3035   (let* (cc tos)
3036     (save-restriction
3037       (message-narrow-to-headers)
3038       (message-remove-header "Mail-Followup-To")
3039       (setq cc (and include-cc (message-fetch-field "Cc")))
3040       (setq tos (if cc
3041                     (concat (message-fetch-field "To") "," cc)
3042                   (message-fetch-field "To"))))
3043     (message-goto-mail-followup-to)
3044     (insert (concat tos ", " user-mail-address))))
3045
3046 \f
3047
3048 (defun message-insert-to (&optional force)
3049   "Insert a To header that points to the author of the article being replied to.
3050 If the original author requested not to be sent mail, don't insert unless the
3051 prefix FORCE is given."
3052   (interactive "P")
3053   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
3054          (dont (and mct (or (equal (downcase mct) "never")
3055                             (equal (downcase mct) "nobody"))))
3056          (to (or (message-fetch-reply-field "mail-reply-to")
3057                  (message-fetch-reply-field "reply-to")
3058                  (message-fetch-reply-field "from"))))
3059     (when (and dont to)
3060       (message
3061        (if force
3062            "Ignoring the user request not to have copies sent via mail"
3063          "Complying with the user request not to have copies sent via mail")))
3064     (when (and force (not to))
3065       (error "No mail address in the article"))
3066     (when (and to (or force (not dont)))
3067       (message-carefully-insert-headers (list (cons 'To to))))))
3068
3069 (defun message-insert-wide-reply ()
3070   "Insert To and Cc headers as if you were doing a wide reply."
3071   (interactive)
3072   (let ((headers (message-with-reply-buffer
3073                    (message-get-reply-headers t))))
3074     (message-carefully-insert-headers headers)))
3075
3076 (defcustom message-header-synonyms
3077   '((To Cc Bcc))
3078   "List of lists of header synonyms.
3079 E.g., if this list contains a member list with elements `Cc' and `To',
3080 then `message-carefully-insert-headers' will not insert a `To' header
3081 when the message is already `Cc'ed to the recipient."
3082   :version "22.1"
3083   :group 'message-headers
3084   :link '(custom-manual "(message)Message Headers")
3085   :type '(repeat sexp))
3086
3087 (defun message-carefully-insert-headers (headers)
3088   "Insert the HEADERS, an alist, into the message buffer.
3089 Does not insert the headers when they are already present there
3090 or in the synonym headers, defined by `message-header-synonyms'."
3091   ;; FIXME: Should compare only the address and not the full name.  Comparison
3092   ;; should be done case-folded (and with `string=' rather than
3093   ;; `string-match').
3094   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
3095   (dolist (header headers)
3096     (let* ((header-name (symbol-name (car header)))
3097            (new-header (cdr header))
3098            (synonyms (loop for synonym in message-header-synonyms
3099                            when (memq (car header) synonym) return synonym))
3100            (old-header
3101             (loop for synonym in synonyms
3102                   for old-header = (mail-fetch-field (symbol-name synonym))
3103                   when (and old-header (string-match new-header old-header))
3104                   return synonym)))
3105       (if old-header
3106           (message "already have `%s' in `%s'" new-header old-header)
3107         (when (and (message-position-on-field header-name)
3108                    (setq old-header (mail-fetch-field header-name))
3109                    (not (string-match "\\` *\\'" old-header)))
3110           (insert ", "))
3111         (insert new-header)))))
3112
3113 (defun message-widen-reply ()
3114   "Widen the reply to include maximum recipients."
3115   (interactive)
3116   (let ((follow-to
3117          (and message-reply-buffer
3118               (buffer-name message-reply-buffer)
3119               (save-excursion
3120                 (set-buffer message-reply-buffer)
3121                 (message-get-reply-headers t)))))
3122     (save-excursion
3123       (save-restriction
3124         (message-narrow-to-headers)
3125         (dolist (elem follow-to)
3126           (message-remove-header (symbol-name (car elem)))
3127           (goto-char (point-min))
3128           (insert (symbol-name (car elem)) ": "
3129                   (cdr elem) "\n"))))))
3130
3131 (defun message-insert-newsgroups ()
3132   "Insert the Newsgroups header from the article being replied to."
3133   (interactive)
3134   (when (and (message-position-on-field "Newsgroups")
3135              (mail-fetch-field "newsgroups")
3136              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
3137     (insert ","))
3138   (insert (or (message-fetch-reply-field "newsgroups") "")))
3139
3140 \f
3141
3142 ;;; Various commands
3143
3144 (defun message-delete-not-region (beg end)
3145   "Delete everything in the body of the current message outside of the region."
3146   (interactive "r")
3147   (let (citeprefix)
3148     (save-excursion
3149       (goto-char beg)
3150       ;; snarf citation prefix, if appropriate
3151       (unless (eq (point) (progn (beginning-of-line) (point)))
3152         (when (looking-at message-cite-prefix-regexp)
3153           (setq citeprefix (match-string 0))))
3154       (goto-char end)
3155       (delete-region (point) (if (not (message-goto-signature))
3156                                  (point)
3157                                (forward-line -2)
3158                                (point)))
3159       (insert "\n")
3160       (goto-char beg)
3161       (delete-region beg (progn (message-goto-body)
3162                                 (forward-line 2)
3163                                 (point)))
3164       (when citeprefix
3165         (insert citeprefix))))
3166   (when (message-goto-signature)
3167     (forward-line -2)))
3168
3169 (defun message-kill-to-signature (&optional arg)
3170   "Kill all text up to the signature.
3171 If a numberic argument or prefix arg is given, leave that number
3172 of lines before the signature intact."
3173   (interactive "P")
3174   (save-excursion
3175     (save-restriction
3176       (let ((point (point)))
3177         (narrow-to-region point (point-max))
3178         (message-goto-signature)
3179         (unless (eobp)
3180           (if (and arg (numberp arg))
3181               (forward-line (- -1 arg))
3182             (end-of-line -1)))
3183         (unless (= point (point))
3184           (kill-region point (point))
3185           (unless (bolp)
3186             (insert "\n")))))))
3187
3188 (defun message-newline-and-reformat (&optional arg not-break)
3189   "Insert four newlines, and then reformat if inside quoted text.
3190 Prefix arg means justify as well."
3191   (interactive (list (if current-prefix-arg 'full)))
3192   (let (quoted point beg end leading-space bolp fill-paragraph-function)
3193     (setq point (point))
3194     (beginning-of-line)
3195     (setq beg (point))
3196     (setq bolp (= beg point))
3197     ;; Find first line of the paragraph.
3198     (if not-break
3199         (while (and (not (eobp))
3200                     (not (looking-at message-cite-prefix-regexp))
3201                     (looking-at paragraph-start))
3202           (forward-line 1)))
3203     ;; Find the prefix
3204     (when (looking-at message-cite-prefix-regexp)
3205       (setq quoted (match-string 0))
3206       (goto-char (match-end 0))
3207       (looking-at "[ \t]*")
3208       (setq leading-space (match-string 0)))
3209     (if (and quoted
3210              (not not-break)
3211              (not bolp)
3212              (< (- point beg) (length quoted)))
3213         ;; break inside the cite prefix.
3214         (setq quoted nil
3215               end nil))
3216     (if quoted
3217         (progn
3218           (forward-line 1)
3219           (while (and (not (eobp))
3220                       (not (looking-at paragraph-separate))
3221                       (looking-at message-cite-prefix-regexp)
3222                       (equal quoted (match-string 0)))
3223             (goto-char (match-end 0))
3224             (looking-at "[ \t]*")
3225             (if (> (length leading-space) (length (match-string 0)))
3226                 (setq leading-space (match-string 0)))
3227             (forward-line 1))
3228           (setq end (point))
3229           (goto-char beg)
3230           (while (and (if (bobp) nil (forward-line -1) t)
3231                       (not (looking-at paragraph-start))
3232                       (looking-at message-cite-prefix-regexp)
3233                       (equal quoted (match-string 0)))
3234             (setq beg (point))
3235             (goto-char (match-end 0))
3236             (looking-at "[ \t]*")
3237             (if (> (length leading-space) (length (match-string 0)))
3238                 (setq leading-space (match-string 0)))))
3239       (while (and (not (eobp))
3240                   (not (looking-at paragraph-separate))
3241                   (not (looking-at message-cite-prefix-regexp)))
3242         (forward-line 1))
3243       (setq end (point))
3244       (goto-char beg)
3245       (while (and (if (bobp) nil (forward-line -1) t)
3246                   (not (looking-at paragraph-start))
3247                   (not (looking-at message-cite-prefix-regexp)))
3248         (setq beg (point))))
3249     (goto-char point)
3250     (save-restriction
3251       (narrow-to-region beg end)
3252       (if not-break
3253           (setq point nil)
3254         (if bolp
3255             (newline)
3256           (newline)
3257           (newline))
3258         (setq point (point))
3259         ;; (newline 2) doesn't mark both newline's as hard, so call
3260         ;; newline twice. -jas
3261         (newline)
3262         (newline)
3263         (delete-region (point) (re-search-forward "[ \t]*"))
3264         (when (and quoted (not bolp))
3265           (insert quoted leading-space)))
3266       (undo-boundary)
3267       (if quoted
3268           (let* ((adaptive-fill-regexp
3269                   (regexp-quote (concat quoted leading-space)))
3270                  (adaptive-fill-first-line-regexp
3271                   adaptive-fill-regexp ))
3272             (fill-paragraph arg))
3273         (fill-paragraph arg))
3274       (if point (goto-char point)))))
3275
3276 (defun message-fill-paragraph (&optional arg)
3277   "Message specific function to fill a paragraph.
3278 This function is used as the value of `fill-paragraph-function' in
3279 Message buffers and is not meant to be called directly."
3280   (interactive (list (if current-prefix-arg 'full)))
3281   (if (if (boundp 'filladapt-mode) filladapt-mode)
3282       nil
3283     (if (message-point-in-header-p)
3284         (message-fill-field)
3285       (message-newline-and-reformat arg t))
3286     t))
3287
3288 ;; Is it better to use `mail-header-end'?
3289 (defun message-point-in-header-p ()
3290   "Return t if point is in the header."
3291   (save-excursion
3292     (let ((p (point)))
3293       (goto-char (point-min))
3294       (not (re-search-forward
3295             (concat "^" (regexp-quote mail-header-separator) "\n")
3296             p t)))))
3297
3298 (defun message-do-auto-fill ()
3299   "Like `do-auto-fill', but don't fill in message header."
3300   (unless (message-point-in-header-p)
3301     (do-auto-fill)))
3302
3303 (defun message-insert-signature (&optional force)
3304   "Insert a signature.  See documentation for variable `message-signature'."
3305   (interactive (list 0))
3306   (let* ((signature
3307           (cond
3308            ((and (null message-signature)
3309                  (eq force 0))
3310             (save-excursion
3311               (goto-char (point-max))
3312               (not (re-search-backward message-signature-separator nil t))))
3313            ((and (null message-signature)
3314                  force)
3315             t)
3316            ((functionp message-signature)
3317             (funcall message-signature))
3318            ((listp message-signature)
3319             (eval message-signature))
3320            (t message-signature)))
3321          (signature
3322           (cond ((stringp signature)
3323                  signature)
3324                 ((and (eq t signature)
3325                       message-signature-file
3326                       (file-exists-p message-signature-file))
3327                  signature))))
3328     (when signature
3329       (goto-char (point-max))
3330       ;; Insert the signature.
3331       (unless (bolp)
3332         (insert "\n"))
3333       (when message-signature-insert-empty-line
3334         (insert "\n"))
3335       (insert "\n" message-signature-separator-for-insertion)
3336       (unless (bolp)
3337         (insert "\n"))
3338       (if (eq signature t)
3339           (insert-file-contents message-signature-file)
3340         (insert signature))
3341       (goto-char (point-max))
3342       (or (bolp) (insert "\n")))))
3343
3344 (defun message-insert-importance-high ()
3345   "Insert header to mark message as important."
3346   (interactive)
3347   (save-excursion
3348     (save-restriction
3349       (message-narrow-to-headers)
3350       (message-remove-header "Importance"))
3351     (message-goto-eoh)
3352     (insert "Importance: high\n")))
3353
3354 (defun message-insert-importance-low ()
3355   "Insert header to mark message as unimportant."
3356   (interactive)
3357   (save-excursion
3358     (save-restriction
3359       (message-narrow-to-headers)
3360       (message-remove-header "Importance"))
3361     (message-goto-eoh)
3362     (insert "Importance: low\n")))
3363
3364 (defun message-insert-or-toggle-importance ()
3365   "Insert a \"Importance: high\" header, or cycle through the header values.
3366 The three allowed values according to RFC 1327 are `high', `normal'
3367 and `low'."
3368   (interactive)
3369   (save-excursion
3370     (let ((valid '("high" "normal" "low"))
3371           (new "high")
3372           cur)
3373       (save-restriction
3374         (message-narrow-to-headers)
3375         (when (setq cur (message-fetch-field "Importance"))
3376           (message-remove-header "Importance")
3377           (setq new (cond ((string= cur "high")
3378                            "low")
3379                           ((string= cur "low")
3380                            "normal")
3381                           (t
3382                            "high")))))
3383       (message-goto-eoh)
3384       (insert (format "Importance: %s\n" new)))))
3385
3386 (defun message-insert-disposition-notification-to ()
3387   "Request a disposition notification (return receipt) to this message.
3388 Note that this should not be used in newsgroups."
3389   (interactive)
3390   (save-excursion
3391     (save-restriction
3392       (message-narrow-to-headers)
3393       (message-remove-header "Disposition-Notification-To"))
3394     (message-goto-eoh)
3395     (insert (format "Disposition-Notification-To: %s\n"
3396                     (or (message-field-value "Reply-to")
3397                         (message-field-value "From")
3398                         (message-make-from))))))
3399
3400 (defun message-elide-region (b e)
3401   "Elide the text in the region.
3402 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3403 text was killed."
3404   (interactive "r")
3405   (kill-region b e)
3406   (insert message-elide-ellipsis))
3407
3408 (defvar message-caesar-translation-table nil)
3409
3410 (defun message-caesar-region (b e &optional n)
3411   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3412   (interactive
3413    (list
3414     (min (point) (or (mark t) (point)))
3415     (max (point) (or (mark t) (point)))
3416     (when current-prefix-arg
3417       (prefix-numeric-value current-prefix-arg))))
3418
3419   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3420   (unless (or (zerop n)                 ; no action needed for a rot of 0
3421               (= b e))                  ; no region to rotate
3422     ;; We build the table, if necessary.
3423     (when (or (not message-caesar-translation-table)
3424               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3425       (setq message-caesar-translation-table
3426             (message-make-caesar-translation-table n)))
3427     (translate-region b e message-caesar-translation-table)))
3428
3429 (defun message-make-caesar-translation-table (n)
3430   "Create a rot table with offset N."
3431   (let ((i -1)
3432         (table (make-string 256 0)))
3433     (while (< (incf i) 256)
3434       (aset table i i))
3435     (concat
3436      (substring table 0 ?A)
3437      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3438      (substring table ?A (+ ?A n))
3439      (substring table (+ ?A 26) ?a)
3440      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3441      (substring table ?a (+ ?a n))
3442      (substring table (+ ?a 26) 255))))
3443
3444 (defun message-caesar-buffer-body (&optional rotnum)
3445   "Caesar rotate all letters in the current buffer by 13 places.
3446 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3447 With prefix arg, specifies the number of places to rotate each letter forward.
3448 Mail and USENET news headers are not rotated."
3449   (interactive (if current-prefix-arg
3450                    (list (prefix-numeric-value current-prefix-arg))
3451                  (list nil)))
3452   (save-excursion
3453     (save-restriction
3454       (when (message-goto-body)
3455         (narrow-to-region (point) (point-max)))
3456       (message-caesar-region (point-min) (point-max) rotnum))))
3457
3458 (defun message-pipe-buffer-body (program)
3459   "Pipe the message body in the current buffer through PROGRAM."
3460   (save-excursion
3461     (save-restriction
3462       (when (message-goto-body)
3463         (narrow-to-region (point) (point-max)))
3464       (shell-command-on-region
3465        (point-min) (point-max) program nil t))))
3466
3467 (defun message-rename-buffer (&optional enter-string)
3468   "Rename the *message* buffer to \"*message* RECIPIENT\".
3469 If the function is run with a prefix, it will ask for a new buffer
3470 name, rather than giving an automatic name."
3471   (interactive "Pbuffer name: ")
3472   (save-excursion
3473     (save-restriction
3474       (goto-char (point-min))
3475       (narrow-to-region (point)
3476                         (search-forward mail-header-separator nil 'end))
3477       (let* ((mail-to (or
3478                        (if (message-news-p) (message-fetch-field "Newsgroups")
3479                          (message-fetch-field "To"))
3480                        ""))
3481              (mail-trimmed-to
3482               (if (string-match "," mail-to)
3483                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3484                 mail-to))
3485              (name-default (concat "*message* " mail-trimmed-to))
3486              (name (if enter-string
3487                        (read-string "New buffer name: " name-default)
3488                      name-default)))
3489         (rename-buffer name t)))))
3490
3491 (defun message-fill-yanked-message (&optional justifyp)
3492   "Fill the paragraphs of a message yanked into this one.
3493 Numeric argument means justify as well."
3494   (interactive "P")
3495   (save-excursion
3496     (goto-char (point-min))
3497     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3498     (let ((fill-prefix message-yank-prefix))
3499       (fill-individual-paragraphs (point) (point-max) justifyp))))
3500
3501 (defun message-indent-citation ()
3502   "Modify text just inserted from a message to be cited.
3503 The inserted text should be the region.
3504 When this function returns, the region is again around the modified text.
3505
3506 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3507 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3508   (let ((start (point)))
3509     ;; Remove unwanted headers.
3510     (when message-ignored-cited-headers
3511       (let (all-removed)
3512         (save-restriction
3513           (narrow-to-region
3514            (goto-char start)
3515            (if (search-forward "\n\n" nil t)
3516                (1- (point))
3517              (point)))
3518           (message-remove-header message-ignored-cited-headers t)
3519           (when (= (point-min) (point-max))
3520             (setq all-removed t))
3521           (goto-char (point-max)))
3522         (if all-removed
3523             (goto-char start)
3524           (forward-line 1))))
3525     ;; Delete blank lines at the start of the buffer.
3526     (while (and (point-min)
3527                 (eolp)
3528                 (not (eobp)))
3529       (message-delete-line))
3530     ;; Delete blank lines at the end of the buffer.
3531     (goto-char (point-max))
3532     (unless (bolp)
3533       (insert "\n"))
3534     (while (and (zerop (forward-line -1))
3535                 (looking-at "$"))
3536       (message-delete-line))
3537     ;; Do the indentation.
3538     (if (null message-yank-prefix)
3539         (indent-rigidly start (mark t) message-indentation-spaces)
3540       (save-excursion
3541         (goto-char start)
3542         (while (< (point) (mark t))
3543           (cond ((looking-at ">")
3544                  (insert message-yank-cited-prefix))
3545                 ((looking-at "^$")
3546                  (insert message-yank-empty-prefix))
3547                 (t
3548                  (insert message-yank-prefix)))
3549           (forward-line 1))))
3550     (goto-char start)))
3551
3552 (defun message-list-references (refs-list &rest refs-strs)
3553   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
3554 to REFS-LIST."
3555   (let (refs ref id saved-id)
3556     (when (and refs-list
3557                (integerp message-list-references-add-position))
3558       (let ((pos message-list-references-add-position))
3559         (while (and refs-list
3560                     (> pos 0))
3561           (push (pop refs-list) saved-id)
3562           (setq pos (1- pos)))))
3563     (while refs-strs
3564       (when (setq refs (pop refs-strs))
3565         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
3566         (while refs
3567           (when (eq (car (setq ref (pop refs))) 'msg-id)
3568             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
3569             (or (member id refs-list)
3570                 (member id saved-id)
3571                 (push id refs-list))))))
3572     (while saved-id
3573       (push (pop saved-id) refs-list))
3574     refs-list))
3575
3576 (defun message-yank-original (&optional arg)
3577   "Insert the message being replied to, if any.
3578 Puts point before the text and mark after.
3579 Normally indents each nonblank line ARG spaces (default 3).  However,
3580 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3581
3582 This function uses `message-cite-function' to do the actual citing.
3583
3584 Just \\[universal-argument] as argument means don't indent, insert no
3585 prefix, and don't delete any headers.
3586
3587 In addition, if `message-yank-add-new-references' is non-nil and this
3588 command is called interactively, new IDs from the yanked article will
3589 be added to the \"References\" field."
3590   (interactive "P")
3591   (let ((modified (buffer-modified-p)))
3592     (when (let ((buffer (message-eval-parameter message-reply-buffer)))
3593             (and buffer
3594                  message-cite-function
3595                  (prog1
3596                      t
3597                    (delete-windows-on buffer t)
3598                    ; Set the mark at the end of the yanked message.
3599                    (push-mark (save-excursion
3600                                 (insert-buffer-substring buffer)
3601                                 (point))))))
3602       ;; Add new IDs to the References field.
3603       (when (and message-yank-add-new-references
3604                  (interactive-p))
3605         (let ((start (point))
3606               (end (mark t))
3607               refs newrefs)
3608           (save-excursion
3609             (save-restriction
3610               (widen)
3611               (setq refs (message-list-references
3612                           nil
3613                           (or (message-make-references)
3614                               (prog2
3615                                   (message-narrow-to-headers)
3616                                   (message-fetch-field "References")
3617                                 (widen)))))
3618               (narrow-to-region start end)
3619               (std11-narrow-to-header)
3620               (unless (equal (setq newrefs
3621                                    (message-list-references
3622                                     (copy-sequence refs)
3623                                     (unless (eq message-yank-add-new-references
3624                                                 'message-id-only)
3625                                       (or (message-fetch-field "References")
3626                                           (message-fetch-field "In-Reply-To")))
3627                                     (message-fetch-field "Message-ID")))
3628                              refs)
3629                 ;; If the References field has been changed, we make it
3630                 ;; visible in the header.
3631                 (when message-reply-headers
3632                   (mail-header-set-message-id message-reply-headers nil)
3633                   (mail-header-set-references message-reply-headers nil))
3634                 (widen)
3635                 (message-narrow-to-headers)
3636                 (if (let ((case-fold-search t))
3637                       (re-search-forward "^References:\\([\t ]+.+\n\\)+"
3638                                          nil t))
3639                     (replace-match "")
3640                   (goto-char (point-max)))
3641                 (mail-header-format
3642                  (list (or (assq 'References message-header-format-alist)
3643                            '(References . message-fill-references)))
3644                  (list (cons 'References
3645                              (mapconcat 'identity
3646                                         (nreverse newrefs) " ")))))))))
3647       (unless arg
3648         (if (and message-suspend-font-lock-when-citing
3649                  (boundp 'font-lock-mode)
3650                  (symbol-value 'font-lock-mode))
3651             (unwind-protect
3652                 (progn
3653                   (sit-for 0)
3654                   (font-lock-mode 0)
3655                   (funcall message-cite-function))
3656               (font-lock-mode 1))
3657           (funcall message-cite-function)))
3658       (message-exchange-point-and-mark)
3659       (unless (bolp)
3660         (insert ?\n))
3661       (unless modified
3662         (setq message-checksum (message-checksum))))))
3663
3664 (defun message-yank-buffer (buffer)
3665   "Insert BUFFER into the current buffer and quote it."
3666   (interactive "bYank buffer: ")
3667   (let ((message-reply-buffer (get-buffer buffer)))
3668     (save-window-excursion
3669       (message-yank-original))))
3670
3671 (defun message-buffers ()
3672   "Return a list of active message buffers."
3673   (let (buffers)
3674     (save-excursion
3675       (dolist (buffer (buffer-list t))
3676         (set-buffer buffer)
3677         (when (and (eq major-mode 'message-mode)
3678                    (null message-sent-message-via))
3679           (push (buffer-name buffer) buffers))))
3680     (nreverse buffers)))
3681
3682 (eval-when-compile (defvar mail-citation-hook)) ; Compiler directive
3683
3684 (defun message-cite-original-1 (strip-signature)
3685   "Cite an original message.
3686 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3687 original message.
3688
3689 This function uses `mail-citation-hook' if that is non-nil."
3690   (if (and (boundp 'mail-citation-hook)
3691            mail-citation-hook)
3692       (run-hooks 'mail-citation-hook)
3693     (let ((start (point))
3694           (end (mark t))
3695           (x-no-archive nil)
3696           (functions
3697            (when message-indent-citation-function
3698              (if (listp message-indent-citation-function)
3699                  message-indent-citation-function
3700                (list message-indent-citation-function))))
3701           (message-reply-headers (or message-reply-headers
3702                                      (make-mail-header))))
3703       (save-restriction
3704         (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3705                                       (1- (point))
3706                                     (point-max)))
3707         (mail-header-set-from message-reply-headers
3708                               (or (message-fetch-field "from")
3709                                   "unknown sender"))
3710         (setq x-no-archive (message-fetch-field "x-no-archive")))
3711       (goto-char start)
3712       (mapc 'funcall functions)
3713       (when strip-signature
3714         ;; Allow undoing.
3715         (undo-boundary)
3716         (goto-char end)
3717         (when (re-search-backward message-signature-separator start t)
3718           ;; Also peel off any blank lines before the signature.
3719           (forward-line -1)
3720           (while (looking-at "^[ \t]*$")
3721             (forward-line -1))
3722           (forward-line 1)
3723           (delete-region (point) end)
3724           (unless (search-backward "\n\n" start t)
3725             ;; Insert a blank line if it is peeled off.
3726             (insert "\n"))))
3727       (when message-citation-line-function
3728         (unless (bolp)
3729           (insert "\n"))
3730         (funcall message-citation-line-function))
3731       (when (and x-no-archive
3732                  (not message-cite-articles-with-x-no-archive)
3733                  (string-match "yes" x-no-archive))
3734         (undo-boundary)
3735         (delete-region (point) (mark t))
3736         (insert "> [Quoted text removed due to X-No-Archive]\n")
3737         (forward-line -1)))))
3738
3739 (defun message-cite-original ()
3740   "Cite function in the standard Message manner."
3741   (message-cite-original-1 nil))
3742
3743 (defun message-cite-original-without-signature ()
3744   "Cite function in the standard Message manner.
3745 This function strips off the signature from the original message."
3746   (message-cite-original-1 t))
3747
3748 (defun message-insert-citation-line ()
3749   "Insert a simple citation line."
3750   (when message-reply-headers
3751     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3752
3753 (defun message-position-on-field (header &rest afters)
3754   (let ((case-fold-search t))
3755     (save-restriction
3756       (narrow-to-region
3757        (goto-char (point-min))
3758        (progn
3759          (re-search-forward
3760           (concat "^" (regexp-quote mail-header-separator) "$"))
3761          (match-beginning 0)))
3762       (goto-char (point-min))
3763       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3764           (progn
3765             (re-search-forward "^[^ \t]" nil 'move)
3766             (beginning-of-line)
3767             (skip-chars-backward "\n")
3768             t)
3769         (while (and afters
3770                     (not (re-search-forward
3771                           (concat "^" (regexp-quote (car afters)) ":")
3772                           nil t)))
3773           (pop afters))
3774         (when afters
3775           (re-search-forward "^[^ \t]" nil 'move)
3776           (beginning-of-line))
3777         (insert header ": \n")
3778         (forward-char -1)
3779         nil))))
3780
3781 (defun message-remove-signature ()
3782   "Remove the signature from the text between point and mark.
3783 The text will also be indented the normal way."
3784   (save-excursion
3785     (let ((start (point))
3786           mark)
3787       (if (not (re-search-forward message-signature-separator (mark t) t))
3788           ;; No signature here, so we just indent the cited text.
3789           (message-indent-citation)
3790         ;; Find the last non-empty line.
3791         (forward-line -1)
3792         (while (looking-at "[ \t]*$")
3793           (forward-line -1))
3794         (forward-line 1)
3795         (setq mark (set-marker (make-marker) (point)))
3796         (goto-char start)
3797         (message-indent-citation)
3798         ;; Enable undoing the deletion.
3799         (undo-boundary)
3800         (delete-region mark (mark t))
3801         (set-marker mark nil)))))
3802
3803 \f
3804
3805 ;;;
3806 ;;; Sending messages
3807 ;;;
3808
3809 ;; Avoid byte-compile warning.
3810 (defvar message-encoding-buffer nil)
3811 (defvar message-edit-buffer nil)
3812 (defvar message-mime-mode nil)
3813
3814 (defun message-send-and-exit (&optional arg)
3815   "Send message like `message-send', then, if no errors, exit from mail buffer."
3816   (interactive "P")
3817   (let ((buf (current-buffer))
3818         (actions message-exit-actions)
3819         (frame (selected-frame))
3820         (org-frame message-original-frame))
3821     (when (and (message-send arg)
3822                (buffer-name buf))
3823       (if message-kill-buffer-on-exit
3824           (kill-buffer buf)
3825         (bury-buffer buf)
3826         (when (eq buf (current-buffer))
3827           (message-bury buf)))
3828       (message-do-actions actions)
3829       (message-delete-frame frame org-frame)
3830       t)))
3831
3832 (defun message-dont-send ()
3833   "Don't send the message you have been editing.
3834 Instead, just auto-save the buffer and then bury it."
3835   (interactive)
3836   (set-buffer-modified-p t)
3837   (save-buffer)
3838   (let ((actions message-postpone-actions)
3839         (frame (selected-frame))
3840         (org-frame message-original-frame))
3841     (message-bury (current-buffer))
3842     (message-do-actions actions)
3843     (message-delete-frame frame org-frame)))
3844
3845 (defun message-kill-buffer ()
3846   "Kill the current buffer."
3847   (interactive)
3848   (when (or (not (buffer-modified-p))
3849             (not message-kill-buffer-query)
3850             (eq t message-kill-buffer-query-function)
3851             (funcall message-kill-buffer-query-function
3852                      "The buffer modified; kill anyway? "))
3853     (let ((actions message-kill-actions)
3854           (draft-article message-draft-article)
3855           (auto-save-file-name buffer-auto-save-file-name)
3856           (file-name buffer-file-name)
3857           (modified (buffer-modified-p))
3858           (frame (selected-frame))
3859           (org-frame message-original-frame))
3860       (setq buffer-file-name nil)
3861       (kill-buffer (current-buffer))
3862       (when (and message-kill-buffer-and-remove-file
3863                  (or (and auto-save-file-name
3864                           (file-exists-p auto-save-file-name))
3865                      (and file-name
3866                           (file-exists-p file-name)))
3867                  (progn
3868                    ;; If the message buffer has lived in a dedicated window,
3869                    ;; `kill-buffer' has killed the frame.  Thus the
3870                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
3871                    ;; that the user can see the question by raising the
3872                    ;; current frame:
3873                    (raise-frame)
3874                    (yes-or-no-p (format "Remove the backup file%s? "
3875                                         (if modified " too" "")))))
3876         (ignore-errors
3877           (delete-file auto-save-file-name))
3878         (let ((message-draft-article draft-article))
3879           (message-disassociate-draft)))
3880       (message-do-actions actions)
3881       (message-delete-frame frame org-frame)))
3882   (message ""))
3883
3884 (defun message-mimic-kill-buffer ()
3885   "Kill the current buffer with query.  This is an imitation for
3886 `kill-buffer', but it will delete a message frame."
3887   (interactive)
3888   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3889                                       (buffer-name))))
3890         message-kill-buffer-and-remove-file)
3891     (when (or (not bufname)
3892               (string-equal bufname "")
3893               (string-equal bufname (buffer-name)))
3894       (message-kill-buffer))))
3895
3896 (defun message-delete-frame (frame org-frame)
3897   "Delete frame for editing message."
3898   (when (and (static-if (featurep 'xemacs)
3899                  (device-on-window-system-p)
3900                window-system)
3901              (or (and (eq message-delete-frame-on-exit t)
3902                       (select-frame frame)
3903                       (or (eq frame org-frame)
3904                           (prog1
3905                               (y-or-n-p "Delete this frame?")
3906                             (message ""))))
3907                  (and (eq message-delete-frame-on-exit 'ask)
3908                       (select-frame frame)
3909                       (prog1
3910                           (y-or-n-p "Delete this frame?")
3911                         (message "")))))
3912     (delete-frame frame)))
3913
3914 (defun message-bury (buffer)
3915   "Bury this mail BUFFER."
3916   (let ((newbuf (other-buffer buffer)))
3917     (bury-buffer buffer)
3918     (if (and (window-dedicated-p (selected-window))
3919              (not (null (delq (selected-frame) (visible-frame-list)))))
3920         (delete-frame (selected-frame))
3921       (switch-to-buffer newbuf))))
3922
3923 (defun message-send (&optional arg)
3924   "Send the message in the current buffer.
3925 If `message-interactive' is non-nil, wait for success indication or
3926 error messages, and inform user.
3927 Otherwise any failure is reported in a message back to the user from
3928 the mailer.
3929 The usage of ARG is defined by the instance that called Message.
3930 It should typically alter the sending method in some way or other."
3931   (interactive "P")
3932   ;; Disabled test.
3933   (when (or (buffer-modified-p)
3934             (message-check-element 'unchanged)
3935             (y-or-n-p "No changes in the buffer; really send? "))
3936     ;; Make it possible to undo the coming changes.
3937     (undo-boundary)
3938     (let ((inhibit-read-only t))
3939       (put-text-property (point-min) (point-max) 'read-only nil))
3940     (run-hooks 'message-send-hook)
3941     (message-fix-before-sending)
3942     (message message-sending-message)
3943     (let ((message-encoding-buffer
3944            (message-generate-new-buffer-clone-locals " message encoding"))
3945           (message-edit-buffer (current-buffer))
3946           (message-mime-mode mime-edit-mode-flag)
3947           (alist message-send-method-alist)
3948           (success t)
3949           elem sent dont-barf-on-no-method
3950           (message-options message-options))
3951       (unwind-protect
3952           (progn
3953             (message-options-set-recipient)
3954             (save-excursion
3955               (set-buffer message-encoding-buffer)
3956               (erase-buffer)
3957               ;; ;; Avoid copying text props (except hard newlines).
3958               ;; T-gnus change: copy all text props from the editing buffer
3959               ;; into the encoding buffer.
3960               (insert-buffer-substring message-edit-buffer)
3961               (funcall message-encode-function)
3962               (while (and success
3963                           (setq elem (pop alist)))
3964                 (when (funcall (cadr elem))
3965                   (when (and
3966                          (or (not (memq (car elem)
3967                                         message-sent-message-via))
3968                              (message-fetch-field "supersedes")
3969                              (if (or (message-gnksa-enable-p 'multiple-copies)
3970                                      (not (eq (car elem) 'news)))
3971                                  (y-or-n-p
3972                                   (format
3973                                    "Already sent message via %s; resend? "
3974                                    (car elem)))
3975                                (error "Denied posting -- multiple copies")))
3976                          (setq success (funcall (caddr elem) arg)))
3977                     (setq sent t)))))
3978             (unless
3979                 (or
3980                  sent
3981                  (not success)
3982                  (let ((fcc (message-fetch-field "Fcc"))
3983                        (gcc (message-fetch-field "Gcc")))
3984                    (when (or fcc gcc)
3985                      (or
3986                       (eq message-allow-no-recipients 'always)
3987                       (and (not (eq message-allow-no-recipients 'never))
3988                            (setq dont-barf-on-no-method
3989                                  (gnus-y-or-n-p
3990                                   (format "No receiver, perform %s anyway? "
3991                                           (cond ((and fcc gcc) "Fcc and Gcc")
3992                                                 (fcc "Fcc")
3993                                                 (t "Gcc"))))))))))
3994               (error "No methods specified to send by"))
3995             (when (or dont-barf-on-no-method
3996                       (and success sent))
3997               (message-do-fcc)
3998               (save-excursion
3999                 (run-hooks 'message-sent-hook))
4000               (message "Sending...done")
4001               ;; Mark the buffer as unmodified and delete auto-save.
4002               (set-buffer-modified-p nil)
4003               (delete-auto-save-file-if-necessary t)
4004               (message-disassociate-draft)
4005               ;; Delete other mail buffers and stuff.
4006               (message-do-send-housekeeping)
4007               (message-do-actions message-send-actions)
4008               ;; Return success.
4009               t))
4010         (kill-buffer message-encoding-buffer)))))
4011
4012 (defun message-send-via-mail (arg)
4013   "Send the current message via mail."
4014   (message-send-mail arg))
4015
4016 (defun message-send-via-news (arg)
4017   "Send the current message via news."
4018   (message-send-news arg))
4019
4020 (defmacro message-check (type &rest forms)
4021   "Eval FORMS if TYPE is to be checked."
4022   `(or (message-check-element ,type)
4023        (save-excursion
4024          ,@forms)))
4025
4026 (put 'message-check 'lisp-indent-function 1)
4027 (put 'message-check 'edebug-form-spec '(form body))
4028
4029 ;; Advise the function `invisible-region'.
4030 (unless noninteractive
4031   (let (current-load-list)
4032     (eval
4033      `(defadvice invisible-region (around add-mime-edit-invisible (start end)
4034                                           activate)
4035         "Advised by T-gnus Message.
4036 Add the text property `mime-edit-invisible' to an invisible text when
4037 the buffer's major mode is `message-mode'.  The added property will be
4038 used to distinguish whether the invisible text is a MIME part or not."
4039         ,(if (featurep 'xemacs)
4040              '(if (eq ?\n (char-after start))
4041                   (setq start (1+ start)))
4042            '(if (eq ?\n (char-after (1- end)))
4043                 (setq end (1- end))))
4044         (setq ad-return-value
4045               (if (eq 'message-mode major-mode)
4046                   (add-text-properties start end
4047                                        '(invisible t mime-edit-invisible t))
4048                 (put-text-property start end 'invisible t)))))))
4049
4050 (defun message-text-with-property (prop &optional start end reverse)
4051   "Return a list of start and end positions where the text has PROP.
4052 START and END bound the search, they default to `point-min' and
4053 `point-max' respectively.  If REVERSE is non-nil, find text which does
4054 not have PROP."
4055   (unless start
4056     (setq start (point-min)))
4057   (unless end
4058     (setq end (point-max)))
4059   (let (next regions)
4060     (if reverse
4061         (while (and start
4062                     (setq start (text-property-any start end prop nil)))
4063           (setq next (next-single-property-change start prop nil end))
4064           (push (cons start (or next end)) regions)
4065           (setq start next))
4066       (while (and start
4067                   (or (get-text-property start prop)
4068                       (and (setq start (next-single-property-change
4069                                         start prop nil end))
4070                            (get-text-property start prop))))
4071         (setq next (text-property-any start end prop nil))
4072         (push (cons start (or next end)) regions)
4073         (setq start next)))
4074     (nreverse regions)))
4075
4076 (defun message-fix-before-sending ()
4077   "Do various things to make the message nice before sending it."
4078   ;; Make sure there's a newline at the end of the message.
4079   (widen)
4080   (goto-char (point-max))
4081   (unless (bolp)
4082     (insert "\n"))
4083   ;; Make the hidden headers visible.
4084   (widen)
4085   ;; Sort headers before sending the message.
4086   (message-sort-headers)
4087   ;; Make invisible text visible except for mime parts which may be
4088   ;; inserted by the MIME-Edit.
4089   ;; It doesn't seem as if this is useful, since the invisible property
4090   ;; is clobbered by an after-change hook anyhow.
4091   (message-check 'invisible-text
4092     ;; FIXME T-gnus: It should also detect invisible overlays.
4093     (let (from
4094           (to (point-min))
4095           mime-from mime-to hidden-start)
4096       (while (setq from (text-property-any to (point-max) 'invisible t))
4097         (setq to (or (text-property-not-all from (point-max) 'invisible t)
4098                      (point-max))
4099               mime-to from)
4100         (while (setq mime-from (text-property-any mime-to to
4101                                                   'mime-edit-invisible t))
4102           (when (> mime-from mime-to)
4103             (setq hidden-start (or hidden-start mime-to))
4104             (add-text-properties mime-to mime-from
4105                                  '(invisible nil face highlight
4106                                              font-lock-face highlight)))
4107           (setq mime-to (or (text-property-not-all mime-from to
4108                                                    'mime-edit-invisible t)
4109                             to)))
4110         (when (< mime-to to)
4111           (setq hidden-start (or hidden-start mime-to))
4112           (add-text-properties mime-to to
4113                                '(invisible nil face highlight
4114                                            font-lock-face highlight))))
4115       (when hidden-start
4116         (goto-char hidden-start)
4117         (set-window-start (selected-window) (point-at-bol))
4118         (unless (yes-or-no-p
4119                  "Invisible text found and made visible; continue sending? ")
4120           (error "Invisible text found and made visible")))))
4121 ;; The following check is needless to T-gnus since T-gnus determines
4122 ;; a MIME charset forcibly (even if it cannot be determined properly,
4123 ;; the value of the `default-mime-charset-for-write' variable is used).
4124 ;;  (message-check 'illegible-text
4125 ;;    (let (found choice)
4126 ;;      (message-goto-body)
4127 ;;      (skip-chars-forward mm-7bit-chars)
4128 ;;      (while (not (eobp))
4129 ;;      (when (let ((char (char-after)))
4130 ;;              (or (< (mm-char-int char) 128)
4131 ;;                  (and (mm-multibyte-p)
4132 ;;                       (memq (char-charset char)
4133 ;;                             '(eight-bit-control eight-bit-graphic
4134 ;;                                                 control-1))
4135 ;;                       (not (get-text-property
4136 ;;                             (point) 'untranslated-utf-8)))))
4137 ;;        (message-overlay-put (message-make-overlay (point) (1+ (point)))
4138 ;;                             'face 'highlight)
4139 ;;        (setq found t))
4140 ;;      (forward-char)
4141 ;;      (skip-chars-forward mm-7bit-chars))
4142 ;;      (when found
4143 ;;      (setq choice
4144 ;;            (gnus-multiple-choice
4145 ;;             "Non-printable characters found.  Continue sending?"
4146 ;;             '((?d "Remove non-printable characters and send")
4147 ;;               (?r "Replace non-printable characters with dots and send")
4148 ;;               (?i "Ignore non-printable characters and send")
4149 ;;               (?e "Continue editing"))))
4150 ;;      (if (eq choice ?e)
4151 ;;          (error "Non-printable characters"))
4152 ;;      (message-goto-body)
4153 ;;      (skip-chars-forward mm-7bit-chars)
4154 ;;      (while (not (eobp))
4155 ;;        (when (let ((char (char-after)))
4156 ;;                (or (< (mm-char-int char) 128)
4157 ;;                    (and (mm-multibyte-p)
4158 ;;                         ;; Fixme: Wrong for Emacs 23 and for things
4159 ;;                         ;; like undecable utf-8.  Should at least
4160 ;;                         ;; use find-coding-systems-region.
4161 ;;                         (memq (char-charset char)
4162 ;;                               '(eight-bit-control eight-bit-graphic
4163 ;;                                                   control-1))
4164 ;;                         (not (get-text-property
4165 ;;                               (point) 'untranslated-utf-8)))))
4166 ;;          (if (eq choice ?i)
4167 ;;              (message-kill-all-overlays)
4168 ;;            (delete-char 1)
4169 ;;            (when (eq choice ?r)
4170 ;;              (insert "."))))
4171 ;;        (forward-char)
4172 ;;        (skip-chars-forward mm-7bit-chars)))))
4173   )
4174
4175 (defun message-add-action (action &rest types)
4176   "Add ACTION to be performed when doing an exit of type TYPES."
4177   (while types
4178     (add-to-list (intern (format "message-%s-actions" (pop types)))
4179                  action)))
4180
4181 (defun message-delete-action (action &rest types)
4182   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4183   (let (var)
4184     (while types
4185       (set (setq var (intern (format "message-%s-actions" (pop types))))
4186            (delq action (symbol-value var))))))
4187
4188 (defun message-do-actions (actions)
4189   "Perform all actions in ACTIONS."
4190   ;; Now perform actions on successful sending.
4191   (dolist (action actions)
4192     (ignore-errors
4193       (cond
4194        ;; A simple function.
4195        ((functionp action)
4196         (funcall action))
4197        ;; Something to be evaled.
4198        (t
4199         (eval action))))))
4200
4201 (defsubst message-maybe-split-and-send-mail ()
4202   "Split a message if necessary, and send it via mail.
4203 Returns nil if sending succeeded, returns any string if sending failed.
4204 This sub function is for exclusive use of `message-send-mail'."
4205   (let ((mime-edit-split-ignored-field-regexp
4206          mime-edit-split-ignored-field-regexp)
4207         (case-fold-search t)
4208         failure)
4209     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4210       (setq mime-edit-split-ignored-field-regexp
4211             (concat (substring mime-edit-split-ignored-field-regexp
4212                                0 (match-beginning 0))
4213                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4214                     "_so_don't_rape_it!"
4215                     (substring mime-edit-split-ignored-field-regexp
4216                                (match-end 0)))))
4217     (setq failure
4218           (or
4219            (catch 'message-sending-mail-failure
4220              (mime-edit-maybe-split-and-send
4221               (function
4222                (lambda ()
4223                  (interactive)
4224                  (save-restriction
4225                    (std11-narrow-to-header mail-header-separator)
4226                    (goto-char (point-min))
4227                    (when (re-search-forward "^Message-ID:" nil t)
4228                      (delete-region (match-end 0) (std11-field-end))
4229                      (insert " " (message-make-message-id))))
4230                  (condition-case err
4231                      (funcall (or message-send-mail-real-function
4232                                   message-send-mail-function))
4233                    (error
4234                     (throw 'message-sending-mail-failure err))))))
4235              nil)
4236            (condition-case err
4237                (progn
4238                  (funcall (or message-send-mail-real-function
4239                               message-send-mail-function))
4240                  nil)
4241              (error err))))
4242     (when failure
4243       (if (eq 'error (car failure))
4244           (cadr failure)
4245         (prin1-to-string failure)))))
4246
4247 (defun message-send-mail-partially ()
4248   "Send mail as message/partial."
4249   ;; replace the header delimiter with a blank line
4250   (goto-char (point-min))
4251   (re-search-forward
4252    (concat "^" (regexp-quote mail-header-separator) "\n"))
4253   (replace-match "\n")
4254   (run-hooks 'message-send-mail-hook)
4255   (let ((p (goto-char (point-min)))
4256         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4257         (curbuf (current-buffer))
4258         (id (message-make-message-id)) (n 1)
4259         plist total  header required-mail-headers)
4260     (while (not (eobp))
4261       (if (< (point-max) (+ p message-send-mail-partially-limit))
4262           (goto-char (point-max))
4263         (goto-char (+ p message-send-mail-partially-limit))
4264         (beginning-of-line)
4265         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4266       (push p plist)
4267       (setq p (point)))
4268     (setq total (length plist))
4269     (push (point-max) plist)
4270     (setq plist (nreverse plist))
4271     (unwind-protect
4272         (save-excursion
4273           (setq p (pop plist))
4274           (while plist
4275             (set-buffer curbuf)
4276             (copy-to-buffer tembuf p (car plist))
4277             (set-buffer tembuf)
4278             (goto-char (point-min))
4279             (if header
4280                 (progn
4281                   (goto-char (point-min))
4282                   (narrow-to-region (point) (point))
4283                   (insert header))
4284               (message-goto-eoh)
4285               (setq header (buffer-substring (point-min) (point)))
4286               (goto-char (point-min))
4287               (narrow-to-region (point) (point))
4288               (insert header)
4289               (message-remove-header "Mime-Version")
4290               (message-remove-header "Content-Type")
4291               (message-remove-header "Content-Transfer-Encoding")
4292               (message-remove-header "Message-ID")
4293               (message-remove-header "Lines")
4294               (goto-char (point-max))
4295               (insert "Mime-Version: 1.0\n")
4296               (setq header (buffer-string)))
4297             (goto-char (point-max))
4298             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4299                             id n total))
4300             (forward-char -1)
4301             (let ((mail-header-separator ""))
4302               (when (memq 'Message-ID message-required-mail-headers)
4303                 (insert "Message-ID: " (message-make-message-id) "\n"))
4304               (when (memq 'Lines message-required-mail-headers)
4305                 (insert "Lines: " (message-make-lines) "\n"))
4306               (message-goto-subject)
4307               (end-of-line)
4308               (insert (format " (%d/%d)" n total))
4309               (widen)
4310               (mm-with-unibyte-current-buffer
4311                 (funcall (or message-send-mail-real-function
4312                              message-send-mail-function))))
4313             (setq n (+ n 1))
4314             (setq p (pop plist))
4315             (erase-buffer)))
4316       (kill-buffer tembuf))))
4317
4318 (defun message-send-mail (&optional arg)
4319   (require 'mail-utils)
4320   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4321          (case-fold-search nil)
4322          (news (message-news-p))
4323          (message-this-is-mail t)
4324          (headers message-required-mail-headers)
4325          failure)
4326     (when message-generate-hashcash
4327       (message "Generating hashcash...")
4328       ;; Wait for calculations already started to finish...
4329       (hashcash-wait-async)
4330       ;; ...and do calculations not already done.  mail-add-payment
4331       ;; will leave existing X-Hashcash headers alone.
4332       (mail-add-payment)
4333       (message "Generating hashcash...done"))
4334     (save-restriction
4335       (message-narrow-to-headers)
4336       ;; Generate the Mail-Followup-To header if the header is not there...
4337       (if (and (message-subscribed-p)
4338                (not (mail-fetch-field "mail-followup-to")))
4339           (setq headers
4340                 (cons
4341                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4342                  message-required-mail-headers))
4343         ;; otherwise, delete the MFT header if the field is empty
4344         (when (equal "" (mail-fetch-field "mail-followup-to"))
4345           (message-remove-header "^Mail-Followup-To:")))
4346       ;; Insert some headers.
4347       (let ((message-deletable-headers
4348              (if news nil message-deletable-headers)))
4349         (message-generate-headers headers))
4350       ;; Let the user do all of the above.
4351       (run-hooks 'message-header-hook))
4352     (if (not (message-check-mail-syntax))
4353         (progn
4354           (message "")
4355           nil)
4356       (unwind-protect
4357           (save-excursion
4358             (set-buffer tembuf)
4359             (erase-buffer)
4360             ;; ;; Avoid copying text props (except hard newlines).
4361             ;; T-gnus change: copy all text props from the editing buffer
4362             ;; into the encoding buffer.
4363             (insert-buffer-substring message-encoding-buffer)
4364             ;; Remove some headers.
4365             (save-restriction
4366               (message-narrow-to-headers)
4367 ;; We Semi-gnus people have no use for it.
4368 ;;            ;; We (re)generate the Lines header.
4369 ;;            (when (memq 'Lines message-required-mail-headers)
4370 ;;              (message-generate-headers '(Lines)))
4371               (message-remove-header message-ignored-mail-headers t))
4372             (goto-char (point-max))
4373             ;; require one newline at the end.
4374             (or (= (preceding-char) ?\n)
4375                 (insert ?\n))
4376             (message-cleanup-headers)
4377             ;; FIXME: we're inserting the courtesy copy after encoding.
4378             ;; This is wrong if the courtesy copy string contains
4379             ;; non-ASCII characters. -- jh
4380             (when
4381                 (save-restriction
4382                   (message-narrow-to-headers)
4383                   (and news
4384                        (or (message-fetch-field "cc")
4385                            (message-fetch-field "bcc")
4386                            (message-fetch-field "to"))
4387                        (let ((content-type (mime-read-Content-Type)))
4388                          (and
4389                           (or
4390                            (not content-type)
4391                            (and
4392                             (eq 'text (cdr (assq 'type content-type)))
4393                             (eq 'plain (cdr (assq 'subtype content-type)))))
4394                           (not
4395                            (string= "base64"
4396                                     (mime-read-Content-Transfer-Encoding)))))))
4397               (message-insert-courtesy-copy))
4398             (setq failure (message-maybe-split-and-send-mail)))
4399         (kill-buffer tembuf))
4400       (set-buffer message-edit-buffer)
4401       (if failure
4402           (progn
4403             (message "Couldn't send message via mail: %s" failure)
4404             nil)
4405         (push 'mail message-sent-message-via)))))
4406
4407 (defun message-send-mail-with-sendmail ()
4408   "Send off the prepared buffer with sendmail."
4409   (let ((errbuf (if message-interactive
4410                     (message-generate-new-buffer-clone-locals
4411                      " sendmail errors")
4412                   0))
4413         resend-to-addresses delimline)
4414     (unwind-protect
4415         (progn
4416           (let ((case-fold-search t))
4417             (save-restriction
4418               (message-narrow-to-headers)
4419               (setq resend-to-addresses (message-fetch-field "resent-to")))
4420             ;; Change header-delimiter to be what sendmail expects.
4421             (goto-char (point-min))
4422             (re-search-forward
4423              (concat "^" (regexp-quote mail-header-separator) "\n"))
4424             (replace-match "\n")
4425             (backward-char 1)
4426             (setq delimline (point-marker))
4427             (run-hooks 'message-send-mail-hook)
4428             ;; Insert an extra newline if we need it to work around
4429             ;; Sun's bug that swallows newlines.
4430             (goto-char (1+ delimline))
4431             (when (eval message-mailer-swallows-blank-line)
4432               (newline))
4433             (when message-interactive
4434               (with-current-buffer errbuf
4435                 (erase-buffer))))
4436           (let* ((default-directory "/")
4437                  (cpr (as-binary-process
4438                        (apply
4439                         'call-process-region
4440                         (append
4441                          (list (point-min) (point-max)
4442                                (if (boundp 'sendmail-program)
4443                                    sendmail-program
4444                                  "/usr/lib/sendmail")
4445                                nil errbuf nil "-oi")
4446                          ;; Always specify who from,
4447                          ;; since some systems have broken sendmails.
4448                          ;; But some systems are more broken with -f, so
4449                          ;; we'll let users override this.
4450                          (if (null message-sendmail-f-is-evil)
4451                              (list "-f" (message-sendmail-envelope-from)))
4452                          ;; These mean "report errors by mail"
4453                          ;; and "deliver in background".
4454                          (if (null message-interactive) '("-oem" "-odb"))
4455                          ;; Get the addresses from the message
4456                          ;; unless this is a resend.
4457                          ;; We must not do that for a resend
4458                          ;; because we would find the original addresses.
4459                          ;; For a resend, include the specific addresses.
4460                          (if resend-to-addresses
4461                              (list resend-to-addresses)
4462                            '("-t")))))))
4463             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4464               (error "Sending...failed with exit value %d" cpr)))
4465           (when message-interactive
4466             (save-excursion
4467               (set-buffer errbuf)
4468               (goto-char (point-min))
4469               (while (re-search-forward "\n+ *" nil t)
4470                 (replace-match "; "))
4471               (if (not (zerop (buffer-size)))
4472                   (error "Sending...failed to %s"
4473                          (buffer-string))))))
4474       (when (bufferp errbuf)
4475         (kill-buffer errbuf)))))
4476
4477 (defun message-send-mail-with-qmail ()
4478   "Pass the prepared message buffer to qmail-inject.
4479 Refer to the documentation for the variable `message-send-mail-function'
4480 to find out how to use this."
4481   ;; replace the header delimiter with a blank line
4482   (goto-char (point-min))
4483   (re-search-forward
4484    (concat "^" (regexp-quote mail-header-separator) "\n"))
4485   (replace-match "\n")
4486   (backward-char 1)
4487   (run-hooks 'message-send-mail-hook)
4488   ;; send the message
4489   (case
4490       (as-binary-process
4491        (apply
4492         'call-process-region (point-min) (point-max)
4493         message-qmail-inject-program nil nil nil
4494         ;; qmail-inject's default behaviour is to look for addresses on the
4495         ;; command line; if there're none, it scans the headers.
4496         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4497         ;;
4498         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4499         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4500         ;; message from stdin.
4501         ;;
4502         ;; qmail also has the advantage of not having been raped by
4503         ;; various vendors, so we don't have to allow for that, either --
4504         ;; compare this with message-send-mail-with-sendmail and weep
4505         ;; for sendmail's lost innocence.
4506         ;;
4507         ;; all this is way cool coz it lets us keep the arguments entirely
4508         ;; free for -inject-arguments -- a big win for the user and for us
4509         ;; since we don't have to play that double-guessing game and the user
4510         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4511         (if (functionp message-qmail-inject-args)
4512             (funcall message-qmail-inject-args)
4513           message-qmail-inject-args)))
4514     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4515     ;; we have to look at the retval instead
4516     (0 nil)
4517     (100 (error "qmail-inject reported permanent failure"))
4518     (111 (error "qmail-inject reported transient failure"))
4519     ;; should never happen
4520     (t   (error "qmail-inject reported unknown failure"))))
4521
4522 (defun message-send-mail-with-mh ()
4523   "Send the prepared message buffer with mh."
4524   (let ((mh-previous-window-config nil)
4525         (name (mh-new-draft-name)))
4526     (setq buffer-file-name name)
4527     ;; MH wants to generate these headers itself.
4528     (when message-mh-deletable-headers
4529       (let ((headers message-mh-deletable-headers))
4530         (while headers
4531           (goto-char (point-min))
4532           (and (re-search-forward
4533                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4534                (message-delete-line))
4535           (pop headers))))
4536     (run-hooks 'message-send-mail-hook)
4537     ;; Pass it on to mh.
4538     (mh-send-letter)))
4539
4540 (defun message-send-mail-with-smtp ()
4541   "Send off the prepared buffer with SMTP."
4542   (require 'smtp) ; XXX
4543   (let ((case-fold-search t)
4544         recipients)
4545     (save-restriction
4546       (message-narrow-to-headers)
4547       (setq recipients
4548             ;; XXX: Should be replaced by better one.
4549             (smtp-deduce-address-list (current-buffer)
4550                                       (point-min) (point-max)))
4551       ;; Remove BCC lines.
4552       (message-remove-header "bcc"))
4553     ;; replace the header delimiter with a blank line.
4554     (goto-char (point-min))
4555     (re-search-forward
4556      (concat "^" (regexp-quote mail-header-separator) "\n"))
4557     (replace-match "\n")
4558     (backward-char 1)
4559     (run-hooks 'message-send-mail-hook)
4560     (if recipients
4561         (smtp-send-buffer user-mail-address recipients (current-buffer))
4562       (error "Sending failed; no recipients"))))
4563
4564 (defsubst message-maybe-split-and-send-news (method)
4565   "Split a message if necessary, and send it via news.
4566 Returns nil if sending succeeded, returns t if sending failed.
4567 This sub function is for exclusive use of `message-send-news'."
4568   (let ((mime-edit-split-ignored-field-regexp
4569          mime-edit-split-ignored-field-regexp)
4570         (case-fold-search t))
4571     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4572       (setq mime-edit-split-ignored-field-regexp
4573             (concat (substring mime-edit-split-ignored-field-regexp
4574                                0 (match-beginning 0))
4575                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4576                     "_so_don't_rape_it!"
4577                     (substring mime-edit-split-ignored-field-regexp
4578                                (match-end 0)))))
4579     (or
4580      (catch 'message-sending-news-failure
4581        (mime-edit-maybe-split-and-send
4582         (function
4583          (lambda ()
4584            (interactive)
4585            (save-restriction
4586              (std11-narrow-to-header mail-header-separator)
4587              (goto-char (point-min))
4588              (when (re-search-forward "^Message-ID:" nil t)
4589                (delete-region (match-end 0) (std11-field-end))
4590                (insert " " (message-make-message-id))))
4591            (unless (funcall message-send-news-function method)
4592              (throw 'message-sending-news-failure t)))))
4593        nil)
4594      (not (funcall message-send-news-function method)))))
4595
4596 (defun message-smtpmail-send-it ()
4597   "Send the prepared message buffer with `smtpmail-send-it'.
4598 This only differs from `smtpmail-send-it' that this command evaluates
4599 `message-send-mail-hook' just before sending a message.  It is useful
4600 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4601 manual for details."
4602   (run-hooks 'message-send-mail-hook)
4603   (smtpmail-send-it))
4604
4605 (defun message-canlock-generate ()
4606   "Return a string that is non-trivial to guess.
4607 Do not use this for anything important, it is cryptographically weak."
4608   (require 'sha1)
4609   (let (sha1-maximum-internal-length)
4610     (sha1 (concat (message-unique-id)
4611                   (format "%x%x%x" (random) (random t) (random))
4612                   (prin1-to-string (recent-keys))
4613                   (prin1-to-string (garbage-collect))))))
4614
4615 (defun message-canlock-password ()
4616   "The password used by message for cancel locks.
4617 This is the value of `canlock-password', if that option is non-nil.
4618 Otherwise, generate and save a value for `canlock-password' first."
4619   (unless canlock-password
4620     (customize-save-variable 'canlock-password (message-canlock-generate))
4621     (setq canlock-password-for-verify canlock-password))
4622   canlock-password)
4623
4624 (defun message-insert-canlock ()
4625   (when message-insert-canlock
4626     (message-canlock-password)
4627     (canlock-insert-header)))
4628
4629 (defun message-send-news (&optional arg)
4630   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4631          (case-fold-search nil)
4632          (method (if (functionp message-post-method)
4633                      (funcall message-post-method arg)
4634                    message-post-method))
4635          (newsgroups-field (save-restriction
4636                              (message-narrow-to-headers-or-head)
4637                              (message-fetch-field "Newsgroups")))
4638          (followup-field (save-restriction
4639                            (message-narrow-to-headers-or-head)
4640                            (message-fetch-field "Followup-To")))
4641          ;; BUG: We really need to get the charset for each name in the
4642          ;; Newsgroups and Followup-To lines to allow crossposting
4643          ;; between group namess with incompatible character sets.
4644          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4645          (group-field-charset
4646           (gnus-group-name-charset method newsgroups-field))
4647          (followup-field-charset
4648           (gnus-group-name-charset method (or followup-field "")))
4649          (mime-field-encoding-method-alist
4650           (append (when group-field-charset
4651                     (list (cons "Newsgroups" group-field-charset)))
4652                   (when followup-field-charset
4653                     (list (cons "Followup-To" followup-field-charset)))
4654                   mime-field-encoding-method-alist))
4655          (message-syntax-checks
4656           (if (and arg
4657                    (listp message-syntax-checks))
4658               (cons '(existing-newsgroups . disabled)
4659                     message-syntax-checks)
4660             message-syntax-checks))
4661          (message-this-is-news t)
4662          result)
4663     (save-restriction
4664       (message-narrow-to-headers)
4665       ;; Insert some headers.
4666       (message-generate-headers message-required-news-headers)
4667       (message-insert-canlock)
4668       ;; Let the user do all of the above.
4669       (run-hooks 'message-header-hook))
4670     ;; Note: This check will be disabled by the ".*" default value for
4671     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4672     (when (and group-field-charset
4673                (listp message-syntax-checks))
4674       (setq message-syntax-checks
4675             (cons '(valid-newsgroups . disabled)
4676                   message-syntax-checks)))
4677     (message-cleanup-headers)
4678     (if (not (let ((message-post-method method))
4679                (message-check-news-syntax)))
4680         nil
4681       (unwind-protect
4682           (save-excursion
4683             (set-buffer tembuf)
4684             (buffer-disable-undo)
4685             (erase-buffer)
4686             (insert-buffer-substring message-encoding-buffer)
4687             ;; Remove some headers.
4688             (save-restriction
4689               (message-narrow-to-headers)
4690 ;; We Semi-gnus people have no use for it.
4691 ;;            ;; We (re)generate the Lines header.
4692 ;;            (when (memq 'Lines message-required-mail-headers)
4693 ;;              (message-generate-headers '(Lines)))
4694               ;; Remove some headers.
4695               (message-remove-header message-ignored-news-headers t))
4696             (goto-char (point-max))
4697             ;; require one newline at the end.
4698             (or (= (preceding-char) ?\n)
4699                 (insert ?\n))
4700             (setq result (message-maybe-split-and-send-news method)))
4701         (kill-buffer tembuf))
4702       (set-buffer message-edit-buffer)
4703       (if result
4704           (progn
4705             (message "Couldn't send message via news: %s"
4706                      (nnheader-get-report (car method)))
4707             nil)
4708         (push 'news message-sent-message-via)))))
4709
4710 ;; 1997-09-29 by MORIOKA Tomohiko
4711 (defun message-send-news-with-gnus (method)
4712   (let ((case-fold-search t))
4713     ;; Remove the delimiter.
4714     (goto-char (point-min))
4715     (re-search-forward
4716      (concat "^" (regexp-quote mail-header-separator) "\n"))
4717     (replace-match "\n")
4718     (backward-char 1)
4719     (run-hooks 'message-send-news-hook)
4720     (gnus-open-server method)
4721     (message "Sending news via %s..." (gnus-server-string method))
4722     (gnus-request-post method)
4723     ))
4724
4725 ;;;
4726 ;;; Header generation & syntax checking.
4727 ;;;
4728
4729 (defun message-check-element (type)
4730   "Return non-nil if this TYPE is not to be checked."
4731   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4732       t
4733     (let ((able (assq type message-syntax-checks)))
4734       (and (consp able)
4735            (eq (cdr able) 'disabled)))))
4736
4737 (defun message-check-news-syntax ()
4738   "Check the syntax of the message."
4739   (save-excursion
4740     (save-restriction
4741       (widen)
4742       (and
4743        ;; We narrow to the headers and check them first.
4744        (save-excursion
4745          (save-restriction
4746            (message-narrow-to-headers)
4747            (message-check-news-header-syntax)))
4748        ;; Check the body.
4749        (save-excursion
4750          (set-buffer message-edit-buffer)
4751          (message-check-news-body-syntax))))))
4752
4753 (defun message-check-news-header-syntax ()
4754   (and
4755    ;; Check Newsgroups header.
4756    (message-check 'newsgroups
4757      (let ((group (message-fetch-field "newsgroups")))
4758        (or
4759         (and group
4760              (not (string-match "\\`[ \t]*\\'" group)))
4761         (ignore
4762          (message
4763           "The newsgroups field is empty or missing.  Posting is denied.")))))
4764    ;; Check the Subject header.
4765    (message-check 'subject
4766      (let* ((case-fold-search t)
4767             (subject (message-fetch-field "subject")))
4768        (or
4769         (and subject
4770              (not (string-match "\\`[ \t]*\\'" subject)))
4771         (ignore
4772          (message
4773           "The subject field is empty or missing.  Posting is denied.")))))
4774    ;; Check for commands in Subject.
4775    (message-check 'subject-cmsg
4776      (if (string-match "^cmsg " (message-fetch-field "subject"))
4777          (y-or-n-p
4778           "The control code \"cmsg\" is in the subject.  Really post? ")
4779        t))
4780    ;; Check long header lines.
4781    (message-check 'long-header-lines
4782      (let ((start (point))
4783            (header nil)
4784            (length 0)
4785            found)
4786        (while (and (not found)
4787                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4788          (if (> (- (point) (match-beginning 0)) 998)
4789              (setq found t
4790                    length (- (point) (match-beginning 0)))
4791            (setq header (match-string-no-properties 1)))
4792          (setq start (match-beginning 0))
4793          (forward-line 1))
4794        (if found
4795            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4796                              header length))
4797          t)))
4798    ;; Check for multiple identical headers.
4799    (message-check 'multiple-headers
4800      (let (found)
4801        (while (and (not found)
4802                    (re-search-forward "^[^ \t:]+: " nil t))
4803          (save-excursion
4804            (or (re-search-forward
4805                 (concat "^"
4806                         (regexp-quote
4807                          (setq found
4808                                (buffer-substring
4809                                 (match-beginning 0) (- (match-end 0) 2))))
4810                         ":")
4811                 nil t)
4812                (setq found nil))))
4813        (if found
4814            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4815          t)))
4816    ;; Check for Version and Sendsys.
4817    (message-check 'sendsys
4818      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4819          (y-or-n-p
4820           (format "The article contains a %s command.  Really post? "
4821                   (buffer-substring (match-beginning 0)
4822                                     (1- (match-end 0)))))
4823        t))
4824    ;; See whether we can shorten Followup-To.
4825    (message-check 'shorten-followup-to
4826      (let ((newsgroups (message-fetch-field "newsgroups"))
4827            (followup-to (message-fetch-field "followup-to"))
4828            to)
4829        (when (and newsgroups
4830                   (string-match "," newsgroups)
4831                   (not followup-to)
4832                   (not
4833                    (zerop
4834                     (length
4835                      (setq to (completing-read
4836                                "Followups to (default no Followup-To header): "
4837                                (mapcar #'list
4838                                        (cons "poster"
4839                                              (message-tokenize-header
4840                                               newsgroups)))))))))
4841          (goto-char (point-min))
4842          (insert "Followup-To: " to "\n"))
4843        t))
4844    ;; Check "Shoot me".
4845    (message-check 'shoot
4846      (if (re-search-forward
4847           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4848          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4849        t))
4850    ;; Check for Approved.
4851    (message-check 'approved
4852      (if (re-search-forward "^Approved:" nil t)
4853          (y-or-n-p "The article contains an Approved header.  Really post? ")
4854        t))
4855    ;; Check the Message-ID header.
4856    (message-check 'message-id
4857      (let* ((case-fold-search t)
4858             (message-id (message-fetch-field "message-id" t)))
4859        (or (not message-id)
4860            ;; Is there an @ in the ID?
4861            (and (string-match "@" message-id)
4862                 ;; Is there a dot in the ID?
4863                 (string-match "@[^.]*\\." message-id)
4864                 ;; Does the ID end with a dot?
4865                 (not (string-match "\\.>" message-id)))
4866            (y-or-n-p
4867             (format "The Message-ID looks strange: \"%s\".  Really post? "
4868                     message-id)))))
4869    ;; Check the Newsgroups & Followup-To headers.
4870    (message-check 'existing-newsgroups
4871      (let* ((case-fold-search t)
4872             (newsgroups (message-fetch-field "newsgroups"))
4873             (followup-to (message-fetch-field "followup-to"))
4874             (groups (message-tokenize-header
4875                      (if followup-to
4876                          (concat newsgroups "," followup-to)
4877                        newsgroups)))
4878             (post-method (if (functionp message-post-method)
4879                              (funcall message-post-method)
4880                            message-post-method))
4881             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4882             ;; would probably involve a new nnoo function.
4883             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4884             (method (if (and (consp post-method)
4885                              (eq (car post-method) 'nnvirtual)
4886                              gnus-message-group-art)
4887                         (let ((group (car (nnvirtual-find-group-art
4888                                            (car gnus-message-group-art)
4889                                            (cdr gnus-message-group-art)))))
4890                           (gnus-find-method-for-group group))
4891                       post-method))
4892             (known-groups
4893              (mapcar (lambda (n)
4894                        (gnus-group-name-decode
4895                         (gnus-group-real-name n)
4896                         (gnus-group-name-charset method n)))
4897                      (gnus-groups-from-server method)))
4898             errors)
4899        (while groups
4900          (when (and (not (equal (car groups) "poster"))
4901                     (not (member (car groups) known-groups))
4902                     (not (member (car groups) errors)))
4903            (push (car groups) errors))
4904          (pop groups))
4905        (cond
4906         ;; Gnus is not running.
4907         ((or (not (and (boundp 'gnus-active-hashtb)
4908                        gnus-active-hashtb))
4909              (not (boundp 'gnus-read-active-file)))
4910          t)
4911         ;; We don't have all the group names.
4912         ((and (or (not gnus-read-active-file)
4913                   (eq gnus-read-active-file 'some))
4914               errors)
4915          (y-or-n-p
4916           (format
4917            "Really use %s possibly unknown group%s: %s? "
4918            (if (= (length errors) 1) "this" "these")
4919            (if (= (length errors) 1) "" "s")
4920            (mapconcat 'identity errors ", "))))
4921         ;; There were no errors.
4922         ((not errors)
4923          t)
4924         ;; There are unknown groups.
4925         (t
4926          (y-or-n-p
4927           (format
4928            "Really post to %s unknown group%s: %s? "
4929            (if (= (length errors) 1) "this" "these")
4930            (if (= (length errors) 1) "" "s")
4931            (mapconcat 'identity errors ", ")))))))
4932    ;; Check continuation headers.
4933    (message-check 'continuation-headers
4934      (goto-char (point-min))
4935      (let ((do-posting t))
4936        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4937          (if (y-or-n-p "Fix continuation lines? ")
4938              (progn
4939                (goto-char (match-beginning 0))
4940                (insert " "))
4941            (unless (y-or-n-p "Send anyway? ")
4942              (setq do-posting nil))))
4943        do-posting))
4944    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4945    (message-check 'valid-newsgroups
4946      (let ((case-fold-search t)
4947            (headers '("Newsgroups" "Followup-To"))
4948            header error)
4949        (while (and headers (not error))
4950          (when (setq header (mail-fetch-field (car headers)))
4951            (if (or
4952                 (not
4953                  (string-match
4954                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4955                   header))
4956                 (memq
4957                  nil (mapcar
4958                       (lambda (g)
4959                         (not (string-match "\\.\\'\\|\\.\\." g)))
4960                       (message-tokenize-header header ","))))
4961                (setq error t)))
4962          (unless error
4963            (pop headers)))
4964        (if (not error)
4965            t
4966          (y-or-n-p
4967           (format "The %s header looks odd: \"%s\".  Really post? "
4968                   (car headers) header)))))
4969    (message-check 'repeated-newsgroups
4970      (let ((case-fold-search t)
4971            (headers '("Newsgroups" "Followup-To"))
4972            header error groups group)
4973        (while (and headers
4974                    (not error))
4975          (when (setq header (mail-fetch-field (pop headers)))
4976            (setq groups (message-tokenize-header header ","))
4977            (while (setq group (pop groups))
4978              (when (member group groups)
4979                (setq error group
4980                      groups nil)))))
4981        (if (not error)
4982            t
4983          (y-or-n-p
4984           (format "Group %s is repeated in headers.  Really post? " error)))))
4985    ;; Check the From header.
4986    (message-check 'from
4987      (let* ((case-fold-search t)
4988             (from (message-fetch-field "from"))
4989             ad)
4990        (cond
4991         ((not from)
4992          (message "There is no From line.  Posting is denied.")
4993          nil)
4994         ((or (not (string-match
4995                    "@[^\\.]*\\."
4996                    (setq ad (nth 1 (std11-extract-address-components
4997                                     from))))) ;larsi@ifi
4998              (string-match "\\.\\." ad) ;larsi@ifi..uio
4999              (string-match "@\\." ad)   ;larsi@.ifi.uio
5000              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5001              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5002              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
5003          (message
5004           "Denied posting -- the From looks strange: \"%s\"." from)
5005          nil)
5006         ((let ((addresses (rfc822-addresses from)))
5007            (while (and addresses
5008                        (not (eq (string-to-char (car addresses)) ?\()))
5009              (setq addresses (cdr addresses)))
5010            addresses)
5011          (message
5012           "Denied posting -- bad From address: \"%s\"." from)
5013          nil)
5014         (t t))))
5015    ;; Check the Reply-To header.
5016    (message-check 'reply-to
5017      (let* ((case-fold-search t)
5018             (reply-to (message-fetch-field "reply-to"))
5019             ad)
5020        (cond
5021         ((not reply-to)
5022          t)
5023         ((string-match "," reply-to)
5024          (y-or-n-p
5025           (format "Multiple Reply-To addresses: \"%s\". Really post? "
5026                   reply-to)))
5027         ((or (not (string-match
5028                    "@[^\\.]*\\."
5029                    (setq ad (nth 1 (std11-extract-address-components
5030                                     reply-to))))) ;larsi@ifi
5031              (string-match "\\.\\." ad) ;larsi@ifi..uio
5032              (string-match "@\\." ad)   ;larsi@.ifi.uio
5033              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5034              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5035              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5036          (y-or-n-p
5037           (format
5038            "The Reply-To looks strange: \"%s\". Really post? "
5039            reply-to)))
5040         (t t))))))
5041
5042 (defun message-check-news-body-syntax ()
5043   (and
5044    ;; Check for long lines.
5045    (message-check 'long-lines
5046      (goto-char (point-min))
5047      (re-search-forward
5048       (concat "^" (regexp-quote mail-header-separator) "$"))
5049      (forward-line 1)
5050      (while (and
5051              (or (looking-at
5052                   mime-edit-tag-regexp)
5053                  (let ((p (point)))
5054                    (end-of-line)
5055                    (< (- (point) p) 80)))
5056              (zerop (forward-line 1))))
5057      (or (bolp)
5058          (eobp)
5059          (y-or-n-p
5060           "You have lines longer than 79 characters.  Really post? ")))
5061    ;; Check whether the article is empty.
5062    (message-check 'empty
5063      (goto-char (point-min))
5064      (re-search-forward
5065       (concat "^" (regexp-quote mail-header-separator) "$"))
5066      (forward-line 1)
5067      (let ((b (point)))
5068        (goto-char (point-max))
5069        (re-search-backward message-signature-separator nil t)
5070        (beginning-of-line)
5071        (or (re-search-backward "[^ \n\t]" b t)
5072            (if (message-gnksa-enable-p 'empty-article)
5073                (y-or-n-p "Empty article.  Really post? ")
5074              (message "Denied posting -- Empty article.")
5075              nil))))
5076    ;; Check for control characters.
5077    (message-check 'control-chars
5078      (if (re-search-forward
5079           (string-as-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5080           nil t)
5081          (y-or-n-p
5082           "The article contains control characters.  Really post? ")
5083        t))
5084    ;; Check 8bit characters.
5085    (message-check '8bit
5086      (message-check-8bit))
5087    ;; Check excessive size.
5088    (message-check 'size
5089      (if (> (buffer-size) 60000)
5090          (y-or-n-p
5091           (format "The article is %d octets long.  Really post? "
5092                   (buffer-size)))
5093        t))
5094    ;; Check whether any new text has been added.
5095    (message-check 'new-text
5096      (or
5097       (not message-checksum)
5098       (not (eq (message-checksum) message-checksum))
5099       (if (message-gnksa-enable-p 'quoted-text-only)
5100           (y-or-n-p
5101            "It looks like no new text has been added.  Really post? ")
5102         (message "Denied posting -- no new text has been added.")
5103         nil)))
5104    ;; Check the length of the signature.
5105    (message-check 'signature
5106      (goto-char (point-max))
5107      (if (> (count-lines (point) (point-max)) 5)
5108          (y-or-n-p
5109           (format
5110            "Your .sig is %d lines; it should be max 4.  Really post? "
5111            (1- (count-lines (point) (point-max)))))
5112        t))
5113    ;; Ensure that text follows last quoted portion.
5114    (message-check 'quoting-style
5115      (goto-char (point-max))
5116      (let ((no-problem t))
5117        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5118          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5119        (if no-problem
5120            t
5121          (if (message-gnksa-enable-p 'quoted-text-only)
5122              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5123            ;; Ensure that
5124            (goto-char (point-min))
5125            (re-search-forward
5126             (concat "^" (regexp-quote mail-header-separator) "$"))
5127            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5128                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5129              (message "Denied posting -- only quoted text.")
5130              nil)))))))
5131
5132 (defun message-check-mail-syntax ()
5133   "Check the syntax of the message."
5134   (save-excursion
5135     (save-restriction
5136       (widen)
5137       (and
5138        ;; We narrow to the headers and check them first.
5139        (save-excursion
5140          (save-restriction
5141            (message-narrow-to-headers)
5142            (message-check-mail-header-syntax)))
5143        ;; Check the body.
5144        (save-excursion
5145          (set-buffer message-edit-buffer)
5146          (message-check-mail-body-syntax))))))
5147
5148 (defun message-check-mail-header-syntax ()
5149   t)
5150
5151 (defun message-check-mail-body-syntax ()
5152   (and
5153    ;; Check 8bit characters.
5154    (message-check '8bit
5155      (message-check-8bit)
5156      )))
5157
5158 (defun message-check-8bit ()
5159   "Check the article contains 8bit characters."
5160   (save-excursion
5161     (set-buffer message-encoding-buffer)
5162     (message-narrow-to-headers)
5163     (let* ((case-fold-search t)
5164            (field-value (message-fetch-field "content-transfer-encoding")))
5165       (if (and field-value
5166                (member (downcase field-value) message-8bit-encoding-list))
5167           t
5168         (widen)
5169         (set-buffer (get-buffer-create " message syntax"))
5170         (erase-buffer)
5171         (goto-char (point-min))
5172         (set-buffer-multibyte nil)
5173         (insert-buffer-substring message-encoding-buffer)
5174         (goto-char (point-min))
5175         (if (re-search-forward "[^\x00-\x7f]" nil t)
5176             (y-or-n-p
5177              "The article contains 8bit characters.  Really post? ")
5178           t)))))
5179
5180 (defun message-checksum ()
5181   "Return a \"checksum\" for the current buffer."
5182   (let ((sum 0))
5183     (save-excursion
5184       (goto-char (point-min))
5185       (re-search-forward
5186        (concat "^" (regexp-quote mail-header-separator) "$"))
5187       (while (not (eobp))
5188         (when (not (looking-at "[ \t\n]"))
5189           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5190                             (char-after))))
5191         (forward-char 1)))
5192     sum))
5193
5194 (defun message-do-fcc ()
5195   "Process Fcc headers in the current buffer."
5196   (let ((case-fold-search t)
5197         (coding-system-for-write 'raw-text)
5198         list file
5199         (mml-externalize-attachments message-fcc-externalize-attachments))
5200     (save-excursion
5201       (save-restriction
5202         (message-narrow-to-headers)
5203         (setq file (message-fetch-field "fcc" t)))
5204       (when file
5205         (set-buffer (get-buffer-create " *message temp*"))
5206         (erase-buffer)
5207         (insert-buffer-substring message-encoding-buffer)
5208         (save-restriction
5209           (message-narrow-to-headers)
5210           (while (setq file (message-fetch-field "fcc"))
5211             (push file list)
5212             (message-remove-header "fcc" nil t)))
5213         (goto-char (point-min))
5214         (when (re-search-forward
5215                (concat "^" (regexp-quote mail-header-separator) "$")
5216                nil t)
5217           (replace-match "" t t))
5218         ;; Process FCC operations.
5219         (while list
5220           (setq file (pop list))
5221           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5222               ;; Pipe the article to the program in question.
5223               (call-process-region (point-min) (point-max) shell-file-name
5224                                    nil nil nil shell-command-switch
5225                                    (match-string 1 file))
5226             ;; Save the article.
5227             (setq file (expand-file-name file))
5228             (unless (file-exists-p (file-name-directory file))
5229               (make-directory (file-name-directory file) t))
5230             (if (and message-fcc-handler-function
5231                      (not (eq message-fcc-handler-function 'rmail-output)))
5232                 (funcall message-fcc-handler-function file)
5233               (if (and (file-readable-p file) (mail-file-babyl-p file))
5234                   (rmail-output file 1 nil t)
5235                 (let ((mail-use-rfc822 t))
5236                   (rmail-output file 1 t t))))))
5237         (kill-buffer (current-buffer))))))
5238
5239 (defun message-output (filename)
5240   "Append this article to Unix/babyl mail file FILENAME."
5241   (if (and (file-readable-p filename)
5242            (mail-file-babyl-p filename))
5243       (gnus-output-to-rmail filename t)
5244     (gnus-output-to-mail filename t)))
5245
5246 (defun message-cleanup-headers ()
5247   "Do various automatic cleanups of the headers."
5248   ;; Remove empty lines in the header.
5249   (save-restriction
5250     (message-narrow-to-headers)
5251     ;; Remove blank lines.
5252     (while (re-search-forward "^[ \t]*\n" nil t)
5253       (replace-match "" t t))
5254
5255     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5256     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5257     ;; embedded line breaks.
5258     (goto-char (point-min))
5259     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5260       (save-restriction
5261         (narrow-to-region
5262          (point)
5263          (if (re-search-forward "^[^ \t]" nil t)
5264              (match-beginning 0)
5265            (forward-line 1)
5266            (point)))
5267         (goto-char (point-min))
5268         (while (re-search-forward "\n[ \t]+" nil t)
5269           (replace-match " " t t))      ;No line breaks (too confusing)
5270         (goto-char (point-min))
5271         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5272           (replace-match "," t t))
5273         (goto-char (point-min))
5274         ;; Remove trailing commas.
5275         (when (re-search-forward ",+$" nil t)
5276           (replace-match "" t t))))))
5277
5278 (defun message-make-date (&optional now)
5279   "Make a valid data header.
5280 If NOW, use that time instead."
5281   (let ((system-time-locale "C"))
5282     (format-time-string "%a, %d %b %Y %T %z" now)))
5283
5284 (defun message-make-followup-subject (subject)
5285   "Make a followup Subject."
5286   (cond
5287    ((and (eq message-use-subject-re 'guess)
5288          (string-match message-subject-encoded-re-regexp subject))
5289     subject)
5290    (message-use-subject-re
5291     (concat "Re: " (message-strip-subject-re subject)))
5292    (t subject)))
5293
5294 (defun message-insert-expires (days)
5295   "Insert the Expires header.  Expiry in DAYS days."
5296   (interactive "NExpire article in how many days? ")
5297   (save-excursion
5298     (message-position-on-field "Expires" "X-Draft-From")
5299     (insert (message-make-expires-date days))))
5300
5301 (defun message-make-expires-date (days)
5302   "Make date string for the Expires header.  Expiry in DAYS days.
5303
5304 In posting styles use `(\"Expires\" (make-expires-date 30))'."
5305   (let* ((cur (decode-time (current-time)))
5306          (nday (+ days (nth 3 cur))))
5307     (setf (nth 3 cur) nday)
5308     (message-make-date (apply 'encode-time cur))))
5309
5310 (defun message-make-message-id ()
5311   "Make a unique Message-ID."
5312   (concat "<" (message-unique-id)
5313           (let ((psubject (save-excursion (message-fetch-field "subject")))
5314                 (psupersedes
5315                  (save-excursion (message-fetch-field "supersedes"))))
5316             (if (or
5317                  (and message-reply-headers
5318                       (mail-header-references message-reply-headers)
5319                       (mail-header-subject message-reply-headers)
5320                       psubject
5321                       (not (string=
5322                             (message-strip-subject-re
5323                              (mail-header-subject message-reply-headers))
5324                             (message-strip-subject-re psubject))))
5325                  (and psupersedes
5326                       (string-match "_-_@" psupersedes)))
5327                 "_-_" ""))
5328           "@" (message-make-fqdn) ">"))
5329
5330 (defvar message-unique-id-char nil)
5331
5332 ;; If you ever change this function, make sure the new version
5333 ;; cannot generate IDs that the old version could.
5334 ;; You might for example insert a "." somewhere (not next to another dot
5335 ;; or string boundary), or modify the "fsf" string.
5336 (defun message-unique-id ()
5337   ;; Don't use microseconds from (current-time), they may be unsupported.
5338   ;; Instead we use this randomly inited counter.
5339   (setq message-unique-id-char
5340         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5341            ;; (current-time) returns 16-bit ints,
5342            ;; and 2^16*25 just fits into 4 digits i base 36.
5343            (* 25 25)))
5344   (let ((tm (current-time)))
5345     (concat
5346      (if (memq system-type '(ms-dos emx vax-vms))
5347          (let ((user (downcase (user-login-name))))
5348            (while (string-match "[^a-z0-9_]" user)
5349              (aset user (match-beginning 0) ?_))
5350            user)
5351        (message-number-base36 (user-uid) -1))
5352      (message-number-base36 (+ (car tm)
5353                                (lsh (% message-unique-id-char 25) 16)) 4)
5354      (message-number-base36 (+ (nth 1 tm)
5355                                (lsh (/ message-unique-id-char 25) 16)) 4)
5356      ;; Append a given name, because while the generated ID is unique
5357      ;; to this newsreader, other newsreaders might otherwise generate
5358      ;; the same ID via another algorithm.
5359      ".fsf")))
5360
5361 (defun message-number-base36 (num len)
5362   (if (if (< len 0)
5363           (<= num 0)
5364         (= len 0))
5365       ""
5366     (concat (message-number-base36 (/ num 36) (1- len))
5367             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5368                                   (% num 36))))))
5369
5370 (defun message-make-organization ()
5371   "Make an Organization header."
5372   (let* ((organization
5373           (when message-user-organization
5374             (if (functionp message-user-organization)
5375                 (funcall message-user-organization)
5376               message-user-organization))))
5377     (with-temp-buffer
5378       (set-buffer-multibyte t)
5379       (cond ((stringp organization)
5380              (insert organization))
5381             ((and (eq t organization)
5382                   message-user-organization-file
5383                   (file-exists-p message-user-organization-file))
5384              (insert-file-contents message-user-organization-file)))
5385       (goto-char (point-min))
5386       (while (re-search-forward "[\t\n]+" nil t)
5387         (replace-match "" t t))
5388       (unless (zerop (buffer-size))
5389         (buffer-string)))))
5390
5391 (defun message-make-lines ()
5392   "Count the number of lines and return numeric string."
5393   (save-excursion
5394     (save-restriction
5395       (widen)
5396       (message-goto-body)
5397       (int-to-string (count-lines (point) (point-max))))))
5398
5399 (defun message-make-references ()
5400   "Return the References header for this message."
5401   (when message-reply-headers
5402     (let ((message-id (mail-header-message-id message-reply-headers))
5403           (references (mail-header-references message-reply-headers))
5404           new-references)
5405       (if (or references message-id)
5406           (concat (or references "") (and references " ")
5407                   (or message-id ""))
5408         nil))))
5409
5410 (defun message-make-in-reply-to ()
5411   "Return the In-Reply-To header for this message."
5412   (when message-reply-headers
5413     (let ((from (mail-header-from message-reply-headers))
5414           (date (mail-header-date message-reply-headers))
5415           (msg-id (mail-header-message-id message-reply-headers)))
5416       (when from
5417         (let ((name (std11-extract-address-components from)))
5418           (concat msg-id (if msg-id " (")
5419                   (or (car name)
5420                       (nth 1 name))
5421                   "'s message of \""
5422                   (if (or (not date) (string= date ""))
5423                       "(unknown date)" date)
5424                   "\"" (if msg-id ")")))))))
5425
5426 (defun message-make-distribution ()
5427   "Make a Distribution header."
5428   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5429     (cond ((functionp message-distribution-function)
5430            (funcall message-distribution-function))
5431           (t orig-distribution))))
5432
5433 (defun message-make-expires ()
5434   "Return an Expires header based on `message-expires'."
5435   (let ((current (current-time))
5436         (future (* 1.0 message-expires 60 60 24)))
5437     ;; Add the future to current.
5438     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5439     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5440     (message-make-date current)))
5441
5442 (defun message-make-path ()
5443   "Return uucp path."
5444   (let ((login-name (user-login-name)))
5445     (cond ((null message-user-path)
5446            (concat (system-name) "!" login-name))
5447           ((stringp message-user-path)
5448            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5449            (concat message-user-path "!" login-name))
5450           (t login-name))))
5451
5452 (defun message-make-from ()
5453   "Make a From header."
5454   (let* ((style message-from-style)
5455          (login (message-make-address))
5456          (fullname
5457           (or (and (boundp 'user-full-name)
5458                    user-full-name)
5459               (user-full-name))))
5460     (when (string= fullname "&")
5461       (setq fullname (user-login-name)))
5462     (with-temp-buffer
5463       (set-buffer-multibyte t)
5464       (cond
5465        ((or (null style)
5466             (equal fullname ""))
5467         (insert login))
5468        ((or (eq style 'angles)
5469             (and (not (eq style 'parens))
5470                  ;; Use angles if no quoting is needed, or if parens would
5471                  ;; need quoting too.
5472                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5473                      (let ((tmp (concat fullname nil)))
5474                        (while (string-match "([^()]*)" tmp)
5475                          (aset tmp (match-beginning 0) ?-)
5476                          (aset tmp (1- (match-end 0)) ?-))
5477                        (string-match "[\\()]" tmp)))))
5478         (insert fullname)
5479         (goto-char (point-min))
5480         ;; Look for a character that cannot appear unquoted
5481         ;; according to RFC 822.
5482         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5483           ;; Quote fullname, escaping specials.
5484           (goto-char (point-min))
5485           (insert "\"")
5486           (while (re-search-forward "[\"\\]" nil 1)
5487             (replace-match "\\\\\\&" t))
5488           (insert "\""))
5489         (insert " <" login ">"))
5490        (t                               ; 'parens or default
5491         (insert login " (")
5492         (let ((fullname-start (point)))
5493           (insert fullname)
5494           (goto-char fullname-start)
5495           ;; RFC 822 says \ and nonmatching parentheses
5496           ;; must be escaped in comments.
5497           ;; Escape every instance of ()\ ...
5498           (while (re-search-forward "[()\\]" nil 1)
5499             (replace-match "\\\\\\&" t))
5500           ;; ... then undo escaping of matching parentheses,
5501           ;; including matching nested parentheses.
5502           (goto-char fullname-start)
5503           (while (re-search-forward
5504                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5505                   nil 1)
5506             (replace-match "\\1(\\3)" t)
5507             (goto-char fullname-start)))
5508         (insert ")")))
5509       (buffer-string))))
5510
5511 (defun message-make-sender ()
5512   "Return the \"real\" user address.
5513 This function tries to ignore all user modifications, and
5514 give as trustworthy answer as possible."
5515   (concat (user-login-name) "@" (system-name)))
5516
5517 (defun message-make-address ()
5518   "Make the address of the user."
5519   (or (message-user-mail-address)
5520       (concat (user-login-name) "@" (message-make-domain))))
5521
5522 (defun message-user-mail-address ()
5523   "Return the pertinent part of `user-mail-address'."
5524   (when (and user-mail-address
5525              (string-match "@.*\\." user-mail-address))
5526     (if (string-match " " user-mail-address)
5527         (nth 1 (std11-extract-address-components user-mail-address))
5528       user-mail-address)))
5529
5530 (defun message-sendmail-envelope-from ()
5531   "Return the envelope from."
5532   (cond ((eq message-sendmail-envelope-from 'header)
5533          (nth 1 (std11-extract-address-components
5534                  (message-fetch-field "from"))))
5535         ((stringp message-sendmail-envelope-from)
5536          message-sendmail-envelope-from)
5537         (t
5538          (message-make-address))))
5539
5540 (defun message-make-fqdn ()
5541   "Return user's fully qualified domain name."
5542   (let* ((system-name (system-name))
5543          (user-mail (message-user-mail-address))
5544          (user-domain
5545           (if (and user-mail
5546                    (string-match "@\\(.*\\)\\'" user-mail))
5547               (match-string 1 user-mail)))
5548          (case-fold-search t))
5549     (cond
5550      ((and message-user-fqdn
5551            (stringp message-user-fqdn)
5552            (string-match message-valid-fqdn-regexp message-user-fqdn)
5553            (not (string-match message-bogus-system-names message-user-fqdn)))
5554       message-user-fqdn)
5555      ;; `message-user-fqdn' seems to be valid
5556      ((and (string-match message-valid-fqdn-regexp system-name)
5557            (not (string-match message-bogus-system-names system-name)))
5558       ;; `system-name' returned the right result.
5559       system-name)
5560      ;; Try `mail-host-address'.
5561      ((and (boundp 'mail-host-address)
5562            (stringp mail-host-address)
5563            (string-match message-valid-fqdn-regexp mail-host-address)
5564            (not (string-match message-bogus-system-names mail-host-address)))
5565       mail-host-address)
5566      ;; We try `user-mail-address' as a backup.
5567      ((and user-domain
5568            (stringp user-domain)
5569            (string-match message-valid-fqdn-regexp user-domain)
5570            (not (string-match message-bogus-system-names user-domain)))
5571       user-domain)
5572      ;; Default to this bogus thing.
5573      (t
5574       (concat system-name
5575               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5576
5577 (defun message-make-host-name ()
5578   "Return the name of the host."
5579   (let ((fqdn (message-make-fqdn)))
5580     (string-match "^[^.]+\\." fqdn)
5581     (substring fqdn 0 (1- (match-end 0)))))
5582
5583 (defun message-make-domain ()
5584   "Return the domain name."
5585   (or mail-host-address
5586       (message-make-fqdn)))
5587
5588 (defun message-to-list-only ()
5589   "Send a message to the list only.
5590 Remove all addresses but the list address from To and Cc headers."
5591   (interactive)
5592   (let ((listaddr (message-make-mail-followup-to t)))
5593     (when listaddr
5594       (save-excursion
5595         (message-remove-header "to")
5596         (message-remove-header "cc")
5597         (message-position-on-field "To" "X-Draft-From")
5598         (insert listaddr)))))
5599
5600 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5601   "Return the Mail-Followup-To header.
5602 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5603 subscribed address (and not the additional To and Cc header contents)."
5604   (let* ((case-fold-search t)
5605          (to (message-fetch-field "To"))
5606          (cc (message-fetch-field "cc"))
5607          (msg-recipients (concat to (and to cc ", ") cc))
5608          (recipients
5609           (mapcar 'mail-strip-quoted-names
5610                   (message-tokenize-header msg-recipients)))
5611          (file-regexps
5612           (if message-subscribed-address-file
5613               (let (begin end item re)
5614                 (save-excursion
5615                   (with-temp-buffer
5616                     (insert-file-contents message-subscribed-address-file)
5617                     (while (not (eobp))
5618                       (setq begin (point))
5619                       (forward-line 1)
5620                       (setq end (point))
5621                       (if (bolp) (setq end (1- end)))
5622                       (setq item (regexp-quote (buffer-substring begin end)))
5623                       (if re (setq re (concat re "\\|" item))
5624                         (setq re (concat "\\`\\(" item))))
5625                     (and re (list (concat re "\\)\\'"))))))))
5626          (mft-regexps (apply 'append message-subscribed-regexps
5627                              (mapcar 'regexp-quote
5628                                      message-subscribed-addresses)
5629                              file-regexps
5630                              (mapcar 'funcall
5631                                      message-subscribed-address-functions))))
5632     (save-match-data
5633       (let ((subscribed-lists nil)
5634             (list
5635              (loop for recipient in recipients
5636                when (loop for regexp in mft-regexps
5637                       when (string-match regexp recipient) return t)
5638                return recipient)))
5639         (when list
5640           (if only-show-subscribed
5641               list
5642             msg-recipients))))))
5643
5644 ;; Dummy to avoid byte-compile warning.
5645 (defvar mule-version)
5646 (defvar emacs-beta-version)
5647 (defvar xemacs-codename)
5648 (defvar gnus-inviolable-extended-version)
5649
5650 (defun message-make-user-agent ()
5651   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5652 \"User-Agent\" field has already exist, remove it."
5653   (when message-user-agent
5654     (save-excursion
5655       (goto-char (point-min))
5656       (let ((case-fold-search t))
5657         (when (re-search-forward "^User-Agent:[\t ]*" nil t)
5658           (delete-region (match-beginning 0) (1+ (std11-field-end)))))))
5659   message-user-agent)
5660
5661 (defun message-idna-to-ascii-rhs-1 (header)
5662   "Interactively potentially IDNA encode domain names in HEADER."
5663   (let ((field (message-fetch-field header))
5664         rhs ace  address)
5665     (when field
5666       (dolist (rhs
5667                (mm-delete-duplicates
5668                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5669                         (mapcar 'downcase
5670                                 (mapcar
5671                                  'car (mail-header-parse-addresses field))))))
5672         (setq ace (downcase (idna-to-ascii rhs)))
5673         (when (and (not (equal rhs ace))
5674                    (or (not (eq message-use-idna 'ask))
5675                        (y-or-n-p (format "Replace %s with %s in %s:? "
5676                                          rhs ace header))))
5677           (goto-char (point-min))
5678           (while (re-search-forward (concat "^" header ":") nil t)
5679             (message-narrow-to-field)
5680             (while (search-forward (concat "@" rhs) nil t)
5681               (replace-match (concat "@" ace) t t))
5682             (goto-char (point-max))
5683             (widen)))))))
5684
5685 (defun message-idna-to-ascii-rhs ()
5686   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5687 See `message-idna-encode'."
5688   (interactive)
5689   (when message-use-idna
5690     (save-excursion
5691       (save-restriction
5692         (message-narrow-to-head)
5693         (message-idna-to-ascii-rhs-1 "From")
5694         (message-idna-to-ascii-rhs-1 "To")
5695         (message-idna-to-ascii-rhs-1 "Reply-To")
5696         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5697         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5698         (message-idna-to-ascii-rhs-1 "Cc")))))
5699
5700 (defun message-generate-headers (headers)
5701   "Prepare article HEADERS.
5702 Headers already prepared in the buffer are not modified."
5703   (setq headers (append headers message-required-headers))
5704   (save-restriction
5705     (message-narrow-to-headers)
5706     (let* ((Date (message-make-date))
5707            (Message-ID (message-make-message-id))
5708            (Organization (message-make-organization))
5709            (From (message-make-from))
5710            (Path (message-make-path))
5711            (Subject nil)
5712            (Newsgroups nil)
5713            (In-Reply-To (message-make-in-reply-to))
5714            (References (message-make-references))
5715            (To nil)
5716            (Distribution (message-make-distribution))
5717            (Lines (message-make-lines))
5718            (User-Agent (message-make-user-agent))
5719            (Expires (message-make-expires))
5720            (case-fold-search t)
5721            (optionalp nil)
5722            header value elem header-string)
5723       ;; First we remove any old generated headers.
5724       (let ((headers message-deletable-headers))
5725         (unless (buffer-modified-p)
5726           (setq headers (delq 'Message-ID (copy-sequence headers))))
5727         (while headers
5728           (goto-char (point-min))
5729           (and (re-search-forward
5730                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5731                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5732                (message-delete-line))
5733           (pop headers)))
5734       ;; Go through all the required headers and see if they are in the
5735       ;; articles already.  If they are not, or are empty, they are
5736       ;; inserted automatically - except for Subject, Newsgroups and
5737       ;; Distribution.
5738       (while headers
5739         (goto-char (point-min))
5740         (setq elem (pop headers))
5741         (if (consp elem)
5742             (if (eq (car elem) 'optional)
5743                 (setq header (cdr elem)
5744                       optionalp t)
5745               (setq header (car elem)))
5746           (setq header elem))
5747         (setq header-string  (if (stringp header)
5748                                  header
5749                                (symbol-name header)))
5750         (when (or (not (re-search-forward
5751                         (concat "^"
5752                                 (regexp-quote (downcase header-string))
5753                                 ":")
5754                         nil t))
5755                   (progn
5756                     ;; The header was found.  We insert a space after the
5757                     ;; colon, if there is none.
5758                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5759                     ;; Find out whether the header is empty.
5760                     (looking-at "[ \t]*\n[^ \t]")))
5761           ;; So we find out what value we should insert.
5762           (setq value
5763                 (cond
5764                  ((and (consp elem)
5765                        (eq (car elem) 'optional)
5766                        (not (member header-string message-inserted-headers)))
5767                   ;; This is an optional header.  If the cdr of this
5768                   ;; is something that is nil, then we do not insert
5769                   ;; this header.
5770                   (setq header (cdr elem))
5771                   (or (and (functionp (cdr elem))
5772                            (funcall (cdr elem)))
5773                       (and (boundp (cdr elem))
5774                            (symbol-value (cdr elem)))))
5775                  ((consp elem)
5776                   ;; The element is a cons.  Either the cdr is a
5777                   ;; string to be inserted verbatim, or it is a
5778                   ;; function, and we insert the value returned from
5779                   ;; this function.
5780                   (or (and (stringp (cdr elem))
5781                            (cdr elem))
5782                       (and (functionp (cdr elem))
5783                            (funcall (cdr elem)))))
5784                  ((and (boundp header)
5785                        (symbol-value header))
5786                   ;; The element is a symbol.  We insert the value
5787                   ;; of this symbol, if any.
5788                   (symbol-value header))
5789                  ((not (message-check-element
5790                         (intern (downcase (symbol-name header)))))
5791                   ;; We couldn't generate a value for this header,
5792                   ;; so we just ask the user.
5793                   (read-from-minibuffer
5794                    (format "Empty header for %s; enter value: " header)))))
5795           ;; Finally insert the header.
5796           (when (and value
5797                      (not (equal value "")))
5798             (save-excursion
5799               (if (bolp)
5800                   (progn
5801                     ;; This header didn't exist, so we insert it.
5802                     (goto-char (point-max))
5803                     (let ((formatter
5804                            (cdr (assq header message-header-format-alist))))
5805                       (if formatter
5806                           (funcall formatter header value)
5807                         (insert header-string ": " value))
5808                       (goto-char (message-fill-field))
5809                       ;; We check whether the value was ended by a
5810                       ;; newline.  If not, we insert one.
5811                       (unless (bolp)
5812                         (insert "\n"))
5813                       (forward-line -1)))
5814                 ;; The value of this header was empty, so we clear
5815                 ;; totally and insert the new value.
5816                 (delete-region (point) (point-at-eol))
5817                 ;; If the header is optional, and the header was
5818                 ;; empty, we can't insert it anyway.
5819                 (unless optionalp
5820                   (push header-string message-inserted-headers)
5821                   (insert value)
5822                   (message-fill-field)))
5823               ;; Add the deletable property to the headers that require it.
5824               (and (memq header message-deletable-headers)
5825                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5826                    (add-text-properties
5827                     (point) (match-end 0)
5828                     '(message-deletable t face italic) (current-buffer)))))))
5829       ;; Insert new Sender if the From is strange.
5830       (let ((from (message-fetch-field "from"))
5831             (sender (message-fetch-field "sender"))
5832             (secure-sender (message-make-sender)))
5833         (when (and from
5834                    (not (message-check-element 'sender))
5835                    (not (string=
5836                          (downcase
5837                           (cadr (std11-extract-address-components from)))
5838                          (downcase secure-sender)))
5839                    (or (null sender)
5840                        (not
5841                         (string=
5842                          (downcase
5843                           (cadr (std11-extract-address-components sender)))
5844                          (downcase secure-sender)))))
5845           (goto-char (point-min))
5846           ;; Rename any old Sender headers to Original-Sender.
5847           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5848             (beginning-of-line)
5849             (insert "Original-")
5850             (beginning-of-line))
5851           (when (or (message-news-p)
5852                     (string-match "@.+\\.." secure-sender))
5853             (insert "Sender: " secure-sender "\n"))))
5854       ;; Check for IDNA
5855       (message-idna-to-ascii-rhs))))
5856
5857 (defun message-insert-courtesy-copy ()
5858   "Insert a courtesy message in mail copies of combined messages."
5859   (let (newsgroups)
5860     (save-excursion
5861       (save-restriction
5862         (message-narrow-to-headers)
5863         (when (setq newsgroups (message-fetch-field "newsgroups"))
5864           (goto-char (point-max))
5865           (insert "Posted-To: " newsgroups "\n")))
5866       (forward-line 1)
5867       (when message-courtesy-message
5868         (cond
5869          ((string-match "%s" message-courtesy-message)
5870           (insert (format message-courtesy-message newsgroups)))
5871          (t
5872           (insert message-courtesy-message)))))))
5873
5874 ;;;
5875 ;;; Setting up a message buffer
5876 ;;;
5877
5878 (defun message-skip-to-next-address ()
5879   (let ((end (save-excursion
5880                (message-next-header)
5881                (point)))
5882         quoted char)
5883     (when (looking-at ",")
5884       (forward-char 1))
5885     (while (and (not (= (point) end))
5886                 (or (not (eq char ?,))
5887                     quoted))
5888       (skip-chars-forward "^,\"" (point-max))
5889       (when (eq (setq char (following-char)) ?\")
5890         (setq quoted (not quoted)))
5891       (unless (= (point) end)
5892         (forward-char 1)))
5893     (skip-chars-forward " \t\n")))
5894
5895 (defun message-fill-address (header value)
5896   (insert (capitalize (symbol-name header))
5897           ": "
5898           (if (consp value) (car value) value)
5899           "\n")
5900   (message-fill-field-address))
5901
5902 (defun message-fill-references (header value)
5903   (insert (capitalize (symbol-name header))
5904           ": "
5905           (std11-fill-msg-id-list-string
5906            (if (consp value) (car value) value))))
5907
5908 (defun message-split-line ()
5909   "Split current line, moving portion beyond point vertically down.
5910 If the current line has `message-yank-prefix', insert it on the new line."
5911   (interactive "*")
5912   (condition-case nil
5913       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
5914     (error
5915      (split-line))))
5916
5917 (defun message-insert-header (header value)
5918   (insert (capitalize (symbol-name header))
5919           ": "
5920           (if (consp value) (car value) value)))
5921
5922 (defun message-field-name ()
5923   (save-excursion
5924     (goto-char (point-min))
5925     (when (looking-at "\\([^:]+\\):")
5926       (intern (capitalize (match-string 1))))))
5927
5928 (defun message-fill-field ()
5929   (save-excursion
5930     (save-restriction
5931       (message-narrow-to-field)
5932       (let ((field-name (message-field-name)))
5933         (funcall (or (cadr (assq field-name message-field-fillers))
5934                      'message-fill-field-general)))
5935       (point-max))))
5936
5937 (defun message-fill-field-address ()
5938   (while (not (eobp))
5939     (message-skip-to-next-address)
5940     (let (last)
5941       (if (and (> (current-column) 78)
5942                last)
5943           (progn
5944             (save-excursion
5945               (goto-char last)
5946               (insert "\n\t"))
5947             (setq last (1+ (point))))
5948         (setq last (1+ (point)))))))
5949
5950 (defun message-fill-field-general ()
5951   (let ((begin (point))
5952         (fill-column 78)
5953         (fill-prefix " "))
5954     (while (and (search-forward "\n" nil t)
5955                 (not (eobp)))
5956       (replace-match " " t t))
5957     (fill-region-as-paragraph begin (point-max))
5958     ;; Tapdance around looong Message-IDs.
5959     (forward-line -1)
5960     (when (looking-at "[ \t]*$")
5961       (message-delete-line))
5962     (goto-char begin)
5963     (search-forward ":" nil t)
5964     (when (looking-at "\n[ \t]+")
5965       (replace-match " " t t))
5966     (goto-char (point-max))))
5967
5968 (defun message-shorten-1 (list cut surplus)
5969   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5970   (setcdr (nthcdr (- cut 2) list)
5971           (nthcdr (+ (- cut 2) surplus 1) list)))
5972
5973 (defun message-shorten-references (header references)
5974   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5975 When sending via news, also check that the REFERENCES are less
5976 than 988 characters long, and if they are not, trim them until
5977 they are."
5978   (let ((maxcount 21)
5979         (count 0)
5980         (cut 2)
5981         refs)
5982     (with-temp-buffer
5983       (insert references)
5984       (goto-char (point-min))
5985       ;; Cons a list of valid references.
5986       (while (re-search-forward "<[^>]+>" nil t)
5987         (push (match-string 0) refs))
5988       (setq refs (nreverse refs)
5989             count (length refs)))
5990
5991     ;; If the list has more than MAXCOUNT elements, trim it by
5992     ;; removing the CUTth element and the required number of
5993     ;; elements that follow.
5994     (when (> count maxcount)
5995       (let ((surplus (- count maxcount)))
5996         (message-shorten-1 refs cut surplus)
5997         (decf count surplus)))
5998
5999     ;; When sending via news, make sure the total folded length will
6000     ;; be less than 998 characters.  This is to cater to broken INN
6001     ;; 2.3 which counts the total number of characters in a header
6002     ;; rather than the physical line length of each line, as it should.
6003     ;;
6004     ;; This hack should be removed when it's believed than INN 2.3 is
6005     ;; no longer widely used.
6006     ;;
6007     ;; At this point the headers have not been generated, thus we use
6008     ;; message-this-is-news directly.
6009     (when message-this-is-news
6010       (while (< 998
6011                 (with-temp-buffer
6012                   (message-insert-header
6013                    header (mapconcat #'identity refs " "))
6014                   (buffer-size)))
6015         (message-shorten-1 refs cut 1)))
6016     ;; Finally, collect the references back into a string and insert
6017     ;; it into the buffer.
6018     (message-insert-header header (mapconcat #'identity refs " "))))
6019
6020 (defun message-position-point ()
6021   "Move point to where the user probably wants to find it."
6022   (message-narrow-to-headers)
6023   (cond
6024    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
6025     (search-backward ":" )
6026     (widen)
6027     (forward-char 1)
6028     (if (eq (char-after) ? )
6029         (forward-char 1)
6030       (insert " ")))
6031    (t
6032     (goto-char (point-max))
6033     (widen)
6034     (forward-line 1)
6035     (unless (looking-at "$")
6036       (forward-line 2)))
6037    (sit-for 0)))
6038
6039 (defcustom message-beginning-of-line t
6040   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
6041  goes to beginning of header values."
6042   :version "22.1"
6043   :group 'message-buffers
6044   :link '(custom-manual "(message)Movement")
6045   :type 'boolean)
6046
6047 (defun message-beginning-of-line (&optional n)
6048   "Move point to beginning of header value or to beginning of line.
6049 The prefix argument N is passed directly to `beginning-of-line'.
6050
6051 This command is identical to `beginning-of-line' if point is
6052 outside the message header or if the option `message-beginning-of-line'
6053 is nil.
6054
6055 If point is in the message header and on a (non-continued) header
6056 line, move point to the beginning of the header value or the beginning of line,
6057 whichever is closer.  If point is already at beginning of line, move point to
6058 beginning of header value.  Therefore, repeated calls will toggle point
6059 between beginning of field and beginning of line."
6060   (interactive "p")
6061   (let ((zrs 'zmacs-region-stays))
6062     (when (and (interactive-p) (boundp zrs))
6063       (set zrs t)))
6064   (if (and message-beginning-of-line
6065            (message-point-in-header-p))
6066       (let* ((here (point))
6067              (bol (progn (beginning-of-line n) (point)))
6068              (eol (point-at-eol))
6069              (eoh (re-search-forward ": *" eol t)))
6070         (goto-char
6071          (if (and eoh (or (< eoh here) (= bol here)))
6072              eoh bol)))
6073     (beginning-of-line n)))
6074
6075 (defun message-buffer-name (type &optional to group)
6076   "Return a new (unique) buffer name based on TYPE and TO."
6077   (cond
6078    ;; Generate a new buffer name The Message Way.
6079    ((eq message-generate-new-buffers 'unique)
6080     (generate-new-buffer-name
6081      (concat "*" type
6082              (if to
6083                  (concat " to "
6084                          (or (car (std11-extract-address-components to))
6085                              to) "")
6086                "")
6087              (if (and group (not (string= group ""))) (concat " on " group) "")
6088              "*")))
6089    ;; Check whether `message-generate-new-buffers' is a function,
6090    ;; and if so, call it.
6091    ((functionp message-generate-new-buffers)
6092     (funcall message-generate-new-buffers type to group))
6093    ((eq message-generate-new-buffers 'unsent)
6094     (generate-new-buffer-name
6095      (concat "*unsent " type
6096              (if to
6097                  (concat " to "
6098                          (or (car (std11-extract-address-components to))
6099                              to) "")
6100                "")
6101              (if (and group (not (string= group ""))) (concat " on " group) "")
6102              "*")))
6103    ;; Use standard name.
6104    (t
6105     (format "*%s message*" type))))
6106
6107 (defmacro message-pop-to-buffer-1 (buffer)
6108   `(if pop-up-frames
6109        (let (special-display-buffer-names
6110              special-display-regexps
6111              same-window-buffer-names
6112              same-window-regexps)
6113          (pop-to-buffer ,buffer))
6114      (pop-to-buffer ,buffer)))
6115
6116 (defun message-pop-to-buffer (name)
6117   "Pop to buffer NAME, and warn if it already exists and is modified."
6118   (let ((buffer (get-buffer name))
6119         (pop-up-frames (and (static-if (featurep 'xemacs)
6120                                 (device-on-window-system-p)
6121                               window-system)
6122                             message-use-multi-frames)))
6123     (if (and buffer
6124              (buffer-name buffer))
6125         (progn
6126           (message-pop-to-buffer-1 buffer)
6127           (when (and (buffer-modified-p)
6128                      (not (y-or-n-p
6129                            "Message already being composed; erase? ")))
6130             (error "Message being composed")))
6131       (message-pop-to-buffer-1 name))
6132     (erase-buffer)
6133     (message-mode)
6134     (when pop-up-frames
6135       (set (make-local-variable 'message-original-frame) (selected-frame)))))
6136
6137 (defun message-do-send-housekeeping ()
6138   "Kill old message buffers."
6139   ;; We might have sent this buffer already.  Delete it from the
6140   ;; list of buffers.
6141   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6142   (while (and message-max-buffers
6143               message-buffer-list
6144               (>= (length message-buffer-list) message-max-buffers))
6145     ;; Kill the oldest buffer -- unless it has been changed.
6146     (let ((buffer (pop message-buffer-list)))
6147       (when (and (buffer-name buffer)
6148                  (not (buffer-modified-p buffer)))
6149         (kill-buffer buffer))))
6150   ;; Rename the buffer.
6151   (if message-send-rename-function
6152       (funcall message-send-rename-function)
6153     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6154     (when (string-match
6155            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6156            (buffer-name))
6157       (let ((name (match-string 2 (buffer-name)))
6158             to group)
6159         (if (not (or (null name)
6160                      (string-equal name "mail")
6161                      (string-equal name "posting")))
6162             (setq name (concat "*sent " name "*"))
6163           (message-narrow-to-headers)
6164           (setq to (message-fetch-field "to"))
6165           (setq group (message-fetch-field "newsgroups"))
6166           (widen)
6167           (setq name
6168                 (cond
6169                  (to (concat "*sent mail to "
6170                              (or (car (std11-extract-address-components to))
6171                                  to) "*"))
6172                  ((and group (not (string= group "")))
6173                   (concat "*sent posting on " group "*"))
6174                  (t "*sent mail*"))))
6175         (unless (string-equal name (buffer-name))
6176           (rename-buffer name t)))))
6177   ;; Push the current buffer onto the list.
6178   (when message-max-buffers
6179     (setq message-buffer-list
6180           (nconc message-buffer-list (list (current-buffer))))))
6181
6182 (defun message-mail-user-agent ()
6183   (let ((mua (cond
6184               ((not message-mail-user-agent) nil)
6185               ((eq message-mail-user-agent t) mail-user-agent)
6186               (t message-mail-user-agent))))
6187     (if (memq mua '(message-user-agent gnus-user-agent))
6188         nil
6189       mua)))
6190
6191 (defun message-setup (headers &optional replybuffer actions switch-function)
6192   (let ((mua (message-mail-user-agent))
6193         subject to field yank-action)
6194     (if (not (and message-this-is-mail mua))
6195         (message-setup-1 headers replybuffer actions)
6196       (if replybuffer
6197           (setq yank-action (list 'insert-buffer replybuffer)))
6198       (setq headers (copy-sequence headers))
6199       (setq field (assq 'Subject headers))
6200       (when field
6201         (setq subject (cdr field))
6202         (setq headers (delq field headers)))
6203       (setq field (assq 'To headers))
6204       (when field
6205         (setq to (cdr field))
6206         (setq headers (delq field headers)))
6207       (let ((mail-user-agent mua))
6208         (compose-mail to subject
6209                       (mapcar (lambda (item)
6210                                 (cons
6211                                  (format "%s" (car item))
6212                                  (cdr item)))
6213                               headers)
6214                       nil switch-function yank-action actions)))))
6215
6216 (defun message-headers-to-generate (headers included-headers excluded-headers)
6217   "Return a list that includes all headers from HEADERS.
6218 If INCLUDED-HEADERS is a list, just include those headers.  If if is
6219 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6220 are not included."
6221   (let ((result nil)
6222         header-name)
6223     (dolist (header headers)
6224       (setq header-name (cond
6225                          ((and (consp header)
6226                                (eq (car header) 'optional))
6227                           ;; On the form (optional . Header)
6228                           (cdr header))
6229                          ((consp header)
6230                           ;; On the form (Header . function)
6231                           (car header))
6232                          (t
6233                           ;; Just a Header.
6234                           header)))
6235       (when (and (not (memq header-name excluded-headers))
6236                  (or (eq included-headers t)
6237                      (memq header-name included-headers)))
6238         (push header result)))
6239     (nreverse result)))
6240
6241 (defun message-setup-1 (headers &optional replybuffer actions)
6242   (dolist (action actions)
6243     (condition-case nil
6244         (add-to-list 'message-send-actions
6245                      `(apply ',(car action) ',(cdr action)))))
6246   (setq message-reply-buffer
6247         (or (message-get-parameter 'reply-buffer)
6248             replybuffer))
6249   (goto-char (point-min))
6250   ;; Insert all the headers.
6251   (mail-header-format
6252    (let ((h headers)
6253          (alist message-header-format-alist))
6254      (while h
6255        (unless (assq (caar h) message-header-format-alist)
6256          (push (list (caar h)) alist))
6257        (pop h))
6258      alist)
6259    headers)
6260   (delete-region (point) (progn (forward-line -1) (point)))
6261   (when message-default-headers
6262     (insert message-default-headers)
6263     (or (bolp) (insert ?\n)))
6264   (insert mail-header-separator "\n")
6265   (forward-line -1)
6266   (when (message-news-p)
6267     (when message-default-news-headers
6268       (insert message-default-news-headers)
6269       (or (bolp) (insert ?\n)))
6270     (when message-generate-headers-first
6271       (message-generate-headers
6272        (message-headers-to-generate
6273         (append message-required-news-headers
6274                 message-required-headers)
6275         message-generate-headers-first
6276         '(Lines Subject)))))
6277   (when (message-mail-p)
6278     (when message-default-mail-headers
6279       (insert message-default-mail-headers)
6280       (or (bolp) (insert ?\n)))
6281     (when message-generate-headers-first
6282       (message-generate-headers
6283        (message-headers-to-generate
6284         (append message-required-mail-headers
6285                 message-required-headers)
6286         message-generate-headers-first
6287         '(Lines Subject)))))
6288   (run-hooks 'message-signature-setup-hook)
6289   (message-insert-signature)
6290   (save-restriction
6291     (message-narrow-to-headers)
6292     (run-hooks 'message-header-setup-hook))
6293   (set-buffer-modified-p nil)
6294   (setq buffer-undo-list nil)
6295   (when message-generate-hashcash
6296     ;; Generate hashcash headers for recipients already known
6297     (mail-add-payment-async))
6298   (run-hooks 'message-setup-hook)
6299   ;; Do this last to give it precedence over posting styles, etc.
6300   (when (message-mail-p)
6301     (save-restriction
6302       (message-narrow-to-headers)
6303       (if message-alternative-emails
6304           (message-use-alternative-email-as-from))))
6305   (message-position-point)
6306   (undo-boundary))
6307
6308 (defun message-set-auto-save-file-name ()
6309   "Associate the message buffer with a file in the drafts directory."
6310   (when message-auto-save-directory
6311     (unless (file-directory-p
6312              (directory-file-name message-auto-save-directory))
6313       (make-directory message-auto-save-directory t))
6314     (if (gnus-alive-p)
6315         (setq message-draft-article
6316               (nndraft-request-associate-buffer "drafts"))
6317       (setq buffer-file-name (expand-file-name
6318                               (if (memq system-type
6319                                         '(ms-dos ms-windows windows-nt
6320                                                  cygwin cygwin32 win32 w32
6321                                                  mswindows))
6322                                   "message"
6323                                 "*message*")
6324                               message-auto-save-directory))
6325       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6326     (clear-visited-file-modtime)
6327     (setq buffer-file-coding-system message-draft-coding-system)))
6328
6329 (defun message-disassociate-draft ()
6330   "Disassociate the message buffer from the drafts directory."
6331   (when message-draft-article
6332     (nndraft-request-expire-articles
6333      (list message-draft-article) "drafts" nil t)))
6334
6335 (defun message-insert-headers ()
6336   "Generate the headers for the article."
6337   (interactive)
6338   (save-excursion
6339     (save-restriction
6340       (message-narrow-to-headers)
6341       (when (message-news-p)
6342         (message-generate-headers
6343          (delq 'Lines
6344                (delq 'Subject
6345                      (copy-sequence message-required-news-headers)))))
6346       (when (message-mail-p)
6347         (message-generate-headers
6348          (delq 'Lines
6349                (delq 'Subject
6350                      (copy-sequence message-required-mail-headers))))))))
6351
6352 \f
6353
6354 ;;;
6355 ;;; Commands for interfacing with message
6356 ;;;
6357
6358 ;;;###autoload
6359 (defun message-mail (&optional to subject
6360                                other-headers continue switch-function
6361                                yank-action send-actions)
6362   "Start editing a mail message to be sent.
6363 OTHER-HEADERS is an alist of header/value pairs."
6364   (interactive)
6365   (let ((message-this-is-mail t) replybuffer)
6366     (unless (message-mail-user-agent)
6367       (message-pop-to-buffer (message-buffer-name "mail" to)))
6368     ;; FIXME: message-mail should do something if YANK-ACTION is not
6369     ;; insert-buffer.
6370     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6371          (setq replybuffer (nth 1 yank-action)))
6372     (message-setup
6373      (nconc
6374       `((To . ,(or to "")) (Subject . ,(or subject "")))
6375       (when other-headers other-headers))
6376      replybuffer send-actions)
6377     ;; FIXME: Should return nil if failure.
6378     t))
6379
6380 ;;;###autoload
6381 (defun message-news (&optional newsgroups subject)
6382   "Start editing a news article to be sent."
6383   (interactive)
6384   (let ((message-this-is-news t))
6385     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6386     (message-setup `((Newsgroups . ,(or newsgroups ""))
6387                      (Subject . ,(or subject ""))))))
6388
6389 (defun message-get-reply-headers (wide &optional to-address address-headers)
6390   (let (follow-to mct never-mct to cc author mft recipients extra)
6391     ;; Find all relevant headers we need.
6392     (save-restriction
6393       (message-narrow-to-headers-or-head)
6394       (let ((mrt (when message-use-mail-reply-to
6395                    (message-fetch-field "mail-reply-to")))
6396             (reply-to (message-fetch-field "reply-to")))
6397         ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6398         ;; message-header-synonyms.
6399         (setq to (or (message-fetch-field "to")
6400                      (and (loop for synonym in message-header-synonyms
6401                                 when (memq 'Original-To synonym)
6402                                 return t)
6403                           (message-fetch-field "original-to")))
6404               cc (message-fetch-field "cc")
6405               extra (when message-extra-wide-headers
6406                       (mapconcat 'identity
6407                                  (mapcar 'message-fetch-field
6408                                          message-extra-wide-headers)
6409                                  ", "))
6410               mct (when message-use-mail-copies-to
6411                     (message-fetch-field "mail-copies-to"))
6412               author (or mrt
6413                          reply-to
6414                          (message-fetch-field "from")
6415                          "")
6416               mft (when (and (not (or to-address mrt reply-to))
6417                              message-use-mail-followup-to)
6418                     (message-fetch-field "mail-followup-to")))))
6419
6420     (save-match-data
6421       ;; Handle special values of Mail-Copies-To.
6422       (when mct
6423         (cond ((or (equal (downcase mct) "never")
6424                    (equal (downcase mct) "nobody"))
6425                (when (or (not (eq message-use-mail-copies-to 'ask))
6426                          (message-y-or-n-p
6427                           (concat "Obey Mail-Copies-To: never? ") t "\
6428 You should normally obey the Mail-Copies-To: header.
6429
6430         `Mail-Copies-To: " mct "'
6431 directs you not to send your response to the author."))
6432                  (setq never-mct t))
6433                (setq mct nil))
6434               ((or (equal (downcase mct) "always")
6435                    (equal (downcase mct) "poster"))
6436                (if (or (not (eq message-use-mail-copies-to 'ask))
6437                        (message-y-or-n-p
6438                         (concat "Obey Mail-Copies-To: always? ") t "\
6439 You should normally obey the Mail-Copies-To: header.
6440
6441         `Mail-Copies-To: " mct "'
6442 sends a copy of your response to the author."))
6443                    (setq mct author)
6444                  (setq mct nil)))
6445               ((and (eq message-use-mail-copies-to 'ask)
6446                     (not (message-y-or-n-p
6447                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6448 You should normally obey the Mail-Copies-To: header.
6449
6450         `Mail-Copies-To: " mct "'
6451 sends a copy of your response to " (if (string-match "," mct)
6452                                        "the specified addresses"
6453                                      "that address") ".")))
6454                (setq mct nil))))
6455
6456       ;; Build (textual) list of new recipient addresses.
6457       (cond
6458        ((not wide)
6459         (setq recipients (concat ", " author)))
6460        (address-headers
6461         (dolist (header address-headers)
6462           (let ((value (message-fetch-field header)))
6463             (when value
6464               (setq recipients (concat recipients ", " value))))))
6465        ((and mft
6466              (string-match "[^ \t,]" mft)
6467              (or (not (eq message-use-mail-followup-to 'ask))
6468                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6469 You should normally obey the Mail-Followup-To: header.  In this
6470 article, it has the value of
6471
6472 " mft "
6473
6474 which directs your response to " (if (string-match "," mft)
6475                                      "the specified addresses"
6476                                    "that address only") ".
6477
6478 Most commonly, Mail-Followup-To is used by a mailing list poster to
6479 express that responses should be sent to just the list, and not the
6480 poster as well.
6481
6482 If a message is posted to several mailing lists, Mail-Followup-To may
6483 also be used to direct the following discussion to one list only,
6484 because discussions that are spread over several lists tend to be
6485 fragmented and very difficult to follow.
6486
6487 Also, some source/announcement lists are not intended for discussion;
6488 responses here are directed to other addresses.
6489
6490 You may customize the variable `message-use-mail-followup-to', if you
6491 want to get rid of this query permanently.")))
6492         (setq recipients (concat ", " mft)))
6493        (to-address
6494         (setq recipients (concat ", " to-address))
6495         ;; If the author explicitly asked for a copy, we don't deny it to them.
6496         (if mct (setq recipients (concat recipients ", " mct))))
6497        (t
6498         (setq recipients (if never-mct "" (concat ", " author)))
6499         (if to (setq recipients (concat recipients ", " to)))
6500         (if cc (setq recipients (concat recipients ", " cc)))
6501         (if extra (setq recipients (concat recipients ", " extra)))
6502         (if mct (setq recipients (concat recipients ", " mct)))))
6503       (if (>= (length recipients) 2)
6504           ;; Strip the leading ", ".
6505           (setq recipients (substring recipients 2)))
6506       ;; Squeeze whitespace.
6507       (while (string-match "[ \t][ \t]+" recipients)
6508         (setq recipients (replace-match " " t t recipients)))
6509       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6510       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6511         (setq recipients (rmail-dont-reply-to recipients)))
6512       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6513       (if (string-equal recipients "")
6514           (setq recipients author))
6515       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6516       (setq recipients
6517             (mapcar
6518              (lambda (addr)
6519                (cons (downcase (mail-strip-quoted-names addr)) addr))
6520              (message-tokenize-header recipients)))
6521       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6522       (let ((s recipients))
6523         (while s
6524           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6525
6526       ;; Remove hierarchical lists that are contained within each other,
6527       ;; if message-hierarchical-addresses is defined.
6528       (when message-hierarchical-addresses
6529         (let ((plain-addrs (mapcar 'car recipients))
6530               subaddrs recip)
6531           (while plain-addrs
6532             (setq subaddrs (assoc (car plain-addrs)
6533                                   message-hierarchical-addresses)
6534                   plain-addrs (cdr plain-addrs))
6535             (when subaddrs
6536               (setq subaddrs (cdr subaddrs))
6537               (while subaddrs
6538                 (setq recip (assoc (car subaddrs) recipients)
6539                       subaddrs (cdr subaddrs))
6540                 (if recip
6541                     (setq recipients (delq recip recipients))))))))
6542
6543       ;; Build the header alist.  Allow the user to be asked whether
6544       ;; or not to reply to all recipients in a wide reply.
6545       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6546       (when (and recipients
6547                  (or (not message-wide-reply-confirm-recipients)
6548                      (y-or-n-p "Reply to all recipients? ")))
6549         (setq recipients (mapconcat
6550                           (lambda (addr) (cdr addr)) recipients ", "))
6551         (if (string-match "^ +" recipients)
6552             (setq recipients (substring recipients (match-end 0))))
6553         (push (cons 'Cc recipients) follow-to)))
6554     follow-to))
6555
6556 ;;;###autoload
6557 (defun message-reply (&optional to-address wide)
6558   "Start editing a reply to the article in the current buffer."
6559   (interactive)
6560   (require 'gnus-sum)                   ; for gnus-list-identifiers
6561   (let ((cur (current-buffer))
6562         from subject date
6563         references message-id follow-to
6564         (inhibit-point-motion-hooks t)
6565         (message-this-is-mail t)
6566         gnus-warning in-reply-to)
6567     (save-restriction
6568       (message-narrow-to-head-1)
6569       ;; Allow customizations to have their say.
6570       (if (not wide)
6571           ;; This is a regular reply.
6572           (when (functionp message-reply-to-function)
6573             (save-excursion
6574               (setq follow-to (funcall message-reply-to-function))))
6575         ;; This is a followup.
6576         (when (functionp message-wide-reply-to-function)
6577           (save-excursion
6578             (setq follow-to
6579                   (funcall message-wide-reply-to-function)))))
6580       (setq message-id (message-fetch-field "message-id" t)
6581             references (message-fetch-field "references")
6582             date (message-fetch-field "date")
6583             from (message-fetch-field "from")
6584             subject (or (message-fetch-field "subject") "none"))
6585       (when gnus-list-identifiers
6586         (setq subject (message-strip-list-identifiers subject)))
6587       (setq subject (message-make-followup-subject subject))
6588       (when message-subject-trailing-was-query
6589         (setq subject (message-strip-subject-trailing-was subject)))
6590
6591       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6592                  (string-match "<[^>]+>" gnus-warning))
6593         (setq message-id (match-string 0 gnus-warning)))
6594
6595       (unless follow-to
6596         (setq follow-to (message-get-reply-headers wide to-address)))
6597
6598       ;; Get the references from "In-Reply-To" field if there were
6599       ;; no references and "In-Reply-To" field looks promising.
6600       (unless references
6601         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6602                    (string-match "<[^>]+>" in-reply-to))
6603           (setq references (match-string 0 in-reply-to)))))
6604
6605     (unless (message-mail-user-agent)
6606       (message-pop-to-buffer
6607        (message-buffer-name
6608         (if wide "wide reply" "reply") from
6609         (if wide to-address nil))))
6610
6611     (setq message-reply-headers
6612           (make-full-mail-header-from-decoded-header
6613            0 subject from date message-id references 0 0 ""))
6614
6615     (message-setup
6616      `((Subject . ,subject)
6617        ,@follow-to)
6618      cur)))
6619
6620 ;;;###autoload
6621 (defun message-wide-reply (&optional to-address)
6622   "Make a \"wide\" reply to the message in the current buffer."
6623   (interactive)
6624   (message-reply to-address t))
6625
6626 ;;;###autoload
6627 (defun message-followup (&optional to-newsgroups)
6628   "Follow up to the message in the current buffer.
6629 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6630   (interactive)
6631   (require 'gnus-sum)                   ; for gnus-list-identifiers
6632   (let ((cur (current-buffer))
6633         from subject date reply-to mrt mct mft
6634         references message-id follow-to
6635         (inhibit-point-motion-hooks t)
6636         (message-this-is-news t)
6637         followup-to distribution newsgroups gnus-warning posted-to)
6638     (save-restriction
6639       (message-narrow-to-head)
6640       (when (functionp message-followup-to-function)
6641         (setq follow-to
6642               (funcall message-followup-to-function)))
6643       (setq from (message-fetch-field "from")
6644             date (message-fetch-field "date")
6645             subject (or (message-fetch-field "subject") "none")
6646             references (message-fetch-field "references")
6647             message-id (message-fetch-field "message-id" t)
6648             followup-to (message-fetch-field "followup-to")
6649             newsgroups (message-fetch-field "newsgroups")
6650             posted-to (message-fetch-field "posted-to")
6651             reply-to (message-fetch-field "reply-to")
6652             mrt (when message-use-mail-reply-to
6653                   (message-fetch-field "mail-reply-to"))
6654             distribution (message-fetch-field "distribution")
6655             mct (when message-use-mail-copies-to
6656                   (message-fetch-field "mail-copies-to"))
6657             mft (when message-use-mail-followup-to
6658                   (message-fetch-field "mail-followup-to")))
6659       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6660                  (string-match "<[^>]+>" gnus-warning))
6661         (setq message-id (match-string 0 gnus-warning)))
6662       ;; Remove bogus distribution.
6663       (when (and (stringp distribution)
6664                  (let ((case-fold-search t))
6665                    (string-match "world" distribution)))
6666         (setq distribution nil))
6667       (if gnus-list-identifiers
6668           (setq subject (message-strip-list-identifiers subject)))
6669       (setq subject (message-make-followup-subject subject))
6670       (when message-subject-trailing-was-query
6671         (setq subject (message-strip-subject-trailing-was subject)))
6672       (widen))
6673
6674     ;; Handle special values of Mail-Copies-To.
6675     (when mct
6676       (cond
6677        ((and (or (equal (downcase mct) "never")
6678                  (equal (downcase mct) "nobody")))
6679         (setq mct nil))
6680        ((and (or (equal (downcase mct) "always")
6681                  (equal (downcase mct) "poster")))
6682         (if (or (not (eq message-use-mail-copies-to 'ask))
6683                 (message-y-or-n-p
6684                  (concat "Obey Mail-Copies-To: always? ") t "\
6685 You should normally obey the Mail-Copies-To: header.
6686
6687         `Mail-Copies-To: " mct "'
6688 sends a copy of your response to the author."))
6689             (setq mct (or mrt reply-to from))
6690           (setq mct nil)))
6691        ((and (eq message-use-mail-copies-to 'ask)
6692              (not
6693               (message-y-or-n-p
6694                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6695 You should normally obey the Mail-Copies-To: header.
6696
6697         `Mail-Copies-To: " mct "'
6698 sends a copy of your response to " (if (string-match "," mct)
6699                                        "the specified addresses"
6700                                      "that address") ".")))
6701         (setq mct nil))))
6702
6703     (unless follow-to
6704       (cond
6705        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6706        ;; Handle Followup-To.
6707        (followup-to
6708         (cond
6709          ((equal (downcase followup-to) "poster")
6710           (if (or (and followup-to (eq message-use-followup-to 'use))
6711                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6712 You should normally obey the Followup-To: header.
6713
6714         `Followup-To: poster'
6715 sends your response via e-mail instead of news.
6716
6717 A typical situation where `Followup-To: poster' is used is when the poster
6718 does not read the newsgroup, so he wouldn't see any replies sent to it.
6719
6720 You may customize the variable `message-use-followup-to', if you
6721 want to get rid of this query permanently."))
6722               (setq message-this-is-news nil
6723                     distribution nil
6724                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6725             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6726          (t
6727           (if (or (equal followup-to newsgroups)
6728                   (not (and followup-to (eq message-use-followup-to 'ask)))
6729                   (message-y-or-n-p
6730                    (concat "Obey Followup-To: " followup-to "? ") t "\
6731 You should normally obey the Followup-To: header.
6732
6733         `Followup-To: " followup-to "'
6734 directs your response to " (if (string-match "," followup-to)
6735                                "the specified newsgroups"
6736                              "that newsgroup only") ".
6737
6738 If a message is posted to several newsgroups, Followup-To is often
6739 used to direct the following discussion to one newsgroup only,
6740 because discussions that are spread over several newsgroup tend to
6741 be fragmented and very difficult to follow.
6742
6743 Also, some source/announcement newsgroups are not intended for discussion;
6744 responses here are directed to other newsgroups.
6745
6746 You may customize the variable `message-use-followup-to', if you
6747 want to get rid of this query permanently."))
6748               (setq follow-to (list (cons 'Newsgroups followup-to)))
6749             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6750        ;; Handle Mail-Followup-To, followup via e-mail.
6751        ((and mft
6752              (or (not (eq message-use-mail-followup-to 'ask))
6753                  (message-y-or-n-p
6754                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6755 You should normally obey the Mail-Followup-To: header.
6756
6757         `Mail-Followup-To: " mft "'
6758 directs your response to " (if (string-match "," mft)
6759                                "the specified addresses"
6760                              "that address only") " instead of news.
6761
6762 A typical situation where Mail-Followup-To is used is when the author thinks
6763 that further discussion should take place only in "
6764                              (if (string-match "," mft)
6765                                  "the specified mailing lists"
6766                                "that mailing list") ".")))
6767         (setq message-this-is-news nil
6768               distribution nil
6769               follow-to (list (cons 'To mft))))
6770        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6771        (t
6772         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6773
6774     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6775
6776     (setq message-reply-headers
6777           (make-full-mail-header-from-decoded-header
6778            0 subject from date message-id references 0 0 ""))
6779
6780     (message-setup
6781      `((Subject . ,subject)
6782        ,@follow-to
6783        ,@(and mct (list (cons 'Cc mct)))
6784        ,@(and distribution (list (cons 'Distribution distribution))))
6785      cur)))
6786
6787 (defun message-is-yours-p ()
6788   "Non-nil means current article is yours.
6789 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6790 are yours except those that have Cancel-Lock header not belonging to you.
6791 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6792 regexp to match all of yours addresses."
6793   ;; Canlock-logic as suggested by Per Abrahamsen
6794   ;; <abraham@dina.kvl.dk>
6795   ;;
6796   ;; IF article has cancel-lock THEN
6797   ;;   IF we can verify it THEN
6798   ;;     issue cancel
6799   ;;   ELSE
6800   ;;     error: cancellock: article is not yours
6801   ;; ELSE
6802   ;;   Use old rules, comparing sender...
6803   (save-excursion
6804     (save-restriction
6805       (message-narrow-to-head-1)
6806       (if (message-fetch-field "Cancel-Lock")
6807           (if (null (canlock-verify))
6808               t
6809             (error "Failed to verify Cancel-lock: This article is not yours"))
6810         (let (sender from)
6811           (or
6812            (message-gnksa-enable-p 'cancel-messages)
6813            (and (setq sender (message-fetch-field "sender"))
6814                 (string-equal (downcase sender)
6815                               (downcase (message-make-sender))))
6816            ;; Email address in From field equals to our address
6817            (and (setq from (message-fetch-field "from"))
6818                 (string-equal
6819                  (downcase (cadr (std11-extract-address-components from)))
6820                  (downcase (cadr (std11-extract-address-components
6821                                   (message-make-from))))))
6822            ;; Email address in From field matches
6823            ;; 'message-alternative-emails' regexp
6824            (and from
6825                 message-alternative-emails
6826                 (string-match
6827                  message-alternative-emails
6828                  (cadr (std11-extract-address-components from))))))))))
6829
6830 ;;;###autoload
6831 (defun message-cancel-news (&optional arg)
6832   "Cancel an article you posted.
6833 If ARG, allow editing of the cancellation message."
6834   (interactive "P")
6835   (unless (message-news-p)
6836     (error "This is not a news article; canceling is impossible"))
6837   (let (from newsgroups message-id distribution buf)
6838     (save-excursion
6839       ;; Get header info from original article.
6840       (save-restriction
6841         (message-narrow-to-head-1)
6842         (setq from (message-fetch-field "from")
6843               newsgroups (message-fetch-field "newsgroups")
6844               message-id (message-fetch-field "message-id" t)
6845               distribution (message-fetch-field "distribution")))
6846       ;; Make sure that this article was written by the user.
6847       (unless (message-is-yours-p)
6848         (error "This article is not yours"))
6849       (when (yes-or-no-p "Do you really want to cancel this article? ")
6850         ;; Make control message.
6851         (if arg
6852             (message-news)
6853           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6854         (erase-buffer)
6855         (insert "Newsgroups: " newsgroups "\n"
6856                 "From: " from "\n"
6857                 "Subject: cmsg cancel " message-id "\n"
6858                 "Control: cancel " message-id "\n"
6859                 (if distribution
6860                     (concat "Distribution: " distribution "\n")
6861                   "")
6862                 mail-header-separator "\n"
6863                 message-cancel-message)
6864         (run-hooks 'message-cancel-hook)
6865         (unless arg
6866           (message "Canceling your article...")
6867           (if (let ((message-syntax-checks
6868                      'dont-check-for-anything-just-trust-me)
6869                     (message-encoding-buffer (current-buffer))
6870                     (message-edit-buffer (current-buffer)))
6871                 (message-send-news))
6872               (message "Canceling your article...done"))
6873           (kill-buffer buf))))))
6874
6875 (defun message-supersede-setup-for-mime-edit ()
6876   (set (make-local-variable 'message-setup-hook) nil)
6877   (mime-edit-again))
6878
6879 ;;;###autoload
6880 (defun message-supersede ()
6881   "Start composing a message to supersede the current message.
6882 This is done simply by taking the old article and adding a Supersedes
6883 header line with the old Message-ID."
6884   (interactive)
6885   (let ((cur (current-buffer)))
6886     ;; Check whether the user owns the article that is to be superseded.
6887     (unless (message-is-yours-p)
6888       (error "This article is not yours"))
6889     ;; Get a normal message buffer.
6890     (message-pop-to-buffer (message-buffer-name "supersede"))
6891     (insert-buffer-substring cur)
6892     (message-narrow-to-head-1)
6893     ;; Remove unwanted headers.
6894     (when message-ignored-supersedes-headers
6895       (message-remove-header message-ignored-supersedes-headers t))
6896     (goto-char (point-min))
6897     (if (not (re-search-forward "^Message-ID: " nil t))
6898         (error "No Message-ID in this article")
6899       (replace-match "Supersedes: " t t))
6900     (goto-char (point-max))
6901     (insert mail-header-separator)
6902     (widen)
6903     (when message-supersede-setup-function
6904       (funcall message-supersede-setup-function))
6905     (run-hooks 'message-supersede-setup-hook)
6906     (goto-char (point-min))
6907     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6908
6909 ;;;###autoload
6910 (defun message-recover ()
6911   "Reread contents of current buffer from its last auto-save file."
6912   (interactive)
6913   (let ((file-name (make-auto-save-file-name)))
6914     (cond ((save-window-excursion
6915              (if (not (eq system-type 'vax-vms))
6916                  (with-output-to-temp-buffer "*Directory*"
6917                    (with-current-buffer standard-output
6918                      (fundamental-mode)) ; for Emacs 20.4+
6919                    (buffer-disable-undo standard-output)
6920                    (let ((default-directory "/"))
6921                      (call-process
6922                       "ls" nil standard-output nil "-l" file-name))))
6923              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6924            (let ((buffer-read-only nil))
6925              (erase-buffer)
6926              (insert-file-contents file-name nil)))
6927           (t (error "message-recover cancelled")))))
6928
6929 ;;; Washing Subject:
6930
6931 (defun message-wash-subject (subject)
6932   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6933 Previous forwarders, replyers, etc. may add it."
6934   (with-temp-buffer
6935     (insert subject)
6936     (goto-char (point-min))
6937     ;; strip Re/Fwd stuff off the beginning
6938     (while (re-search-forward
6939             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6940       (replace-match ""))
6941
6942     ;; and gnus-style forwards [foo@bar.com] subject
6943     (goto-char (point-min))
6944     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6945       (replace-match ""))
6946
6947     ;; and off the end
6948     (goto-char (point-max))
6949     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6950       (replace-match ""))
6951
6952     ;; and finally, any whitespace that was left-over
6953     (goto-char (point-min))
6954     (while (re-search-forward "^[ \t]+" nil t)
6955       (replace-match ""))
6956     (goto-char (point-max))
6957     (while (re-search-backward "[ \t]+$" nil t)
6958       (replace-match ""))
6959
6960     (buffer-string)))
6961
6962 ;;; Forwarding messages.
6963
6964 (defvar message-forward-decoded-p nil
6965   "Non-nil means the original message is decoded.")
6966
6967 (defun message-forward-subject-name-subject (subject)
6968   "Generate a SUBJECT for a forwarded message.
6969 The form is: [Source] Subject, where if the original message was mail,
6970 Source is the name of the sender, and if the original message was
6971 news, Source is the list of newsgroups is was posted to."
6972   (concat "["
6973           (let ((group (message-fetch-field "newsgroups"))
6974                 from)
6975             (if group
6976                 (gnus-group-decoded-name group)
6977               (or (and (setq from (message-fetch-field "from"))
6978                        (car (std11-extract-address-components
6979                              (nnheader-decode-from from)))
6980                        (cadr (std11-extract-address-components
6981                               (nnheader-decode-from from))))
6982                   "(nowhere)")))
6983           "] " subject))
6984
6985 (defun message-forward-subject-author-subject (subject)
6986   "Generate a SUBJECT for a forwarded message.
6987 The form is: [Source] Subject, where if the original message was mail,
6988 Source is the sender, and if the original message was news, Source is
6989 the list of newsgroups is was posted to."
6990   (concat "["
6991           (let ((group (message-fetch-field "newsgroups"))
6992                 from)
6993             (if group
6994                 (gnus-group-decoded-name group)
6995               (if (setq from (message-fetch-field "from"))
6996                   (nnheader-decode-from from)
6997                 "(nowhere)")))
6998           "] " subject))
6999
7000 (defun message-forward-subject-fwd (subject)
7001   "Generate a SUBJECT for a forwarded message.
7002 The form is: Fwd: Subject, where Subject is the original subject of
7003 the message."
7004   (if (string-match "^Fwd: " subject)
7005       subject
7006     (concat "Fwd: " subject)))
7007
7008 (defun message-make-forward-subject ()
7009   "Return a Subject header suitable for the message in the current buffer."
7010   (save-excursion
7011     (save-restriction
7012       (message-narrow-to-head-1)
7013       (let ((funcs message-make-forward-subject-function)
7014             (subject (message-fetch-field "Subject")))
7015         (setq subject
7016               (if subject
7017                   (if message-forward-decoded-p
7018                       subject
7019                     (nnheader-decode-subject subject))
7020                 ""))
7021         (when message-wash-forwarded-subjects
7022           (setq subject (message-wash-subject subject)))
7023         ;; Make sure funcs is a list.
7024         (and funcs
7025              (not (listp funcs))
7026              (setq funcs (list funcs)))
7027         ;; Apply funcs in order, passing subject generated by previous
7028         ;; func to the next one.
7029         (dolist (func funcs)
7030           (when (functionp func)
7031             (setq subject (funcall func subject))))
7032         subject))))
7033
7034 ;;;###autoload
7035 (defun message-forward (&optional news)
7036   "Forward the current message via mail.
7037 Optional NEWS will use news to forward instead of mail."
7038   (interactive "P")
7039   (let ((cur (current-buffer))
7040         (subject (message-make-forward-subject)))
7041     (if news
7042         (message-news nil subject)
7043       (message-mail nil subject))
7044     (message-forward-make-body cur)))
7045
7046 (defun message-forward-make-body-plain (forward-buffer)
7047   (insert
7048    "\n-------------------- Start of forwarded message --------------------\n")
7049   (let ((b (point)) e)
7050     (insert
7051      (with-temp-buffer
7052        (mm-disable-multibyte)
7053        (insert
7054         (with-current-buffer forward-buffer
7055           (mm-with-unibyte-current-buffer (buffer-string))))
7056        (mm-enable-multibyte)
7057        (mime-to-mml)
7058        (goto-char (point-min))
7059        (when (looking-at "From ")
7060          (replace-match "X-From-Line: "))
7061        (buffer-string)))
7062     (setq e (point))
7063     (insert
7064      "\n-------------------- End of forwarded message --------------------\n")
7065     (when message-forward-ignored-headers
7066       (save-restriction
7067         (narrow-to-region b e)
7068         (goto-char b)
7069         (narrow-to-region (point)
7070                           (or (search-forward "\n\n" nil t) (point)))
7071         (message-remove-header message-forward-ignored-headers t)))))
7072
7073 (defun message-forward-make-body-mime (forward-buffer)
7074   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7075   (let ((b (point)) e)
7076     (save-restriction
7077       (narrow-to-region (point) (point))
7078       (mml-insert-buffer forward-buffer)
7079       (goto-char (point-min))
7080       (when (looking-at "From ")
7081         (replace-match "X-From-Line: "))
7082       (goto-char (point-max)))
7083     (setq e (point))
7084     (insert "<#/part>\n")))
7085
7086 (defun message-forward-make-body-mml (forward-buffer)
7087   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7088   (let ((b (point)) e)
7089     (if (not message-forward-decoded-p)
7090         (insert
7091          (with-temp-buffer
7092            (mm-disable-multibyte)
7093            (insert
7094             (with-current-buffer forward-buffer
7095               (mm-with-unibyte-current-buffer (buffer-string))))
7096            (mm-enable-multibyte)
7097            (mime-to-mml)
7098            (goto-char (point-min))
7099            (when (looking-at "From ")
7100              (replace-match "X-From-Line: "))
7101            (buffer-string)))
7102       (save-restriction
7103         (narrow-to-region (point) (point))
7104         (mml-insert-buffer forward-buffer)
7105         (goto-char (point-min))
7106         (when (looking-at "From ")
7107           (replace-match "X-From-Line: "))
7108         (goto-char (point-max))))
7109     (setq e (point))
7110     (insert "<#/mml>\n")
7111     (when (and (not message-forward-decoded-p)
7112                message-forward-ignored-headers)
7113       (save-restriction
7114         (narrow-to-region b e)
7115         (goto-char b)
7116         (narrow-to-region (point)
7117                           (or (search-forward "\n\n" nil t) (point)))
7118         (message-remove-header message-forward-ignored-headers t)))))
7119
7120 (defun message-forward-make-body-digest-plain (forward-buffer)
7121   (insert
7122    "\n-------------------- Start of forwarded message --------------------\n")
7123   (let ((b (point)) e)
7124     (mml-insert-buffer forward-buffer)
7125     (setq e (point))
7126     (insert
7127      "\n-------------------- End of forwarded message --------------------\n")))
7128
7129 (defun message-forward-make-body-digest-mime (forward-buffer)
7130   (insert "\n<#multipart type=digest>\n")
7131   (let ((b (point)) e)
7132     (insert-buffer-substring forward-buffer)
7133     (setq e (point))
7134     (insert "<#/multipart>\n")
7135     (save-restriction
7136       (narrow-to-region b e)
7137       (goto-char b)
7138       (narrow-to-region (point)
7139                         (or (search-forward "\n\n" nil t) (point)))
7140       (delete-region (point-min) (point-max)))))
7141
7142 (defun message-forward-make-body-digest (forward-buffer)
7143   (if message-forward-as-mime
7144       (message-forward-make-body-digest-mime forward-buffer)
7145     (message-forward-make-body-digest-plain forward-buffer)))
7146
7147 ;;;###autoload
7148 (defun message-forward-make-body (forward-buffer)
7149   ;; Put point where we want it before inserting the forwarded
7150   ;; message.
7151   ;; Note that this function definition for T-gnus is totally different
7152   ;; from the original Gnus."
7153   (if message-forward-before-signature
7154       (message-goto-body)
7155     (goto-char (point-max)))
7156   ;; Make sure we're at the start of the line.
7157   (unless (bolp)
7158     (insert "\n"))
7159   ;; Narrow to the area we are to insert.
7160   (narrow-to-region (point) (point))
7161   ;; Insert the separators and the forwarded buffer.
7162   (insert message-forward-start-separator)
7163   (let ((art-beg (point)))
7164     (insert-buffer-substring forward-buffer)
7165     (goto-char (point-max))
7166     (insert message-forward-end-separator)
7167     (set-text-properties (point-min) (point-max) nil)
7168     ;; Remove all unwanted headers.
7169     (goto-char art-beg)
7170     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
7171                                   (1- (point))
7172                                 (point)))
7173     (goto-char (point-min))
7174     (message-remove-header message-included-forward-headers t nil t)
7175     (widen)
7176     (message-position-point)))
7177
7178 ;;;###autoload
7179 (defun message-forward-rmail-make-body (forward-buffer)
7180   (save-window-excursion
7181     (set-buffer forward-buffer)
7182     (if (rmail-msg-is-pruned)
7183         (rmail-msg-restore-non-pruned-header)))
7184   (message-forward-make-body forward-buffer))
7185
7186 (eval-when-compile (defvar rmail-enable-mime-composing))
7187
7188 ;; Fixme: Should have defcustom.
7189 ;;;###autoload
7190 (defun message-insinuate-rmail ()
7191   "Let RMAIL use message to forward."
7192   (interactive)
7193   (setq rmail-enable-mime-composing t)
7194   (setq rmail-insert-mime-forwarded-message-function
7195         'message-forward-rmail-make-body))
7196
7197 ;;;###autoload
7198 (defun message-resend (address)
7199   "Resend the current article to ADDRESS."
7200   (interactive
7201    (list (message-read-from-minibuffer "Resend message to: ")))
7202   (message "Resending message to %s..." address)
7203   (save-excursion
7204     (let ((cur (current-buffer))
7205           beg)
7206       ;; We first set up a normal mail buffer.
7207       (unless (message-mail-user-agent)
7208         (set-buffer (get-buffer-create " *message resend*"))
7209         (erase-buffer))
7210       (let ((message-this-is-mail t)
7211             message-setup-hook)
7212         (message-setup `((To . ,address))))
7213       ;; Insert our usual headers.
7214       (message-generate-headers '(From Date To Message-ID))
7215       (message-narrow-to-headers)
7216       ;; Remove X-Draft-From header etc.
7217       (message-remove-header message-ignored-mail-headers t)
7218       ;; Rename them all to "Resent-*".
7219       (goto-char (point-min))
7220       (while (re-search-forward "^[A-Za-z]" nil t)
7221         (forward-char -1)
7222         (insert "Resent-"))
7223       (widen)
7224       (forward-line)
7225       (delete-region (point) (point-max))
7226       (setq beg (point))
7227       ;; Insert the message to be resent.
7228       (insert-buffer-substring cur)
7229       (goto-char (point-min))
7230       (search-forward "\n\n")
7231       (forward-char -1)
7232       (save-restriction
7233         (narrow-to-region beg (point))
7234         (message-remove-header message-ignored-resent-headers t)
7235         (goto-char (point-max)))
7236       (insert mail-header-separator)
7237       ;; Rename all old ("Also-")Resent headers.
7238       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7239         (beginning-of-line)
7240         (insert "Also-"))
7241       ;; Quote any "From " lines at the beginning.
7242       (goto-char beg)
7243       (when (looking-at "From ")
7244         (replace-match "X-From-Line: "))
7245       ;; Send it.
7246       (let ((message-encoding-buffer (current-buffer))
7247             (message-edit-buffer (current-buffer))
7248             message-required-mail-headers)
7249         (message-send-mail))
7250       (kill-buffer (current-buffer)))
7251     (message "Resending message to %s...done" address)))
7252
7253 (defun message-bounce-setup-for-mime-edit ()
7254   (set (make-local-variable 'message-setup-hook) nil)
7255   (mime-edit-again))
7256
7257 ;;;###autoload
7258 (defun message-bounce ()
7259   "Re-mail the current message.
7260 This only makes sense if the current message is a bounce message that
7261 contains some mail you have written which has been bounced back to
7262 you."
7263   (interactive)
7264   (let ((cur (current-buffer))
7265         mime-boundary boundary)
7266     (message-pop-to-buffer (message-buffer-name "bounce"))
7267     (insert-buffer-substring cur)
7268     (undo-boundary)
7269     (message-narrow-to-head)
7270     (if (and (message-fetch-field "MIME-Version")
7271              (setq mime-boundary (message-fetch-field "Content-Type")))
7272         (if (string-match "boundary=\"\\([^\"]+\\)\"" mime-boundary)
7273             (setq mime-boundary (concat (regexp-quote
7274                                          (match-string 1 mime-boundary))
7275                                         " *\nContent-Type: message/rfc822"))
7276           (setq mime-boundary nil)))
7277     (widen)
7278     (goto-char (point-min))
7279     (re-search-forward "\n\n+" nil t)
7280     (setq boundary (point))
7281     ;; We remove everything before the bounced mail.
7282     (if (or (and mime-boundary
7283                  (re-search-forward mime-boundary nil t)
7284                  (forward-line 1))
7285             (re-search-forward message-unsent-separator nil t)
7286             (progn
7287               (search-forward "\n\n" nil 'move)
7288               (re-search-backward "^Return-Path:.*\n" boundary t)))
7289         (progn
7290           (forward-line 1)
7291           (delete-region (point-min)
7292                          (if (re-search-forward "^[^ \n\t]+:" nil t)
7293                              (match-beginning 0)
7294                            (point))))
7295       (when (re-search-backward "^.?From .*\n" nil t)
7296         (delete-region (match-beginning 0) (match-end 0))))
7297     (save-restriction
7298       (message-narrow-to-head-1)
7299       (message-remove-header message-ignored-bounced-headers t)
7300       (goto-char (point-max))
7301       (insert mail-header-separator))
7302     (when message-bounce-setup-function
7303       (funcall message-bounce-setup-function))
7304     (run-hooks 'message-bounce-setup-hook)
7305     (message-position-point)))
7306
7307 ;;;
7308 ;;; Interactive entry points for new message buffers.
7309 ;;;
7310
7311 ;;;###autoload
7312 (defun message-mail-other-window (&optional to subject)
7313   "Like `message-mail' command, but display mail buffer in another window."
7314   (interactive)
7315   (unless (message-mail-user-agent)
7316     (let ((pop-up-windows t)
7317           (special-display-buffer-names nil)
7318           (special-display-regexps nil)
7319           (same-window-buffer-names nil)
7320           (same-window-regexps nil))
7321       (message-pop-to-buffer (message-buffer-name "mail" to))))
7322   (let ((message-this-is-mail t))
7323     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7324                    nil nil 'switch-to-buffer-other-window)))
7325
7326 ;;;###autoload
7327 (defun message-mail-other-frame (&optional to subject)
7328   "Like `message-mail' command, but display mail buffer in another frame."
7329   (interactive)
7330   (unless (message-mail-user-agent)
7331     (let ((pop-up-frames t)
7332           (special-display-buffer-names nil)
7333           (special-display-regexps nil)
7334           (same-window-buffer-names nil)
7335           (same-window-regexps nil))
7336       (message-pop-to-buffer (message-buffer-name "mail" to))))
7337   (let ((message-this-is-mail t))
7338     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7339                    nil nil 'switch-to-buffer-other-frame)))
7340
7341 ;;;###autoload
7342 (defun message-news-other-window (&optional newsgroups subject)
7343   "Start editing a news article to be sent."
7344   (interactive)
7345   (let ((pop-up-windows t)
7346         (special-display-buffer-names nil)
7347         (special-display-regexps nil)
7348         (same-window-buffer-names nil)
7349         (same-window-regexps nil))
7350     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7351   (let ((message-this-is-news t))
7352     (message-setup `((Newsgroups . ,(or newsgroups ""))
7353                      (Subject . ,(or subject ""))))))
7354
7355 ;;;###autoload
7356 (defun message-news-other-frame (&optional newsgroups subject)
7357   "Start editing a news article to be sent."
7358   (interactive)
7359   (let ((pop-up-frames t)
7360         (special-display-buffer-names nil)
7361         (special-display-regexps nil)
7362         (same-window-buffer-names nil)
7363         (same-window-regexps nil))
7364     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7365   (let ((message-this-is-news t))
7366     (message-setup `((Newsgroups . ,(or newsgroups ""))
7367                      (Subject . ,(or subject ""))))))
7368
7369 ;;; underline.el
7370
7371 ;; This code should be moved to underline.el (from which it is stolen).
7372
7373 ;;;###autoload
7374 (defun message-bold-region (start end)
7375   "Bold all nonblank characters in the region.
7376 Works by overstriking characters.
7377 Called from program, takes two arguments START and END
7378 which specify the range to operate on."
7379   (interactive "r")
7380   (save-excursion
7381     (let ((end1 (make-marker)))
7382       (move-marker end1 (max start end))
7383       (goto-char (min start end))
7384       (while (< (point) end1)
7385         (or (looking-at "[_\^@- ]")
7386             (insert (char-after) "\b"))
7387         (forward-char 1)))))
7388
7389 ;;;###autoload
7390 (defun message-unbold-region (start end)
7391   "Remove all boldness (overstruck characters) in the region.
7392 Called from program, takes two arguments START and END
7393 which specify the range to operate on."
7394   (interactive "r")
7395   (save-excursion
7396     (let ((end1 (make-marker)))
7397       (move-marker end1 (max start end))
7398       (goto-char (min start end))
7399       (while (search-forward "\b" end1 t)
7400         (if (eq (char-after) (char-after (- (point) 2)))
7401             (delete-char -2))))))
7402
7403 (defun message-exchange-point-and-mark ()
7404   "Exchange point and mark, but don't activate region if it was inactive."
7405   (unless (prog1
7406               (message-mark-active-p)
7407             (exchange-point-and-mark))
7408     (setq mark-active nil)))
7409
7410 (defalias 'message-make-overlay 'make-overlay)
7411 (defalias 'message-delete-overlay 'delete-overlay)
7412 (defalias 'message-overlay-put 'overlay-put)
7413 (defun message-kill-all-overlays ()
7414   (if (featurep 'xemacs)
7415       (map-extents (lambda (extent ignore) (delete-extent extent)))
7416     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7417
7418 ;; Support for toolbar
7419 (eval-when-compile
7420   (defvar tool-bar-map)
7421   (defvar tool-bar-mode))
7422
7423 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
7424   ;; We need to make tool bar entries in local keymaps with
7425   ;; `tool-bar-local-item-from-menu' in Emacs >= 22
7426   (if (fboundp 'tool-bar-local-item-from-menu)
7427       (tool-bar-local-item-from-menu command icon in-map from-map props)
7428     (tool-bar-add-item-from-menu command icon from-map props)))
7429
7430 (defun message-tool-bar-map ()
7431   (or message-tool-bar-map
7432       (setq message-tool-bar-map
7433             (and
7434              (condition-case nil (require 'tool-bar) (error nil))
7435              (fboundp 'tool-bar-add-item-from-menu)
7436              tool-bar-mode
7437              (let ((tool-bar-map (copy-keymap tool-bar-map))
7438                    (load-path (mm-image-load-path)))
7439                ;; Zap some items which aren't so relevant and take
7440                ;; up space.
7441                (dolist (key '(print-buffer kill-buffer save-buffer
7442                                            write-file dired open-file))
7443                  (define-key tool-bar-map (vector key) nil))
7444                (message-tool-bar-local-item-from-menu
7445                 'message-send-and-exit "mail/send" tool-bar-map message-mode-map)
7446                (message-tool-bar-local-item-from-menu
7447                 'message-kill-buffer "close" tool-bar-map message-mode-map)
7448                (message-tool-bar-local-item-from-menu
7449                 'message-dont-send "cancel" tool-bar-map message-mode-map)
7450 ;;             (message-tool-bar-local-item-from-menu
7451 ;;              'mime-edit-insert-file "attach"
7452 ;;              tool-bar-map mime-edit-mode-map)
7453                (message-tool-bar-local-item-from-menu
7454                 'ispell-message "spell" tool-bar-map message-mode-map)
7455 ;;             (message-tool-bar-local-item-from-menu
7456 ;;              'mime-edit-preview-message "preview"
7457 ;;              tool-bar-map mime-edit-mode-map)
7458                (message-tool-bar-local-item-from-menu
7459                 'message-insert-importance-high "important"
7460                 tool-bar-map message-mode-map)
7461                (message-tool-bar-local-item-from-menu
7462                 'message-insert-importance-low "unimportant"
7463                 tool-bar-map message-mode-map)
7464                (message-tool-bar-local-item-from-menu
7465                 'message-insert-disposition-notification-to "receipt"
7466                 tool-bar-map message-mode-map)
7467                tool-bar-map)))))
7468
7469 ;;; Group name completion.
7470
7471 (defcustom message-newgroups-header-regexp
7472   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7473   "Regexp that match headers that lists groups."
7474   :group 'message
7475   :type 'regexp)
7476
7477 (defcustom message-completion-alist
7478   (list (cons message-newgroups-header-regexp 'message-expand-group)
7479         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7480         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7481           . message-expand-name)
7482         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7483           . message-expand-name))
7484   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7485   :version "22.1"
7486   :group 'message
7487   :type '(alist :key-type regexp :value-type function))
7488
7489 (defcustom message-expand-name-databases
7490   (list 'bbdb 'eudc 'lsdb)
7491   "List of databases to try for name completion (`message-expand-name').
7492 Each element is a symbol and can be `bbdb', `eudc' or `lsdb'."
7493   :group 'message
7494   :type '(set (const bbdb) (const eudc) (const lsdb)))
7495
7496 (defcustom message-expand-name-function
7497   (cond ((and (boundp 'eudc-protocol)
7498               eudc-protocol)
7499          'eudc-expand-inline)
7500         ((fboundp 'bbdb-complete-name)
7501          'bbdb-complete-name)
7502         ((fboundp 'lsdb-complete-name)
7503          'lsdb-complete-name)
7504         (t 'expand-abbrev))
7505   "*A function called to expand addresses in field body.
7506 This variable is semi-obsolete, set it as nil and use
7507 `message-expand-name-databases' instead."
7508   :group 'message
7509   :type '(radio (const :format "Invalidate it: %v\n" nil)
7510                 (function-item :format "eudc: %v\n" eudc-expand-inline)
7511                 (function-item :format "bbdb: %v\n" bbdb-complete-name)
7512                 (function-item :format "lsdb: %v\n" lsdb-complete-name)
7513                 (function :value expand-abbrev)))
7514
7515 (defcustom message-tab-body-function nil
7516   "*Function to execute when `message-tab' (TAB) is executed in the body.
7517 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7518   :version "22.1"
7519   :group 'message
7520   :link '(custom-manual "(message)Various Commands")
7521   :type '(choice (const nil)
7522                  function))
7523
7524 (defun message-tab ()
7525   "Complete names according to `message-completion-alist'.
7526 Execute function specified by `message-tab-body-function' when not in
7527 those headers."
7528   (interactive)
7529   (let ((alist message-completion-alist))
7530     (while (and alist
7531                 (let ((mail-abbrev-mode-regexp (caar alist)))
7532                   (not (mail-abbrev-in-expansion-header-p))))
7533       (setq alist (cdr alist)))
7534     (funcall (or (cdar alist) message-tab-body-function
7535                  (lookup-key text-mode-map "\t")
7536                  (lookup-key global-map "\t")
7537                  'indent-relative))))
7538
7539 (eval-and-compile
7540   (condition-case nil
7541       (with-temp-buffer
7542         (let ((standard-output (current-buffer)))
7543           (eval '(display-completion-list nil "")))
7544         (defalias 'message-display-completion-list 'display-completion-list))
7545     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
7546      (defun message-display-completion-list (completions &optional ignore)
7547        "Display the list of completions, COMPLETIONS, using `standard-output'."
7548        (display-completion-list completions)))))
7549
7550 (defun message-expand-group ()
7551   "Expand the group name under point."
7552   (let* ((b (save-excursion
7553               (save-restriction
7554                 (narrow-to-region
7555                  (save-excursion
7556                    (beginning-of-line)
7557                    (skip-chars-forward "^:")
7558                    (1+ (point)))
7559                  (point))
7560                 (skip-chars-backward "^, \t\n") (point))))
7561          (completion-ignore-case t)
7562          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7563                                             (point))))
7564          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7565          (completions (all-completions string hashtb))
7566          comp)
7567     (delete-region b (point))
7568     (cond
7569      ((= (length completions) 1)
7570       (if (string= (car completions) string)
7571           (progn
7572             (insert string)
7573             (message "Only matching group"))
7574         (insert (car completions))))
7575      ((and (setq comp (try-completion string hashtb))
7576            (not (string= comp string)))
7577       (insert comp))
7578      (t
7579       (insert string)
7580       (if (not comp)
7581           (message "No matching groups")
7582         (save-selected-window
7583           (pop-to-buffer "*Completions*")
7584           (buffer-disable-undo)
7585           (let ((buffer-read-only nil))
7586             (erase-buffer)
7587             (let ((standard-output (current-buffer)))
7588               (message-display-completion-list (sort completions 'string<)
7589                                                string))
7590             (setq buffer-read-only nil)
7591             (goto-char (point-min))
7592             (delete-region (point) (progn (forward-line 3) (point))))))))))
7593
7594 (defun message-expand-name ()
7595   (cond (message-expand-name-function
7596          (funcall message-expand-name-function))
7597         ((and (memq 'eudc message-expand-name-databases)
7598               (boundp 'eudc-protocol)
7599               eudc-protocol)
7600          (eudc-expand-inline))
7601         ((and (memq 'bbdb message-expand-name-databases)
7602               (fboundp 'bbdb-complete-name))
7603          (bbdb-complete-name))
7604         ((and (memq 'lsdb message-expand-name-databases)
7605               (fboundp 'lsdb-complete-name))
7606          (lsdb-complete-name))
7607         (t 'expand-abbrev)))
7608
7609 ;;; Help stuff.
7610
7611 (defun message-talkative-question (ask question show &rest text)
7612   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7613 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7614 The following arguments may contain lists of values."
7615   (if (and show
7616            (setq text (message-flatten-list text)))
7617       (save-window-excursion
7618         (save-excursion
7619           (with-output-to-temp-buffer " *MESSAGE information message*"
7620             (set-buffer " *MESSAGE information message*")
7621             (fundamental-mode)          ; for Emacs 20.4+
7622             (mapcar 'princ text)
7623             (goto-char (point-min))))
7624         (funcall ask question))
7625     (funcall ask question)))
7626
7627 (defun message-flatten-list (list)
7628   "Return a new, flat list that contains all elements of LIST.
7629
7630 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7631 => (1 2 3 4 5 6 7)"
7632   (cond ((consp list)
7633          (apply 'append (mapcar 'message-flatten-list list)))
7634         (list
7635          (list list))))
7636
7637 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7638   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7639 Then clone the local variables and values from the old buffer to the
7640 new one, cloning only the locals having a substring matching the
7641 regexp VARSTR."
7642   (let ((oldbuf (current-buffer)))
7643     (save-excursion
7644       (set-buffer (generate-new-buffer name))
7645       (message-clone-locals oldbuf varstr)
7646       (current-buffer))))
7647
7648 (defun message-clone-locals (buffer &optional varstr)
7649   "Clone the local variables from BUFFER to the current buffer."
7650   (let ((locals (save-excursion
7651                   (set-buffer buffer)
7652                   (buffer-local-variables)))
7653         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address\\|^user-full-name"))
7654     (mapcar
7655      (lambda (local)
7656        (when (and (consp local)
7657                   (car local)
7658                   (string-match regexp (symbol-name (car local)))
7659                   (or (null varstr)
7660                       (string-match varstr (symbol-name (car local)))))
7661          (ignore-errors
7662            (set (make-local-variable (car local))
7663                 (cdr local)))))
7664      locals)))
7665
7666 ;;; @ for MIME Edit mode
7667 ;;;
7668
7669 (defun message-maybe-encode ()
7670   (when message-mime-mode
7671     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
7672     (let ((pgp-processing (with-current-buffer message-edit-buffer
7673                             mime-edit-pgp-processing)))
7674       (setq mime-edit-pgp-processing pgp-processing))
7675     (run-hooks 'mime-edit-translate-hook)
7676     (if (catch 'mime-edit-error
7677           (save-excursion
7678             (mime-edit-pgp-enclose-buffer)
7679             (mime-edit-translate-body)))
7680         (error "Translation error!"))
7681     (run-hooks 'mime-edit-exit-hook)))
7682
7683 (defun message-mime-insert-article (&optional full-headers)
7684   (interactive "P")
7685   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7686         (message-reply-buffer
7687          (message-get-parameter-with-eval 'original-buffer))
7688         (start (point)))
7689     (message-yank-original nil)
7690     (save-excursion
7691       (narrow-to-region (goto-char start)
7692                         (if (search-forward "\n\n" nil t)
7693                             (1- (point))
7694                           (point-max)))
7695       (goto-char (point-min))
7696       (let ((message-included-forward-headers
7697              (if full-headers "" message-included-forward-headers)))
7698         (message-remove-header message-included-forward-headers t nil t))
7699       (widen))))
7700
7701 (set-alist 'mime-edit-message-inserter-alist
7702            'message-mode (function message-mime-insert-article))
7703
7704 ;;;
7705 ;;; MIME functions
7706 ;;;
7707
7708 (defvar message-inhibit-body-encoding t)
7709
7710 (defun message-encode-message-body ()
7711   (unless message-inhibit-body-encoding
7712     (let ((mail-parse-charset (or mail-parse-charset
7713                                   message-default-charset))
7714           (case-fold-search t)
7715           lines content-type-p)
7716       (message-goto-body)
7717       (save-restriction
7718         (narrow-to-region (point) (point-max))
7719         (let ((new (mml-generate-mime)))
7720           (when new
7721             (delete-region (point-min) (point-max))
7722             (insert new)
7723             (goto-char (point-min))
7724             (if (eq (aref new 0) ?\n)
7725                 (delete-char 1)
7726               (search-forward "\n\n")
7727               (setq lines (buffer-substring (point-min) (1- (point))))
7728               (delete-region (point-min) (point))))))
7729       (save-restriction
7730         (message-narrow-to-headers-or-head)
7731         (message-remove-header "Mime-Version")
7732         (goto-char (point-max))
7733         (insert "MIME-Version: 1.0\n")
7734         (when lines
7735           (insert lines))
7736         (setq content-type-p
7737               (or mml-boundary
7738                   (re-search-backward "^Content-Type:" nil t))))
7739       (save-restriction
7740         (message-narrow-to-headers-or-head)
7741         (message-remove-first-header "Content-Type")
7742         (message-remove-first-header "Content-Transfer-Encoding"))
7743       ;; We always make sure that the message has a Content-Type
7744       ;; header.  This is because some broken MTAs and MUAs get
7745       ;; awfully confused when confronted with a message with a
7746       ;; MIME-Version header and without a Content-Type header.  For
7747       ;; instance, Solaris' /usr/bin/mail.
7748       (unless content-type-p
7749         (goto-char (point-min))
7750         ;; For unknown reason, MIME-Version doesn't exist.
7751         (when (re-search-forward "^MIME-Version:" nil t)
7752           (forward-line 1)
7753           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7754
7755 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7756   "Read from the minibuffer while providing abbrev expansion."
7757   (if (fboundp 'mail-abbrevs-setup)
7758       (let ((mail-abbrev-mode-regexp "")
7759             (minibuffer-setup-hook 'mail-abbrevs-setup)
7760             (minibuffer-local-map message-minibuffer-local-map))
7761         (read-from-minibuffer prompt initial-contents))
7762     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7763           (minibuffer-local-map message-minibuffer-local-map))
7764       (read-string prompt initial-contents))))
7765
7766 (defun message-use-alternative-email-as-from ()
7767   "Set From field of the outgoing message to the first matching
7768 address in `message-alternative-emails', looking at To, Cc and
7769 From headers in the original article."
7770   (require 'mail-utils)
7771   (let* ((fields '("To" "Cc" "From"))
7772          (emails
7773           (split-string
7774            (mail-strip-quoted-names
7775             (mapconcat 'message-fetch-reply-field fields ","))
7776            "[ \f\t\n\r\v,]+"))
7777          email)
7778     (while emails
7779       (if (string-match message-alternative-emails (car emails))
7780           (setq email (car emails)
7781                 emails nil))
7782       (pop emails))
7783     (unless (or (not email) (equal email user-mail-address))
7784       (message-remove-header "From")
7785       (goto-char (point-max))
7786       (insert "From: " (let ((user-mail-address email)) (message-make-from))
7787               "\n"))))
7788
7789 (defun message-options-get (symbol)
7790   (cdr (assq symbol message-options)))
7791
7792 (defun message-options-set (symbol value)
7793   (let ((the-cons (assq symbol message-options)))
7794     (if the-cons
7795         (if value
7796             (setcdr the-cons value)
7797           (setq message-options (delq the-cons message-options)))
7798       (and value
7799            (push (cons symbol value) message-options))))
7800   value)
7801
7802 (defun message-options-set-recipient ()
7803   (save-restriction
7804     (message-narrow-to-headers-or-head)
7805     (message-options-set 'message-sender
7806                          (mail-strip-quoted-names
7807                           (message-fetch-field "from")))
7808     (message-options-set 'message-recipients
7809                          (mail-strip-quoted-names
7810                           (let ((to (message-fetch-field "to"))
7811                                 (cc (message-fetch-field "cc"))
7812                                 (bcc (message-fetch-field "bcc")))
7813                             (concat
7814                              (or to "")
7815                              (if (and to cc) ", ")
7816                              (or cc "")
7817                              (if (and (or to cc) bcc) ", ")
7818                              (or bcc "")))))))
7819
7820 (defun message-hide-headers ()
7821   "Hide headers based on the `message-hidden-headers' variable."
7822   (let ((regexps (if (stringp message-hidden-headers)
7823                      (list message-hidden-headers)
7824                    message-hidden-headers))
7825         (inhibit-point-motion-hooks t)
7826         (after-change-functions nil)
7827         (end-of-headers 0))
7828     (when regexps
7829       (save-excursion
7830         (save-restriction
7831           (message-narrow-to-headers)
7832           (goto-char (point-min))
7833           (while (not (eobp))
7834             (if (not (message-hide-header-p regexps))
7835                 (message-next-header)
7836               (let ((begin (point))
7837                     header header-len)
7838                 (message-next-header)
7839                 (setq header (buffer-substring begin (point))
7840                       header-len (- (point) begin))
7841                 (delete-region begin (point))
7842                 (goto-char (1+ end-of-headers))
7843                 (insert header)
7844                 (setq end-of-headers
7845                       (+ end-of-headers header-len))))))))
7846     (narrow-to-region (1+ end-of-headers) (point-max))))
7847
7848 (defun message-hide-header-p (regexps)
7849   (let ((result nil)
7850         (reverse nil))
7851     (when (eq (car regexps) 'not)
7852       (setq reverse t)
7853       (pop regexps))
7854     (dolist (regexp regexps)
7855       (setq result (or result (looking-at regexp))))
7856     (if reverse
7857         (not result)
7858       result)))
7859
7860 (when (featurep 'xemacs)
7861   (require 'messagexmas)
7862   (message-xmas-redefine))
7863
7864 (provide 'message)
7865
7866 (run-hooks 'message-load-hook)
7867
7868 ;; Local Variables:
7869 ;; coding: iso-8859-1
7870 ;; End:
7871
7872 ;;; message.el ends here