1ffad3f9f3a1eaf66b4c36734cd2f81b40181997
[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 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 . bold-region)
1571     (underline . underline-region)
1572     (default . (lambda (b e)
1573                  (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   "A regexp to match the alternative email addresses.
1638 The first matched address (not primary one) is used in the From field."
1639   :group 'message-headers
1640   :link '(custom-manual "(message)Message Headers")
1641   :type '(choice (const :tag "Always use primary" nil)
1642                  regexp))
1643
1644 (defcustom message-hierarchical-addresses nil
1645   "A list of hierarchical mail address definitions.
1646
1647 Inside each entry, the first address is the \"top\" address, and
1648 subsequent addresses are subaddresses; this is used to indicate that
1649 mail sent to the first address will automatically be delivered to the
1650 subaddresses.  So if the first address appears in the recipient list
1651 for a message, the subaddresses will be removed (if present) before
1652 the mail is sent.  All addresses in this structure should be
1653 downcased."
1654   :version "22.1"
1655   :group 'message-headers
1656   :type '(repeat (repeat string)))
1657
1658 (defcustom message-mail-user-agent nil
1659   "Like `mail-user-agent'.
1660 Except if it is nil, use Gnus native MUA; if it is t, use
1661 `mail-user-agent'."
1662   :version "22.1"
1663   :type '(radio (const :tag "Gnus native"
1664                        :format "%t\n"
1665                        nil)
1666                 (const :tag "`mail-user-agent'"
1667                        :format "%t\n"
1668                        t)
1669                 (function-item :tag "Default Emacs mail"
1670                                :format "%t\n"
1671                                sendmail-user-agent)
1672                 (function-item :tag "Emacs interface to MH"
1673                                :format "%t\n"
1674                                mh-e-user-agent)
1675                 (function :tag "Other"))
1676   :version "21.1"
1677   :group 'message)
1678
1679 (defcustom message-wide-reply-confirm-recipients nil
1680   "Whether to confirm a wide reply to multiple email recipients.
1681 If this variable is nil, don't ask whether to reply to all recipients.
1682 If this variable is non-nil, pose the question \"Reply to all
1683 recipients?\" before a wide reply to multiple recipients.  If the user
1684 answers yes, reply to all recipients as usual.  If the user answers
1685 no, only reply back to the author."
1686   :version "22.1"
1687   :group 'message-headers
1688   :link '(custom-manual "(message)Wide Reply")
1689   :type 'boolean)
1690
1691 (defcustom message-user-fqdn nil
1692   "*Domain part of Message-Ids."
1693   :version "22.1"
1694   :group 'message-headers
1695   :link '(custom-manual "(message)News Headers")
1696   :type '(radio (const :format "%v  " nil)
1697                 (string :format "FQDN: %v")))
1698
1699 (defcustom message-use-idna (and (condition-case nil (require 'idna)
1700                                    (file-error))
1701                                  (mm-coding-system-p 'utf-8)
1702                                  (executable-find idna-program)
1703                                  'ask)
1704   "Whether to encode non-ASCII in domain names into ASCII according to IDNA."
1705   :version "22.1"
1706   :group 'message-headers
1707   :link '(custom-manual "(message)IDNA")
1708   :type '(choice (const :tag "Ask" ask)
1709                  (const :tag "Never" nil)
1710                  (const :tag "Always" t)))
1711
1712 (defcustom message-generate-hashcash nil
1713   "*Whether to generate X-Hashcash: headers.
1714 You must have the \"hashcash\" binary installed, see `hashcash-path'."
1715   :group 'message-headers
1716   :link '(custom-manual "(message)Mail Headers")
1717   :type 'boolean)
1718
1719 ;;; Internal variables.
1720
1721 (defvar message-sending-message "Sending...")
1722 (defvar message-buffer-list nil)
1723 (defvar message-this-is-news nil)
1724 (defvar message-this-is-mail nil)
1725 (defvar message-draft-article nil)
1726 (defvar message-mime-part nil)
1727 (defvar message-posting-charset nil)
1728 (defvar message-inserted-headers nil)
1729
1730 ;; Byte-compiler warning
1731 (eval-when-compile
1732   (defvar gnus-active-hashtb)
1733   (defvar gnus-read-active-file))
1734
1735 ;;; Regexp matching the delimiter of messages in UNIX mail format
1736 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1737 ;;; of rmail.el's rmail-unix-mail-delimiter.
1738 (defvar message-unix-mail-delimiter
1739   (let ((time-zone-regexp
1740          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1741                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1742                  "\\|"
1743                  "\\) *")))
1744     (concat
1745      "From "
1746
1747      ;; Many things can happen to an RFC 822 mailbox before it is put into
1748      ;; a `From' line.  The leading phrase can be stripped, e.g.
1749      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1750      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1751      ;; can be removed, e.g.
1752      ;;         From: joe@y.z (Joe      K
1753      ;;                 User)
1754      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1755      ;;         From: Joe User
1756      ;;                 <joe@y.z>
1757      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1758      ;; The mailbox can be removed or be replaced by white space, e.g.
1759      ;;         From: "Joe User"{space}{tab}
1760      ;;                 <joe@y.z>
1761      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1762      ;; where {space} and {tab} represent the Ascii space and tab characters.
1763      ;; We want to match the results of any of these manglings.
1764      ;; The following regexp rejects names whose first characters are
1765      ;; obviously bogus, but after that anything goes.
1766      "\\([^\0-\b\n-\r\^?].*\\)?"
1767
1768      ;; The time the message was sent.
1769      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1770      "\\([^\0-\r \^?]+\\) +"            ; month
1771      "\\([0-3]?[0-9]\\) +"              ; day of month
1772      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1773
1774      ;; Perhaps a time zone, specified by an abbreviation, or by a
1775      ;; numeric offset.
1776      time-zone-regexp
1777
1778      ;; The year.
1779      " \\([0-9][0-9]+\\) *"
1780
1781      ;; On some systems the time zone can appear after the year, too.
1782      time-zone-regexp
1783
1784      ;; Old uucp cruft.
1785      "\\(remote from .*\\)?"
1786
1787      "\n"))
1788   "Regexp matching the delimiter of messages in UNIX mail format.")
1789
1790 (defvar message-unsent-separator
1791   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1792           "^ *---+ +Returned message +---+ *$\\|"
1793           "^Start of returned message$\\|"
1794           "^ *---+ +Original message +---+ *$\\|"
1795           "^ *--+ +begin message +--+ *$\\|"
1796           "^ *---+ +Original message follows +---+ *$\\|"
1797           "^ *---+ +Undelivered message follows +---+ *$\\|"
1798           "^|? *---+ +Message text follows: +---+ *|?$")
1799   "A regexp that matches the separator before the text of a failed message.")
1800
1801 (defvar message-field-fillers
1802   '((To message-fill-field-address)
1803     (Cc message-fill-field-address)
1804     (From message-fill-field-address))
1805   "Alist of header names/filler functions.")
1806
1807 (defvar message-header-format-alist
1808   `((From)
1809     (Newsgroups)
1810     (To)
1811     (Cc)
1812     (Subject)
1813     (In-Reply-To)
1814     (Fcc)
1815     (Bcc)
1816     (Date)
1817     (Organization)
1818     (Distribution)
1819     (Lines)
1820     (Expires)
1821     (Message-ID)
1822     (References . message-shorten-references)
1823     (User-Agent))
1824   "Alist used for formatting headers.")
1825
1826 (defvar message-options nil
1827   "Some saved answers when sending message.")
1828
1829 (defvar message-send-mail-real-function nil
1830   "Internal send mail function.")
1831
1832 (defvar message-bogus-system-names "^localhost\\."
1833   "The regexp of bogus system names.")
1834
1835 (defcustom message-valid-fqdn-regexp
1836   (concat "[a-z0-9][-.a-z0-9]+\\." ;; [hostname.subdomain.]domain.
1837           ;; valid TLDs:
1838           "\\([a-z][a-z]" ;; two letter country TDLs
1839           "\\|biz\\|com\\|edu\\|gov\\|int\\|mil\\|net\\|org"
1840           "\\|aero\\|coop\\|info\\|name\\|museum"
1841           "\\|arpa\\|pro\\|uucp\\|bitnet\\|bofh" ;; old style?
1842           "\\)")
1843   "Regular expression that matches a valid FQDN."
1844   ;; see also: gnus-button-valid-fqdn-regexp
1845   :version "22.1"
1846   :group 'message-headers
1847   :type 'regexp)
1848
1849 (eval-and-compile
1850   (autoload 'gnus-alive-p "gnus-util")
1851   (autoload 'gnus-delay-article "gnus-delay")
1852   (autoload 'gnus-extract-address-components "gnus-util")
1853   (autoload 'gnus-find-method-for-group "gnus")
1854   (autoload 'gnus-group-decoded-name "gnus-group")
1855   (autoload 'gnus-group-name-charset "gnus-group")
1856   (autoload 'gnus-group-name-decode "gnus-group")
1857   (autoload 'gnus-groups-from-server "gnus")
1858   (autoload 'gnus-make-local-hook "gnus-util")
1859   (autoload 'gnus-open-server "gnus-int")
1860   (autoload 'gnus-output-to-mail "gnus-util")
1861   (autoload 'gnus-output-to-rmail "gnus-util")
1862   (autoload 'gnus-request-post "gnus-int")
1863   (autoload 'gnus-server-string "gnus")
1864   (autoload 'idna-to-ascii "idna")
1865   (autoload 'message-setup-toolbar "messagexmas")
1866   (autoload 'mh-new-draft-name "mh-comp")
1867   (autoload 'mh-send-letter "mh-comp")
1868   (autoload 'mu-cite-original "mu-cite")
1869   (autoload 'nndraft-request-associate-buffer "nndraft")
1870   (autoload 'nndraft-request-expire-articles "nndraft")
1871   (autoload 'nnvirtual-find-group-art "nnvirtual")
1872   (autoload 'rmail-dont-reply-to "mail-utils")
1873   (autoload 'rmail-msg-is-pruned "rmail")
1874   (autoload 'rmail-msg-restore-non-pruned-header "rmail")
1875   (autoload 'rmail-output "rmailout"))
1876
1877 \f
1878
1879 ;;;
1880 ;;; Utility functions.
1881 ;;;
1882 (defun message-eval-parameter (parameter)
1883   (condition-case ()
1884       (if (symbolp parameter)
1885           (if (functionp parameter)
1886               (funcall parameter)
1887             (eval parameter))
1888         parameter)
1889     (error nil)))
1890
1891 (defsubst message-get-parameter (key &optional alist)
1892   (unless alist
1893     (setq alist message-parameter-alist))
1894   (cdr (assq key alist)))
1895
1896 (defmacro message-get-parameter-with-eval (key &optional alist)
1897   `(message-eval-parameter (message-get-parameter ,key ,alist)))
1898
1899 (defmacro message-y-or-n-p (question show &rest text)
1900   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1901   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1902
1903 (defmacro message-delete-line (&optional n)
1904   "Delete the current line (and the next N lines)."
1905   `(delete-region (progn (beginning-of-line) (point))
1906                   (progn (forward-line ,(or n 1)) (point))))
1907
1908 (defun message-mark-active-p ()
1909   "Non-nil means the mark and region are currently active in this buffer."
1910   mark-active)
1911
1912 (defun message-unquote-tokens (elems)
1913   "Remove double quotes (\") from strings in list ELEMS."
1914   (mapcar (lambda (item)
1915             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1916               (setq item (concat (match-string 1 item)
1917                                  (match-string 2 item))))
1918             item)
1919           elems))
1920
1921 (defun message-tokenize-header (header &optional separator)
1922   "Split HEADER into a list of header elements.
1923 SEPARATOR is a string of characters to be used as separators.  \",\"
1924 is used by default."
1925   (if (not header)
1926       nil
1927     (let ((regexp (format "[%s]+" (or separator ",")))
1928           (first t)
1929           beg quoted elems paren)
1930       (with-temp-buffer
1931         (set-buffer-multibyte t)
1932         (setq beg (point-min))
1933         (insert header)
1934         (goto-char (point-min))
1935         (while (not (eobp))
1936           (if first
1937               (setq first nil)
1938             (forward-char 1))
1939           (cond ((and (> (point) beg)
1940                       (or (eobp)
1941                           (and (looking-at regexp)
1942                                (not quoted)
1943                                (not paren))))
1944                  (push (buffer-substring beg (point)) elems)
1945                  (setq beg (match-end 0)))
1946                 ((eq (char-after) ?\")
1947                  (setq quoted (not quoted)))
1948                 ((and (eq (char-after) ?\()
1949                       (not quoted))
1950                  (setq paren t))
1951                 ((and (eq (char-after) ?\))
1952                       (not quoted))
1953                  (setq paren nil))))
1954         (nreverse elems)))))
1955
1956 (defun message-mail-file-mbox-p (file)
1957   "Say whether FILE looks like a Unix mbox file."
1958   (when (and (file-exists-p file)
1959              (file-readable-p file)
1960              (file-regular-p file))
1961     (with-temp-buffer
1962       (nnheader-insert-file-contents file)
1963       (goto-char (point-min))
1964       (looking-at message-unix-mail-delimiter))))
1965
1966 (defun message-fetch-field (header &optional not-all)
1967   "The same as `mail-fetch-field', only remove all newlines.
1968 The buffer is expected to be narrowed to just the header of the message;
1969 see `message-narrow-to-headers-or-head'."
1970   (let* ((inhibit-point-motion-hooks t)
1971          (value (mail-fetch-field header nil (not not-all))))
1972     (when value
1973       (while (string-match "\n[\t ]+" value)
1974         (setq value (replace-match " " t t value)))
1975       value)))
1976
1977 (defun message-field-value (header &optional not-all)
1978   "The same as `message-fetch-field', only narrow to the headers first."
1979   (save-excursion
1980     (save-restriction
1981       (message-narrow-to-headers-or-head)
1982       (message-fetch-field header not-all))))
1983
1984 (defun message-narrow-to-field ()
1985   "Narrow the buffer to the header on the current line."
1986   (beginning-of-line)
1987   (while (looking-at "[ \t]")
1988     (forward-line -1))
1989   (narrow-to-region
1990    (point)
1991    (progn
1992      (forward-line 1)
1993      (if (re-search-forward "^[^ \n\t]" nil t)
1994          (point-at-bol)
1995        (point-max))))
1996   (goto-char (point-min)))
1997
1998 (defun message-add-header (&rest headers)
1999   "Add the HEADERS to the message header, skipping those already present."
2000   (while headers
2001     (let (hclean)
2002       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
2003         (error "Invalid header `%s'" (car headers)))
2004       (setq hclean (match-string 1 (car headers)))
2005       (save-restriction
2006         (message-narrow-to-headers)
2007         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
2008           (goto-char (point-max))
2009           (if (string-match "\n$" (car headers))
2010               (insert (car headers))
2011             (insert (car headers) ?\n)))))
2012     (setq headers (cdr headers))))
2013
2014 (defmacro message-with-reply-buffer (&rest forms)
2015   "Evaluate FORMS in the reply buffer, if it exists."
2016   `(let ((buffer (message-eval-parameter message-reply-buffer)))
2017      (when (and buffer
2018                 (buffer-name buffer))
2019        (save-excursion
2020          (set-buffer buffer)
2021          ,@forms))))
2022
2023 (put 'message-with-reply-buffer 'lisp-indent-function 0)
2024 (put 'message-with-reply-buffer 'edebug-form-spec '(body))
2025
2026 (defun message-fetch-reply-field (header)
2027   "Fetch field HEADER from the message we're replying to."
2028   (message-with-reply-buffer
2029     (save-restriction
2030       (mail-narrow-to-head)
2031       (message-fetch-field header))))
2032
2033 (defun message-strip-list-identifiers (subject)
2034   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
2035   (require 'gnus-sum)                   ; for gnus-list-identifiers
2036   (let ((regexp (if (stringp gnus-list-identifiers)
2037                     gnus-list-identifiers
2038                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
2039     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
2040                               " *\\)\\)+\\(Re: +\\)?\\)") subject)
2041         (concat (substring subject 0 (match-beginning 1))
2042                 (or (match-string 3 subject)
2043                     (match-string 5 subject))
2044                 (substring subject
2045                            (match-end 1)))
2046       subject)))
2047
2048 (defun message-strip-subject-re (subject)
2049   "Remove \"Re:\" from subject lines in string SUBJECT."
2050   (if (string-match message-subject-re-regexp subject)
2051       (substring subject (match-end 0))
2052     subject))
2053
2054 ;;; Start of functions adopted from `message-utils.el'.
2055
2056 (defun message-strip-subject-trailing-was (subject)
2057   "Remove trailing \"(was: <old subject>)\" from SUBJECT lines.
2058 Leading \"Re: \" is not stripped by this function.  Use the function
2059 `message-strip-subject-re' for this."
2060   (let* ((query message-subject-trailing-was-query)
2061          (new) (found))
2062     (setq found
2063           (string-match
2064            (if (eq query 'ask)
2065                message-subject-trailing-was-ask-regexp
2066              message-subject-trailing-was-regexp)
2067            subject))
2068     (if found
2069         (setq new (substring subject 0 (match-beginning 0))))
2070     (if (or (not found) (eq query nil))
2071         subject
2072       (if (eq query 'ask)
2073           (if (message-y-or-n-p
2074                "Strip `(was: <old subject>)' in subject? " t
2075                (concat
2076                 "Strip `(was: <old subject>)' in subject "
2077                 "and use the new one instead?\n\n"
2078                 "Current subject is:   \""
2079                 subject "\"\n\n"
2080                 "New subject would be: \""
2081                 new "\"\n\n"
2082                 "See the variable `message-subject-trailing-was-query' "
2083                 "to get rid of this query."
2084                 ))
2085               new subject)
2086         new))))
2087
2088 ;;; Suggested by Jonas Steverud  @  www.dtek.chalmers.se/~d4jonas/
2089
2090 ;;;###autoload
2091 (defun message-change-subject (new-subject)
2092   "Ask for NEW-SUBJECT header, append (was: <Old Subject>)."
2093   ;; <URL:http://www.landfield.com/usefor/drafts/draft-ietf-usefor-useage--1.02.unpaged>
2094   (interactive
2095    (list
2096     (read-from-minibuffer "New subject: ")))
2097   (cond ((and (not (or (null new-subject) ; new subject not empty
2098                        (zerop (string-width new-subject))
2099                        (string-match "^[ \t]*$" new-subject))))
2100          (save-excursion
2101            (let ((old-subject
2102                   (save-restriction
2103                     (message-narrow-to-headers)
2104                     (message-fetch-field "Subject"))))
2105              (cond ((not old-subject)
2106                     (error "No current subject"))
2107                    ((not (string-match
2108                           (concat "^[ \t]*"
2109                                   (regexp-quote new-subject)
2110                                   " \t]*$")
2111                           old-subject))  ; yes, it really is a new subject
2112                     ;; delete eventual Re: prefix
2113                     (setq old-subject
2114                           (message-strip-subject-re old-subject))
2115                     (message-goto-subject)
2116                     (message-delete-line)
2117                     (insert (concat "Subject: "
2118                                     new-subject
2119                                     " (was: "
2120                                     old-subject ")\n")))))))))
2121
2122 ;;;###autoload
2123 (defun message-mark-inserted-region (beg end)
2124   "Mark some region in the current article with enclosing tags.
2125 See `message-mark-insert-begin' and `message-mark-insert-end'."
2126   (interactive "r")
2127   (save-excursion
2128     ;; add to the end of the region first, otherwise end would be invalid
2129     (goto-char end)
2130     (insert message-mark-insert-end)
2131     (goto-char beg)
2132     (insert message-mark-insert-begin)))
2133
2134 ;;;###autoload
2135 (defun message-mark-insert-file (file)
2136   "Insert FILE at point, marking it with enclosing tags.
2137 See `message-mark-insert-begin' and `message-mark-insert-end'."
2138   (interactive "fFile to insert: ")
2139     ;; reverse insertion to get correct result.
2140   (let ((p (point)))
2141     (insert message-mark-insert-end)
2142     (goto-char p)
2143     (insert-file-contents file)
2144     (goto-char p)
2145     (insert message-mark-insert-begin)))
2146
2147 ;;;###autoload
2148 (defun message-add-archive-header ()
2149   "Insert \"X-No-Archive: Yes\" in the header and a note in the body.
2150 The note can be customized using `message-archive-note'.  When called with a
2151 prefix argument, ask for a text to insert.  If you don't want the note in the
2152 body, set  `message-archive-note' to nil."
2153   (interactive)
2154   (if current-prefix-arg
2155       (setq message-archive-note
2156             (read-from-minibuffer "Reason for No-Archive: "
2157                                   (cons message-archive-note 0))))
2158     (save-excursion
2159       (if (message-goto-signature)
2160           (re-search-backward message-signature-separator))
2161       (when message-archive-note
2162         (insert message-archive-note)
2163         (newline))
2164       (message-add-header message-archive-header)
2165       (message-sort-headers)))
2166
2167 ;;;###autoload
2168 (defun message-cross-post-followup-to-header (target-group)
2169   "Mangles FollowUp-To and Newsgroups header to point to TARGET-GROUP.
2170 With prefix-argument just set Follow-Up, don't cross-post."
2171   (interactive
2172    (list ; Completion based on Gnus
2173     (completing-read "Followup To: "
2174                      (if (boundp 'gnus-newsrc-alist)
2175                          gnus-newsrc-alist)
2176                      nil nil '("poster" . 0)
2177                      (if (boundp 'gnus-group-history)
2178                          'gnus-group-history))))
2179   (message-remove-header "Follow[Uu]p-[Tt]o" t)
2180   (message-goto-newsgroups)
2181   (beginning-of-line)
2182   ;; if we already did a crosspost before, kill old target
2183   (if (and message-cross-post-old-target
2184            (re-search-forward
2185             (regexp-quote (concat "," message-cross-post-old-target))
2186             nil t))
2187       (replace-match ""))
2188   ;; unless (followup is to poster or user explicitly asked not
2189   ;; to cross-post, or target-group is already in Newsgroups)
2190   ;; add target-group to Newsgroups line.
2191   (cond ((and (or
2192                ;; def: cross-post, req:no
2193                (and message-cross-post-default (not current-prefix-arg))
2194                ;; def: no-cross-post, req:yes
2195                (and (not message-cross-post-default) current-prefix-arg))
2196               (not (string-match "poster" target-group))
2197               (not (string-match (regexp-quote target-group)
2198                                  (message-fetch-field "Newsgroups"))))
2199          (end-of-line)
2200          (insert (concat "," target-group))))
2201   (end-of-line) ; ensure Followup: comes after Newsgroups:
2202   ;; unless new followup would be identical to Newsgroups line
2203   ;; make a new Followup-To line
2204   (if (not (string-match (concat "^[ \t]*"
2205                                  target-group
2206                                  "[ \t]*$")
2207                          (message-fetch-field "Newsgroups")))
2208       (insert (concat "\nFollowup-To: " target-group)))
2209   (setq message-cross-post-old-target target-group))
2210
2211 ;;;###autoload
2212 (defun message-cross-post-insert-note (target-group cross-post in-old
2213                                                     old-groups)
2214   "Insert a in message body note about a set Followup or Crosspost.
2215 If there have been previous notes, delete them.  TARGET-GROUP specifies the
2216 group to Followup-To.  When CROSS-POST is t, insert note about
2217 crossposting.  IN-OLD specifies whether TARGET-GROUP is a member of
2218 OLD-GROUPS.  OLD-GROUPS lists the old-groups the posting would have
2219 been made to before the user asked for a Crosspost."
2220   ;; start scanning body for previous uses
2221   (message-goto-signature)
2222   (let ((head (re-search-backward
2223                (concat "^" mail-header-separator)
2224                nil t))) ; just search in body
2225     (message-goto-signature)
2226     (while (re-search-backward
2227             (concat "^" (regexp-quote message-cross-post-note) ".*")
2228             head t)
2229       (message-delete-line))
2230     (message-goto-signature)
2231     (while (re-search-backward
2232             (concat "^" (regexp-quote message-followup-to-note) ".*")
2233             head t)
2234       (message-delete-line))
2235     ;; insert new note
2236     (if (message-goto-signature)
2237         (re-search-backward message-signature-separator))
2238     (if (or in-old
2239             (not cross-post)
2240             (string-match "^[ \t]*poster[ \t]*$" target-group))
2241         (insert (concat message-followup-to-note target-group "\n"))
2242       (insert (concat message-cross-post-note target-group "\n")))))
2243
2244 ;;;###autoload
2245 (defun message-cross-post-followup-to (target-group)
2246   "Crossposts message and set Followup-To to TARGET-GROUP.
2247 With prefix-argument just set Follow-Up, don't cross-post."
2248   (interactive
2249    (list ; Completion based on Gnus
2250     (completing-read "Followup To: "
2251                      (if (boundp 'gnus-newsrc-alist)
2252                          gnus-newsrc-alist)
2253                      nil nil '("poster" . 0)
2254                      (if (boundp 'gnus-group-history)
2255                          'gnus-group-history))))
2256   (cond ((not (or (null target-group) ; new subject not empty
2257                   (zerop (string-width target-group))
2258                   (string-match "^[ \t]*$" target-group)))
2259          (save-excursion
2260            (let* ((old-groups (message-fetch-field "Newsgroups"))
2261                   (in-old (string-match
2262                            (regexp-quote target-group)
2263                            (or old-groups ""))))
2264              ;; check whether target exactly matches old Newsgroups
2265              (cond ((not old-groups)
2266                     (error "No current newsgroup"))
2267                    ((or (not in-old)
2268                         (not (string-match
2269                               (concat "^[ \t]*"
2270                                       (regexp-quote target-group)
2271                                       "[ \t]*$")
2272                               old-groups)))
2273                     ;; yes, Newsgroups line must change
2274                     (message-cross-post-followup-to-header target-group)
2275                     ;; insert note whether we do cross-post or followup-to
2276                     (funcall message-cross-post-note-function
2277                              target-group
2278                              (if (or (and message-cross-post-default
2279                                           (not current-prefix-arg))
2280                                      (and (not message-cross-post-default)
2281                                           current-prefix-arg)) t)
2282                              in-old old-groups))))))))
2283
2284 ;;; Reduce To: to Cc: or Bcc: header
2285
2286 ;;;###autoload
2287 (defun message-reduce-to-to-cc ()
2288  "Replace contents of To: header with contents of Cc: or Bcc: header."
2289  (interactive)
2290  (let ((cc-content
2291         (save-restriction (message-narrow-to-headers)
2292                           (message-fetch-field "cc")))
2293        (bcc nil))
2294    (if (and (not cc-content)
2295             (setq cc-content
2296                   (save-restriction
2297                     (message-narrow-to-headers)
2298                     (message-fetch-field "bcc"))))
2299        (setq bcc t))
2300    (cond (cc-content
2301           (save-excursion
2302             (message-goto-to)
2303             (message-delete-line)
2304             (insert (concat "To: " cc-content "\n"))
2305             (save-restriction
2306               (message-narrow-to-headers)
2307               (message-remove-header (if bcc
2308                                          "bcc"
2309                                        "cc"))))))))
2310
2311 ;;; End of functions adopted from `message-utils.el'.
2312
2313 (defun message-remove-header (header &optional is-regexp first reverse)
2314   "Remove HEADER in the narrowed buffer.
2315 If IS-REGEXP, HEADER is a regular expression.
2316 If FIRST, only remove the first instance of the header.
2317 Return the number of headers removed."
2318   (goto-char (point-min))
2319   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
2320         (number 0)
2321         (case-fold-search t)
2322         last)
2323     (while (and (not (eobp))
2324                 (not last))
2325       (if (if reverse
2326               (not (looking-at regexp))
2327             (looking-at regexp))
2328           (progn
2329             (incf number)
2330             (when first
2331               (setq last t))
2332             (delete-region
2333              (point)
2334              ;; There might be a continuation header, so we have to search
2335              ;; until we find a new non-continuation line.
2336              (progn
2337                (forward-line 1)
2338                (if (re-search-forward "^[^ \t]" nil t)
2339                    (goto-char (match-beginning 0))
2340                  (point-max)))))
2341         (forward-line 1)
2342         (if (re-search-forward "^[^ \t]" nil t)
2343             (goto-char (match-beginning 0))
2344           (goto-char (point-max)))))
2345     number))
2346
2347 (defun message-remove-first-header (header)
2348   "Remove the first instance of HEADER if there is more than one."
2349   (let ((count 0)
2350         (regexp (concat "^" (regexp-quote header) ":")))
2351     (save-excursion
2352       (goto-char (point-min))
2353       (while (re-search-forward regexp nil t)
2354         (incf count)))
2355     (while (> count 1)
2356       (message-remove-header header nil t)
2357       (decf count))))
2358
2359 (defun message-narrow-to-headers ()
2360   "Narrow the buffer to the head of the message."
2361   (widen)
2362   (narrow-to-region
2363    (goto-char (point-min))
2364    (if (re-search-forward
2365         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2366        (match-beginning 0)
2367      (point-max)))
2368   (goto-char (point-min)))
2369
2370 (defun message-narrow-to-head-1 ()
2371   "Like `message-narrow-to-head'.  Don't widen."
2372   (narrow-to-region
2373    (goto-char (point-min))
2374    (if (search-forward "\n\n" nil 1)
2375        (1- (point))
2376      (point-max)))
2377   (goto-char (point-min)))
2378
2379 (defun message-narrow-to-head ()
2380   "Narrow the buffer to the head of the message.
2381 Point is left at the beginning of the narrowed-to region."
2382   (widen)
2383   (message-narrow-to-head-1))
2384
2385 (defun message-narrow-to-headers-or-head ()
2386   "Narrow the buffer to the head of the message."
2387   (widen)
2388   (narrow-to-region
2389    (goto-char (point-min))
2390    (cond
2391     ((re-search-forward
2392       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
2393      (match-beginning 0))
2394     ((search-forward "\n\n" nil t)
2395      (1- (point)))
2396     (t
2397      (point-max))))
2398   (goto-char (point-min)))
2399
2400 (defun message-news-p ()
2401   "Say whether the current buffer contains a news message."
2402   (and (not message-this-is-mail)
2403        (or message-this-is-news
2404            (save-excursion
2405              (save-restriction
2406                (message-narrow-to-headers)
2407                (and (message-fetch-field "newsgroups")
2408                     (not (message-fetch-field "posted-to"))))))))
2409
2410 (defun message-mail-p ()
2411   "Say whether the current buffer contains a mail message."
2412   (and (not message-this-is-news)
2413        (or message-this-is-mail
2414            (save-excursion
2415              (save-restriction
2416                (message-narrow-to-headers)
2417                (or (message-fetch-field "to")
2418                    (message-fetch-field "cc")
2419                    (message-fetch-field "bcc")))))))
2420
2421 (defun message-subscribed-p ()
2422   "Say whether we need to insert a MFT header."
2423   (or message-subscribed-regexps
2424       message-subscribed-addresses
2425       message-subscribed-address-file
2426       message-subscribed-address-functions))
2427
2428 (defun message-next-header ()
2429   "Go to the beginning of the next header."
2430   (beginning-of-line)
2431   (or (eobp) (forward-char 1))
2432   (not (if (re-search-forward "^[^ \t]" nil t)
2433            (beginning-of-line)
2434          (goto-char (point-max)))))
2435
2436 (defun message-sort-headers-1 ()
2437   "Sort the buffer as headers using `message-rank' text props."
2438   (goto-char (point-min))
2439   (require 'sort)
2440   (sort-subr
2441    nil 'message-next-header
2442    (lambda ()
2443      (message-next-header)
2444      (unless (bobp)
2445        (forward-char -1)))
2446    (lambda ()
2447      (or (get-text-property (point) 'message-rank)
2448          10000))))
2449
2450 (defun message-sort-headers ()
2451   "Sort the headers of the current message according to `message-header-format-alist'."
2452   (interactive)
2453   (save-excursion
2454     (save-restriction
2455       (let ((max (1+ (length message-header-format-alist)))
2456             rank)
2457         (message-narrow-to-headers)
2458         (while (re-search-forward "^[^ \n]+:" nil t)
2459           (put-text-property
2460            (match-beginning 0) (1+ (match-beginning 0))
2461            'message-rank
2462            (if (setq rank (length (memq (assq (intern (buffer-substring
2463                                                        (match-beginning 0)
2464                                                        (1- (match-end 0))))
2465                                               message-header-format-alist)
2466                                         message-header-format-alist)))
2467                (- max rank)
2468              (1+ max)))))
2469       (message-sort-headers-1))))
2470
2471 (defun message-kill-address ()
2472   "Kill the address under point."
2473   (interactive)
2474   (let ((start (point)))
2475     (message-skip-to-next-address)
2476     (kill-region start (point))))
2477
2478 \f
2479
2480 ;;;
2481 ;;; Message mode
2482 ;;;
2483
2484 ;;; Set up keymap.
2485
2486 (defvar message-mode-map nil)
2487
2488 (unless message-mode-map
2489   (setq message-mode-map (make-keymap))
2490   (set-keymap-parent message-mode-map text-mode-map)
2491   (define-key message-mode-map "\C-c?" 'describe-mode)
2492
2493   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
2494   (define-key message-mode-map "\C-c\C-f\C-o" 'message-goto-from)
2495   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
2496   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
2497   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
2498   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
2499   ;; (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
2500   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-mail-reply-to)
2501   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2502   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
2503   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
2504   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
2505   (define-key message-mode-map "\C-c\C-f\C-m" 'message-goto-mail-followup-to)
2506   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
2507   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
2508   (define-key message-mode-map "\C-c\C-f\C-i"
2509     'message-insert-or-toggle-importance)
2510   (define-key message-mode-map "\C-c\C-f\C-a"
2511     'message-generate-unsubscribed-mail-followup-to)
2512
2513   ;; modify headers (and insert notes in body)
2514   (define-key message-mode-map "\C-c\C-fs"    'message-change-subject)
2515   ;;
2516   (define-key message-mode-map "\C-c\C-fx"    'message-cross-post-followup-to)
2517   ;; prefix+message-cross-post-followup-to = same w/o cross-post
2518   (define-key message-mode-map "\C-c\C-ft"    'message-reduce-to-to-cc)
2519   (define-key message-mode-map "\C-c\C-fa"    'message-add-archive-header)
2520   ;; mark inserted text
2521   (define-key message-mode-map "\C-c\M-m" 'message-mark-inserted-region)
2522   (define-key message-mode-map "\C-c\M-f" 'message-mark-insert-file)
2523
2524   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
2525   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
2526   (define-key message-mode-map "\C-c\C-fc" 'message-goto-mail-copies-to)
2527
2528   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
2529   (define-key message-mode-map "\C-c\C-fw" 'message-insert-wide-reply)
2530   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
2531   (define-key message-mode-map "\C-c\C-l" 'message-to-list-only)
2532
2533   (define-key message-mode-map "\C-c\C-u" 'message-insert-or-toggle-importance)
2534   (define-key message-mode-map "\C-c\M-n"
2535     'message-insert-disposition-notification-to)
2536
2537   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
2538   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
2539   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
2540   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
2541   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
2542   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
2543   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
2544   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
2545
2546   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
2547   (define-key message-mode-map "\C-c\C-s" 'message-send)
2548   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
2549   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
2550   (define-key message-mode-map "\C-c\n" 'gnus-delay-article)
2551
2552   (define-key message-mode-map "\C-c\M-k" 'message-kill-address)
2553   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
2554   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
2555   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
2556   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
2557   (define-key message-mode-map [remap split-line]  'message-split-line)
2558
2559   (define-key message-mode-map "\C-a" 'message-beginning-of-line)
2560   (define-key message-mode-map "\t" 'message-tab)
2561   (define-key message-mode-map "\M-;" 'comment-region)
2562
2563   (define-key message-mode-map "\C-xk" 'message-mimic-kill-buffer))
2564
2565 (easy-menu-define
2566   message-mode-menu message-mode-map "Message Menu."
2567   `("Message"
2568     ["Yank Original" message-yank-original t]
2569     ["Fill Yanked Message" message-fill-yanked-message t]
2570     ["Insert Signature" message-insert-signature t]
2571     ["Caesar (rot13) Message" message-caesar-buffer-body t]
2572     ["Caesar (rot13) Region" message-caesar-region (message-mark-active-p)]
2573     ["Elide Region" message-elide-region
2574      :active (message-mark-active-p)
2575      ,@(if (featurep 'xemacs) nil
2576          '(:help "Replace text in region with an ellipsis"))]
2577     ["Delete Outside Region" message-delete-not-region
2578      :active (message-mark-active-p)
2579      ,@(if (featurep 'xemacs) nil
2580          '(:help "Delete all quoted text outside region"))]
2581     ["Kill To Signature" message-kill-to-signature t]
2582     ["Newline and Reformat" message-newline-and-reformat t]
2583     ["Rename buffer" message-rename-buffer t]
2584     ["Spellcheck" ispell-message
2585      ,@(if (featurep 'xemacs) '(t)
2586          '(:help "Spellcheck this message"))]
2587     ["Attach file as MIME" mime-edit-insert-file
2588      ,@(if (featurep 'xemacs) '(t)
2589          '(:help "Attach a file at point"))]
2590     "----"
2591     ["Insert Region Marked" message-mark-inserted-region
2592      :active (message-mark-active-p)
2593      ,@(if (featurep 'xemacs) nil
2594          '(:help "Mark region with enclosing tags"))]
2595     ["Insert File Marked..." message-mark-insert-file
2596      ,@(if (featurep 'xemacs) '(t)
2597          '(:help "Insert file at point marked with enclosing tags"))]
2598     "----"
2599     ["Send Message" message-send-and-exit
2600      ,@(if (featurep 'xemacs) '(t)
2601          '(:help "Send this message"))]
2602     ["Postpone Message" message-dont-send
2603      ,@(if (featurep 'xemacs) '(t)
2604          '(:help "File this draft message and exit"))]
2605     ["Send at Specific Time..." gnus-delay-article
2606      ,@(if (featurep 'xemacs) '(t)
2607          '(:help "Ask, then arrange to send message at that time"))]
2608     ["Kill Message" message-kill-buffer
2609      ,@(if (featurep 'xemacs) '(t)
2610          '(:help "Delete this message without sending"))]))
2611
2612 (easy-menu-define
2613   message-mode-field-menu message-mode-map ""
2614   `("Field"
2615     ["To" message-goto-to t]
2616     ["From" message-goto-from t]
2617     ["Subject" message-goto-subject t]
2618     ["Change subject..." message-change-subject t]
2619     ["Cc" message-goto-cc t]
2620     ["Bcc" message-goto-bcc t]
2621     ["Fcc" message-goto-fcc t]
2622     ["Reply-To" message-goto-reply-to t]
2623     ["Flag As Important" message-insert-importance-high
2624      ,@(if (featurep 'xemacs) '(t)
2625          '(:help "Mark this message as important"))]
2626     ["Flag As Unimportant" message-insert-importance-low
2627      ,@(if (featurep 'xemacs) '(t)
2628          '(:help "Mark this message as unimportant"))]
2629     ["Request Receipt"
2630      message-insert-disposition-notification-to
2631      ,@(if (featurep 'xemacs) '(t)
2632          '(:help "Request a receipt notification"))]
2633     "----"
2634     ;; (typical) news stuff
2635     ["Summary" message-goto-summary t]
2636     ["Keywords" message-goto-keywords t]
2637     ["Newsgroups" message-goto-newsgroups t]
2638     ["Fetch Newsgroups" message-insert-newsgroups t]
2639     ["Followup-To" message-goto-followup-to t]
2640     ;; ["Followup-To (with note in body)" message-cross-post-followup-to t]
2641     ["Crosspost / Followup-To..." message-cross-post-followup-to t]
2642     ["Distribution" message-goto-distribution t]
2643     ["X-No-Archive:" message-add-archive-header t ]
2644     "----"
2645     ;; (typical) mailing-lists stuff
2646     ["Fetch To" message-insert-to
2647      ,@(if (featurep 'xemacs) '(t)
2648          '(:help "Insert a To header that points to the author."))]
2649     ["Fetch To and Cc" message-insert-wide-reply
2650      ,@(if (featurep 'xemacs) '(t)
2651          '(:help
2652            "Insert To and Cc headers as if you were doing a wide reply."))]
2653     "----"
2654     ["Send to list only" message-to-list-only t]
2655     ["Mail-Followup-To" message-goto-mail-followup-to t]
2656     ["Mail-Reply-To" message-goto-mail-reply-to t]
2657     ["Mail-Copies-To" message-goto-mail-copies-to t]
2658     ["Unsubscribed list post" message-generate-unsubscribed-mail-followup-to
2659      ,@(if (featurep 'xemacs) '(t)
2660          '(:help "Insert a reasonable `Mail-Followup-To:' header."))]
2661     ["Reduce To: to Cc:" message-reduce-to-to-cc t]
2662     "----"
2663     ["Sort Headers" message-sort-headers t]
2664     ["Encode non-ASCII domain names" message-idna-to-ascii-rhs t]
2665     ["Goto Body" message-goto-body t]
2666     ["Goto Signature" message-goto-signature t]))
2667
2668 (defvar message-tool-bar-map nil)
2669
2670 (eval-when-compile
2671   (defvar facemenu-add-face-function)
2672   (defvar facemenu-remove-face-function))
2673
2674 ;;; Forbidden properties
2675 ;;
2676 ;; We use `after-change-functions' to keep special text properties
2677 ;; that interfer with the normal function of message mode out of the
2678 ;; buffer.
2679
2680 (defcustom message-strip-special-text-properties t
2681   "Strip special properties from the message buffer.
2682
2683 Emacs has a number of special text properties which can break message
2684 composing in various ways.  If this option is set, message will strip
2685 these properties from the message composition buffer.  However, some
2686 packages requires these properties to be present in order to work.
2687 If you use one of these packages, turn this option off, and hope the
2688 message composition doesn't break too bad."
2689   :version "22.1"
2690   :group 'message-various
2691   :link '(custom-manual "(message)Various Message Variables")
2692   :type 'boolean)
2693
2694 (defconst message-forbidden-properties
2695   ;; No reason this should be clutter up customize.  We make it a
2696   ;; property list (rather than a list of property symbols), to be
2697   ;; directly useful for `remove-text-properties'.
2698   '(field nil read-only nil invisible nil intangible nil
2699           mouse-face nil modification-hooks nil insert-in-front-hooks nil
2700           insert-behind-hooks nil point-entered nil point-left nil)
2701   ;; Other special properties:
2702   ;; category, face, display: probably doesn't do any harm.
2703   ;; fontified: is used by font-lock.
2704   ;; syntax-table, local-map: I dunno.
2705   ;; We need to add XEmacs names to the list.
2706   "Property list of with properties forbidden in message buffers.
2707 The values of the properties are ignored, only the property names are used.")
2708
2709 (defun message-tamago-not-in-use-p (pos)
2710   "Return t when tamago version 4 is not in use at the cursor position.
2711 Tamago version 4 is a popular input method for writing Japanese text.
2712 It uses the properties `intangible', `invisible', `modification-hooks'
2713 and `read-only' when translating ascii or kana text to kanji text.
2714 These properties are essential to work, so we should never strip them."
2715   (not (and (boundp 'egg-modefull-mode)
2716             (symbol-value 'egg-modefull-mode)
2717             (or (memq (get-text-property pos 'intangible)
2718                       '(its-part-1 its-part-2))
2719                 (get-text-property pos 'egg-end)
2720                 (get-text-property pos 'egg-lang)
2721                 (get-text-property pos 'egg-start)))))
2722
2723 (defun message-strip-forbidden-properties (begin end &optional old-length)
2724   "Strip forbidden properties between BEGIN and END, ignoring the third arg.
2725 This function is intended to be called from `after-change-functions'.
2726 See also `message-forbidden-properties'."
2727   (when (and message-strip-special-text-properties
2728              (message-tamago-not-in-use-p begin)
2729              ;; Check whether the invisible MIME part is not inserted.
2730              (not (text-property-any begin end 'mime-edit-invisible t)))
2731     (let ((buffer-read-only nil)
2732           (inhibit-read-only t))
2733       (remove-text-properties begin end message-forbidden-properties))))
2734
2735 ;;;###autoload
2736 (define-derived-mode message-mode text-mode "Message"
2737   "Major mode for editing mail and news to be sent.
2738 Like Text Mode but with these additional commands:\\<message-mode-map>
2739 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
2740 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
2741 C-c C-f  move to a header field (and create it if there isn't):
2742          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
2743          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
2744          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
2745          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
2746          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
2747          C-c C-f C-o  move to From (\"Originator\")
2748          C-c C-f C-f  move to Followup-To
2749          C-c C-f C-m  move to Mail-Followup-To
2750          C-c C-f c    move to Mail-Copies-To
2751          C-c C-f C-i  cycle through Importance values
2752          C-c C-f s    change subject and append \"(was: <Old Subject>)\"
2753          C-c C-f x    crossposting with FollowUp-To header and note in body
2754          C-c C-f t    replace To: header with contents of Cc: or Bcc:
2755          C-c C-f a    Insert X-No-Archive: header and a note in the body
2756 C-c C-t  `message-insert-to' (add a To header to a news followup)
2757 C-c C-l  `message-to-list-only' (removes all but list address in to/cc)
2758 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
2759 C-c C-b  `message-goto-body' (move to beginning of message text).
2760 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
2761 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
2762 C-c C-y  `message-yank-original' (insert current message, if any).
2763 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
2764 C-c C-e  `message-elide-region' (elide the text between point and mark).
2765 C-c C-v  `message-delete-not-region' (remove the text outside the region).
2766 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
2767 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
2768 C-c C-u  `message-insert-or-toggle-importance'  (insert or cycle importance).
2769 C-c M-n  `message-insert-disposition-notification-to'  (request receipt).
2770 C-c M-m  `message-mark-inserted-region' (mark region with enclosing tags).
2771 C-c M-f  `message-mark-insert-file' (insert file marked with enclosing tags).
2772 M-RET    `message-newline-and-reformat' (break the line and reformat)."
2773   (setq local-abbrev-table text-mode-abbrev-table)
2774   (set (make-local-variable 'message-reply-buffer) nil)
2775   (set (make-local-variable 'message-inserted-headers) nil)
2776   (set (make-local-variable 'message-send-actions) nil)
2777   (set (make-local-variable 'message-exit-actions) nil)
2778   (set (make-local-variable 'message-kill-actions) nil)
2779   (set (make-local-variable 'message-postpone-actions) nil)
2780   (set (make-local-variable 'message-draft-article) nil)
2781   (setq buffer-offer-save t)
2782   (set (make-local-variable 'facemenu-add-face-function)
2783        (lambda (face end)
2784          (let ((face-fun (cdr (assq face message-face-alist))))
2785            (if face-fun
2786                (funcall face-fun (point) end)
2787              (error "Face %s not configured for %s mode" face mode-name)))
2788          ""))
2789   (set (make-local-variable 'facemenu-remove-face-function) t)
2790   (set (make-local-variable 'message-reply-headers) nil)
2791   (make-local-variable 'message-user-agent)
2792   (make-local-variable 'message-post-method)
2793   (set (make-local-variable 'message-sent-message-via) nil)
2794   (set (make-local-variable 'message-checksum) nil)
2795   (make-local-variable 'message-parameter-alist)
2796   (setq message-parameter-alist
2797         (copy-sequence message-startup-parameter-alist))
2798   (message-setup-fill-variables)
2799   ;; Allow using comment commands to add/remove quoting.
2800   ;; (set (make-local-variable 'comment-start) message-yank-prefix)
2801   (when message-yank-prefix
2802     (set (make-local-variable 'comment-start) message-yank-prefix)
2803     (set (make-local-variable 'comment-start-skip)
2804          (concat "^" (regexp-quote message-yank-prefix) "[ \t]*")))
2805   (if (featurep 'xemacs)
2806       (message-setup-toolbar)
2807     (set (make-local-variable 'font-lock-defaults)
2808          '(message-font-lock-keywords t))
2809     (if (boundp 'tool-bar-map)
2810         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
2811   (easy-menu-add message-mode-menu message-mode-map)
2812   (easy-menu-add message-mode-field-menu message-mode-map)
2813   (gnus-make-local-hook 'after-change-functions)
2814   ;; Mmmm... Forbidden properties...
2815   (add-hook 'after-change-functions 'message-strip-forbidden-properties
2816             nil 'local)
2817   ;; Allow mail alias things.
2818   (when (eq message-mail-alias-type 'abbrev)
2819     (if (fboundp 'mail-abbrevs-setup)
2820         (mail-abbrevs-setup)
2821       (if (fboundp 'mail-aliases-setup) ; warning avoidance
2822           (mail-aliases-setup))))
2823   (unless buffer-file-name
2824     (message-set-auto-save-file-name))
2825   (set (make-local-variable 'indent-tabs-mode) nil)) ;No tabs for indentation.
2826
2827 (defun message-setup-fill-variables ()
2828   "Setup message fill variables."
2829   (set (make-local-variable 'fill-paragraph-function)
2830        'message-fill-paragraph)
2831   (make-local-variable 'paragraph-separate)
2832   (make-local-variable 'paragraph-start)
2833   (make-local-variable 'adaptive-fill-regexp)
2834   (unless (boundp 'adaptive-fill-first-line-regexp)
2835     (setq adaptive-fill-first-line-regexp nil))
2836   (make-local-variable 'adaptive-fill-first-line-regexp)
2837   (let ((quote-prefix-regexp
2838          ;; User should change message-cite-prefix-regexp if
2839          ;; message-yank-prefix is set to an abnormal value.
2840          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
2841     (setq paragraph-start
2842           (concat
2843            (regexp-quote mail-header-separator) "$\\|"
2844            "[ \t]*$\\|"                 ; blank lines
2845            "-- $\\|"                    ; signature delimiter
2846            "---+$\\|"                   ; delimiters for forwarded messages
2847            page-delimiter "$\\|"        ; spoiler warnings
2848            ".*wrote:$\\|"               ; attribution lines
2849            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
2850            mime-edit-tag-regexp))       ; MIME-Edit tags
2851     (setq paragraph-separate paragraph-start)
2852     (setq adaptive-fill-regexp
2853           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
2854     (setq adaptive-fill-first-line-regexp
2855           (concat quote-prefix-regexp "\\|"
2856                   adaptive-fill-first-line-regexp)))
2857   (make-local-variable 'auto-fill-inhibit-regexp)
2858   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
2859   (setq auto-fill-inhibit-regexp nil)
2860   (make-local-variable 'normal-auto-fill-function)
2861   (setq normal-auto-fill-function 'message-do-auto-fill)
2862   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
2863   ;; In that case, ensure that it uses the right function.  The real
2864   ;; solution would be not to use `define-derived-mode', and run
2865   ;; `text-mode-hook' ourself at the end of the mode.
2866   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
2867   (when auto-fill-function
2868     (setq auto-fill-function normal-auto-fill-function)))
2869
2870 \f
2871
2872 ;;;
2873 ;;; Message mode commands
2874 ;;;
2875
2876 ;;; Movement commands
2877
2878 (defun message-goto-to ()
2879   "Move point to the To header."
2880   (interactive)
2881   (message-position-on-field "To"))
2882
2883 (defun message-goto-from ()
2884   "Move point to the From header."
2885   (interactive)
2886   (message-position-on-field "From"))
2887
2888 (defun message-goto-subject ()
2889   "Move point to the Subject header."
2890   (interactive)
2891   (message-position-on-field "Subject"))
2892
2893 (defun message-goto-cc ()
2894   "Move point to the Cc header."
2895   (interactive)
2896   (message-position-on-field "Cc" "To"))
2897
2898 (defun message-goto-bcc ()
2899   "Move point to the Bcc  header."
2900   (interactive)
2901   (message-position-on-field "Bcc" "Cc" "To"))
2902
2903 (defun message-goto-fcc ()
2904   "Move point to the Fcc header."
2905   (interactive)
2906   (message-position-on-field "Fcc" "To" "Newsgroups"))
2907
2908 (defun message-goto-reply-to ()
2909   "Move point to the Reply-To header."
2910   (interactive)
2911   (message-position-on-field "Reply-To" "Subject"))
2912
2913 (defun message-goto-mail-reply-to ()
2914   "Move point to the Mail-Reply-To header."
2915   (interactive)
2916   (message-position-on-field "Mail-Reply-To" "Subject"))
2917
2918 (defun message-goto-mail-copies-to ()
2919   "Move point to the Mail-Copies-To header.  If the header is newly created,
2920 a string \"never\" is inserted in default."
2921   (interactive)
2922   (unless (message-position-on-field "Mail-Copies-To" "Subject")
2923     (insert "never")
2924     (backward-char 5)))
2925
2926 (defun message-goto-newsgroups ()
2927   "Move point to the Newsgroups header."
2928   (interactive)
2929   (message-position-on-field "Newsgroups"))
2930
2931 (defun message-goto-distribution ()
2932   "Move point to the Distribution header."
2933   (interactive)
2934   (message-position-on-field "Distribution"))
2935
2936 (defun message-goto-followup-to ()
2937   "Move point to the Followup-To header."
2938   (interactive)
2939   (message-position-on-field "Followup-To" "Newsgroups"))
2940
2941 (defun message-goto-mail-followup-to ()
2942   "Move point to the Mail-Followup-To header.
2943 If the header is newly created and To field contains only one address,
2944 the address is inserted by default."
2945   (interactive)
2946   (unless (message-position-on-field "Mail-Followup-To" "To")
2947     (let ((start (point))
2948           addresses)
2949       (save-restriction
2950         (message-narrow-to-headers)
2951         (setq addresses (split-string (mail-strip-quoted-names
2952                                        (or (std11-fetch-field "to") ""))
2953                                       "[ \f\t\n\r\v,]+"))
2954         (when (eq 1 (length addresses))
2955           (goto-char start)
2956           (insert (car addresses))
2957           (goto-char start))))))
2958
2959 (defun message-goto-keywords ()
2960   "Move point to the Keywords header."
2961   (interactive)
2962   (message-position-on-field "Keywords" "Subject"))
2963
2964 (defun message-goto-summary ()
2965   "Move point to the Summary header."
2966   (interactive)
2967   (message-position-on-field "Summary" "Subject"))
2968
2969 (defun message-goto-body (&optional interactivep)
2970   "Move point to the beginning of the message body."
2971   (interactive (list t))
2972   (when (and interactivep
2973              (looking-at "[ \t]*\n"))
2974     (expand-abbrev))
2975   (goto-char (point-min))
2976   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
2977       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
2978
2979 (defun message-goto-eoh ()
2980   "Move point to the end of the headers."
2981   (interactive)
2982   (message-goto-body)
2983   (forward-line -1))
2984
2985 (defun message-goto-signature ()
2986   "Move point to the beginning of the message signature.
2987 If there is no signature in the article, go to the end and
2988 return nil."
2989   (interactive)
2990   (goto-char (point-min))
2991   (if (re-search-forward message-signature-separator nil t)
2992       (forward-line 1)
2993     (goto-char (point-max))
2994     nil))
2995
2996 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
2997   "Insert a reasonable MFT header in a post to an unsubscribed list.
2998 When making original posts to a mailing list you are not subscribed to,
2999 you have to type in a MFT header by hand.  The contents, usually, are
3000 the addresses of the list and your own address.  This function inserts
3001 such a header automatically.  It fetches the contents of the To: header
3002 in the current mail buffer, and appends the current `user-mail-address'.
3003
3004 If the optional argument INCLUDE-CC is non-nil, the addresses in the
3005 Cc: header are also put into the MFT."
3006
3007   (interactive "P")
3008   (let* (cc tos)
3009     (save-restriction
3010       (message-narrow-to-headers)
3011       (message-remove-header "Mail-Followup-To")
3012       (setq cc (and include-cc (message-fetch-field "Cc")))
3013       (setq tos (if cc
3014                     (concat (message-fetch-field "To") "," cc)
3015                   (message-fetch-field "To"))))
3016     (message-goto-mail-followup-to)
3017     (insert (concat tos ", " user-mail-address))))
3018
3019 \f
3020
3021 (defun message-insert-to (&optional force)
3022   "Insert a To header that points to the author of the article being replied to.
3023 If the original author requested not to be sent mail, don't insert unless the
3024 prefix FORCE is given."
3025   (interactive "P")
3026   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
3027          (dont (and mct (or (equal (downcase mct) "never")
3028                             (equal (downcase mct) "nobody"))))
3029          (to (or (message-fetch-reply-field "mail-reply-to")
3030                  (message-fetch-reply-field "reply-to")
3031                  (message-fetch-reply-field "from"))))
3032     (when (and dont to)
3033       (message
3034        (if force
3035            "Ignoring the user request not to have copies sent via mail"
3036          "Complying with the user request not to have copies sent via mail")))
3037     (when (and force (not to))
3038       (error "No mail address in the article"))
3039     (when (and to (or force (not dont)))
3040       (message-carefully-insert-headers (list (cons 'To to))))))
3041
3042 (defun message-insert-wide-reply ()
3043   "Insert To and Cc headers as if you were doing a wide reply."
3044   (interactive)
3045   (let ((headers (message-with-reply-buffer
3046                    (message-get-reply-headers t))))
3047     (message-carefully-insert-headers headers)))
3048
3049 (defcustom message-header-synonyms
3050   '((To Cc Bcc))
3051   "List of lists of header synonyms.
3052 E.g., if this list contains a member list with elements `Cc' and `To',
3053 then `message-carefully-insert-headers' will not insert a `To' header
3054 when the message is already `Cc'ed to the recipient."
3055   :version "22.1"
3056   :group 'message-headers
3057   :link '(custom-manual "(message)Message Headers")
3058   :type '(repeat sexp))
3059
3060 (defun message-carefully-insert-headers (headers)
3061   "Insert the HEADERS, an alist, into the message buffer.
3062 Does not insert the headers when they are already present there
3063 or in the synonym headers, defined by `message-header-synonyms'."
3064   ;; FIXME: Should compare only the address and not the full name.  Comparison
3065   ;; should be done case-folded (and with `string=' rather than
3066   ;; `string-match').
3067   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
3068   (dolist (header headers)
3069     (let* ((header-name (symbol-name (car header)))
3070            (new-header (cdr header))
3071            (synonyms (loop for synonym in message-header-synonyms
3072                            when (memq (car header) synonym) return synonym))
3073            (old-header
3074             (loop for synonym in synonyms
3075                   for old-header = (mail-fetch-field (symbol-name synonym))
3076                   when (and old-header (string-match new-header old-header))
3077                   return synonym)))
3078       (if old-header
3079           (message "already have `%s' in `%s'" new-header old-header)
3080         (when (and (message-position-on-field header-name)
3081                    (setq old-header (mail-fetch-field header-name))
3082                    (not (string-match "\\` *\\'" old-header)))
3083           (insert ", "))
3084         (insert new-header)))))
3085
3086 (defun message-widen-reply ()
3087   "Widen the reply to include maximum recipients."
3088   (interactive)
3089   (let ((follow-to
3090          (and message-reply-buffer
3091               (buffer-name message-reply-buffer)
3092               (save-excursion
3093                 (set-buffer message-reply-buffer)
3094                 (message-get-reply-headers t)))))
3095     (save-excursion
3096       (save-restriction
3097         (message-narrow-to-headers)
3098         (dolist (elem follow-to)
3099           (message-remove-header (symbol-name (car elem)))
3100           (goto-char (point-min))
3101           (insert (symbol-name (car elem)) ": "
3102                   (cdr elem) "\n"))))))
3103
3104 (defun message-insert-newsgroups ()
3105   "Insert the Newsgroups header from the article being replied to."
3106   (interactive)
3107   (when (and (message-position-on-field "Newsgroups")
3108              (mail-fetch-field "newsgroups")
3109              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
3110     (insert ","))
3111   (insert (or (message-fetch-reply-field "newsgroups") "")))
3112
3113 \f
3114
3115 ;;; Various commands
3116
3117 (defun message-delete-not-region (beg end)
3118   "Delete everything in the body of the current message outside of the region."
3119   (interactive "r")
3120   (let (citeprefix)
3121     (save-excursion
3122       (goto-char beg)
3123       ;; snarf citation prefix, if appropriate
3124       (unless (eq (point) (progn (beginning-of-line) (point)))
3125         (when (looking-at message-cite-prefix-regexp)
3126           (setq citeprefix (match-string 0))))
3127       (goto-char end)
3128       (delete-region (point) (if (not (message-goto-signature))
3129                                  (point)
3130                                (forward-line -2)
3131                                (point)))
3132       (insert "\n")
3133       (goto-char beg)
3134       (delete-region beg (progn (message-goto-body)
3135                                 (forward-line 2)
3136                                 (point)))
3137       (when citeprefix
3138         (insert citeprefix))))
3139   (when (message-goto-signature)
3140     (forward-line -2)))
3141
3142 (defun message-kill-to-signature (&optional arg)
3143   "Kill all text up to the signature.
3144 If a numberic argument or prefix arg is given, leave that number
3145 of lines before the signature intact."
3146   (interactive "p")
3147   (save-excursion
3148     (save-restriction
3149       (let ((point (point)))
3150         (narrow-to-region point (point-max))
3151         (message-goto-signature)
3152         (unless (eobp)
3153           (if (and arg (numberp arg))
3154               (forward-line (- -1 arg))
3155             (end-of-line -1)))
3156         (unless (= point (point))
3157           (kill-region point (point))
3158           (unless (bolp)
3159             (insert "\n")))))))
3160
3161 (defun message-newline-and-reformat (&optional arg not-break)
3162   "Insert four newlines, and then reformat if inside quoted text.
3163 Prefix arg means justify as well."
3164   (interactive (list (if current-prefix-arg 'full)))
3165   (let (quoted point beg end leading-space bolp fill-paragraph-function)
3166     (setq point (point))
3167     (beginning-of-line)
3168     (setq beg (point))
3169     (setq bolp (= beg point))
3170     ;; Find first line of the paragraph.
3171     (if not-break
3172         (while (and (not (eobp))
3173                     (not (looking-at message-cite-prefix-regexp))
3174                     (looking-at paragraph-start))
3175           (forward-line 1)))
3176     ;; Find the prefix
3177     (when (looking-at message-cite-prefix-regexp)
3178       (setq quoted (match-string 0))
3179       (goto-char (match-end 0))
3180       (looking-at "[ \t]*")
3181       (setq leading-space (match-string 0)))
3182     (if (and quoted
3183              (not not-break)
3184              (not bolp)
3185              (< (- point beg) (length quoted)))
3186         ;; break inside the cite prefix.
3187         (setq quoted nil
3188               end nil))
3189     (if quoted
3190         (progn
3191           (forward-line 1)
3192           (while (and (not (eobp))
3193                       (not (looking-at paragraph-separate))
3194                       (looking-at message-cite-prefix-regexp)
3195                       (equal quoted (match-string 0)))
3196             (goto-char (match-end 0))
3197             (looking-at "[ \t]*")
3198             (if (> (length leading-space) (length (match-string 0)))
3199                 (setq leading-space (match-string 0)))
3200             (forward-line 1))
3201           (setq end (point))
3202           (goto-char beg)
3203           (while (and (if (bobp) nil (forward-line -1) t)
3204                       (not (looking-at paragraph-start))
3205                       (looking-at message-cite-prefix-regexp)
3206                       (equal quoted (match-string 0)))
3207             (setq beg (point))
3208             (goto-char (match-end 0))
3209             (looking-at "[ \t]*")
3210             (if (> (length leading-space) (length (match-string 0)))
3211                 (setq leading-space (match-string 0)))))
3212       (while (and (not (eobp))
3213                   (not (looking-at paragraph-separate))
3214                   (not (looking-at message-cite-prefix-regexp)))
3215         (forward-line 1))
3216       (setq end (point))
3217       (goto-char beg)
3218       (while (and (if (bobp) nil (forward-line -1) t)
3219                   (not (looking-at paragraph-start))
3220                   (not (looking-at message-cite-prefix-regexp)))
3221         (setq beg (point))))
3222     (goto-char point)
3223     (save-restriction
3224       (narrow-to-region beg end)
3225       (if not-break
3226           (setq point nil)
3227         (if bolp
3228             (newline)
3229           (newline)
3230           (newline))
3231         (setq point (point))
3232         ;; (newline 2) doesn't mark both newline's as hard, so call
3233         ;; newline twice. -jas
3234         (newline)
3235         (newline)
3236         (delete-region (point) (re-search-forward "[ \t]*"))
3237         (when (and quoted (not bolp))
3238           (insert quoted leading-space)))
3239       (undo-boundary)
3240       (if quoted
3241           (let* ((adaptive-fill-regexp
3242                   (regexp-quote (concat quoted leading-space)))
3243                  (adaptive-fill-first-line-regexp
3244                   adaptive-fill-regexp ))
3245             (fill-paragraph arg))
3246         (fill-paragraph arg))
3247       (if point (goto-char point)))))
3248
3249 (defun message-fill-paragraph (&optional arg)
3250   "Like `fill-paragraph'."
3251   (interactive (list (if current-prefix-arg 'full)))
3252   (if (if (boundp 'filladapt-mode) filladapt-mode)
3253       nil
3254     (if (message-point-in-header-p)
3255         (message-fill-field)
3256       (message-newline-and-reformat arg t))
3257     t))
3258
3259 ;; Is it better to use `mail-header-end'?
3260 (defun message-point-in-header-p ()
3261   "Return t if point is in the header."
3262   (save-excursion
3263     (let ((p (point)))
3264       (goto-char (point-min))
3265       (not (re-search-forward
3266             (concat "^" (regexp-quote mail-header-separator) "\n")
3267             p t)))))
3268
3269 (defun message-do-auto-fill ()
3270   "Like `do-auto-fill', but don't fill in message header."
3271   (unless (message-point-in-header-p)
3272     (do-auto-fill)))
3273
3274 (defun message-insert-signature (&optional force)
3275   "Insert a signature.  See documentation for variable `message-signature'."
3276   (interactive (list 0))
3277   (let* ((signature
3278           (cond
3279            ((and (null message-signature)
3280                  (eq force 0))
3281             (save-excursion
3282               (goto-char (point-max))
3283               (not (re-search-backward message-signature-separator nil t))))
3284            ((and (null message-signature)
3285                  force)
3286             t)
3287            ((functionp message-signature)
3288             (funcall message-signature))
3289            ((listp message-signature)
3290             (eval message-signature))
3291            (t message-signature)))
3292          (signature
3293           (cond ((stringp signature)
3294                  signature)
3295                 ((and (eq t signature)
3296                       message-signature-file
3297                       (file-exists-p message-signature-file))
3298                  signature))))
3299     (when signature
3300       (goto-char (point-max))
3301       ;; Insert the signature.
3302       (unless (bolp)
3303         (insert "\n"))
3304       (when message-signature-insert-empty-line
3305         (insert "\n"))
3306       (insert "\n" message-signature-separator-for-insertion)
3307       (unless (bolp)
3308         (insert "\n"))
3309       (if (eq signature t)
3310           (insert-file-contents message-signature-file)
3311         (insert signature))
3312       (goto-char (point-max))
3313       (or (bolp) (insert "\n")))))
3314
3315 (defun message-insert-importance-high ()
3316   "Insert header to mark message as important."
3317   (interactive)
3318   (save-excursion
3319     (save-restriction
3320       (message-narrow-to-headers)
3321       (message-remove-header "Importance"))
3322     (message-goto-eoh)
3323     (insert "Importance: high\n")))
3324
3325 (defun message-insert-importance-low ()
3326   "Insert header to mark message as unimportant."
3327   (interactive)
3328   (save-excursion
3329     (save-restriction
3330       (message-narrow-to-headers)
3331       (message-remove-header "Importance"))
3332     (message-goto-eoh)
3333     (insert "Importance: low\n")))
3334
3335 (defun message-insert-or-toggle-importance ()
3336   "Insert a \"Importance: high\" header, or cycle through the header values.
3337 The three allowed values according to RFC 1327 are `high', `normal'
3338 and `low'."
3339   (interactive)
3340   (save-excursion
3341     (let ((valid '("high" "normal" "low"))
3342           (new "high")
3343           cur)
3344       (save-restriction
3345         (message-narrow-to-headers)
3346         (when (setq cur (message-fetch-field "Importance"))
3347           (message-remove-header "Importance")
3348           (setq new (cond ((string= cur "high")
3349                            "low")
3350                           ((string= cur "low")
3351                            "normal")
3352                           (t
3353                            "high")))))
3354       (message-goto-eoh)
3355       (insert (format "Importance: %s\n" new)))))
3356
3357 (defun message-insert-disposition-notification-to ()
3358   "Request a disposition notification (return receipt) to this message.
3359 Note that this should not be used in newsgroups."
3360   (interactive)
3361   (save-excursion
3362     (save-restriction
3363       (message-narrow-to-headers)
3364       (message-remove-header "Disposition-Notification-To"))
3365     (message-goto-eoh)
3366     (insert (format "Disposition-Notification-To: %s\n"
3367                     (or (message-field-value "Reply-to")
3368                         (message-field-value "From")
3369                         (message-make-from))))))
3370
3371 (defun message-elide-region (b e)
3372   "Elide the text in the region.
3373 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3374 text was killed."
3375   (interactive "r")
3376   (kill-region b e)
3377   (insert message-elide-ellipsis))
3378
3379 (defvar message-caesar-translation-table nil)
3380
3381 (defun message-caesar-region (b e &optional n)
3382   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3383   (interactive
3384    (list
3385     (min (point) (or (mark t) (point)))
3386     (max (point) (or (mark t) (point)))
3387     (when current-prefix-arg
3388       (prefix-numeric-value current-prefix-arg))))
3389
3390   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3391   (unless (or (zerop n)                 ; no action needed for a rot of 0
3392               (= b e))                  ; no region to rotate
3393     ;; We build the table, if necessary.
3394     (when (or (not message-caesar-translation-table)
3395               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3396       (setq message-caesar-translation-table
3397             (message-make-caesar-translation-table n)))
3398     (translate-region b e message-caesar-translation-table)))
3399
3400 (defun message-make-caesar-translation-table (n)
3401   "Create a rot table with offset N."
3402   (let ((i -1)
3403         (table (make-string 256 0)))
3404     (while (< (incf i) 256)
3405       (aset table i i))
3406     (concat
3407      (substring table 0 ?A)
3408      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3409      (substring table ?A (+ ?A n))
3410      (substring table (+ ?A 26) ?a)
3411      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3412      (substring table ?a (+ ?a n))
3413      (substring table (+ ?a 26) 255))))
3414
3415 (defun message-caesar-buffer-body (&optional rotnum)
3416   "Caesar rotate all letters in the current buffer by 13 places.
3417 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3418 With prefix arg, specifies the number of places to rotate each letter forward.
3419 Mail and USENET news headers are not rotated."
3420   (interactive (if current-prefix-arg
3421                    (list (prefix-numeric-value current-prefix-arg))
3422                  (list nil)))
3423   (save-excursion
3424     (save-restriction
3425       (when (message-goto-body)
3426         (narrow-to-region (point) (point-max)))
3427       (message-caesar-region (point-min) (point-max) rotnum))))
3428
3429 (defun message-pipe-buffer-body (program)
3430   "Pipe the message body in the current buffer through PROGRAM."
3431   (save-excursion
3432     (save-restriction
3433       (when (message-goto-body)
3434         (narrow-to-region (point) (point-max)))
3435       (shell-command-on-region
3436        (point-min) (point-max) program nil t))))
3437
3438 (defun message-rename-buffer (&optional enter-string)
3439   "Rename the *message* buffer to \"*message* RECIPIENT\".
3440 If the function is run with a prefix, it will ask for a new buffer
3441 name, rather than giving an automatic name."
3442   (interactive "Pbuffer name: ")
3443   (save-excursion
3444     (save-restriction
3445       (goto-char (point-min))
3446       (narrow-to-region (point)
3447                         (search-forward mail-header-separator nil 'end))
3448       (let* ((mail-to (or
3449                        (if (message-news-p) (message-fetch-field "Newsgroups")
3450                          (message-fetch-field "To"))
3451                        ""))
3452              (mail-trimmed-to
3453               (if (string-match "," mail-to)
3454                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3455                 mail-to))
3456              (name-default (concat "*message* " mail-trimmed-to))
3457              (name (if enter-string
3458                        (read-string "New buffer name: " name-default)
3459                      name-default)))
3460         (rename-buffer name t)))))
3461
3462 (defun message-fill-yanked-message (&optional justifyp)
3463   "Fill the paragraphs of a message yanked into this one.
3464 Numeric argument means justify as well."
3465   (interactive "P")
3466   (save-excursion
3467     (goto-char (point-min))
3468     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3469     (let ((fill-prefix message-yank-prefix))
3470       (fill-individual-paragraphs (point) (point-max) justifyp))))
3471
3472 (defun message-indent-citation ()
3473   "Modify text just inserted from a message to be cited.
3474 The inserted text should be the region.
3475 When this function returns, the region is again around the modified text.
3476
3477 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3478 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3479   (let ((start (point)))
3480     ;; Remove unwanted headers.
3481     (when message-ignored-cited-headers
3482       (let (all-removed)
3483         (save-restriction
3484           (narrow-to-region
3485            (goto-char start)
3486            (if (search-forward "\n\n" nil t)
3487                (1- (point))
3488              (point)))
3489           (message-remove-header message-ignored-cited-headers t)
3490           (when (= (point-min) (point-max))
3491             (setq all-removed t))
3492           (goto-char (point-max)))
3493         (if all-removed
3494             (goto-char start)
3495           (forward-line 1))))
3496     ;; Delete blank lines at the start of the buffer.
3497     (while (and (point-min)
3498                 (eolp)
3499                 (not (eobp)))
3500       (message-delete-line))
3501     ;; Delete blank lines at the end of the buffer.
3502     (goto-char (point-max))
3503     (unless (bolp)
3504       (insert "\n"))
3505     (while (and (zerop (forward-line -1))
3506                 (looking-at "$"))
3507       (message-delete-line))
3508     ;; Do the indentation.
3509     (if (null message-yank-prefix)
3510         (indent-rigidly start (mark t) message-indentation-spaces)
3511       (save-excursion
3512         (goto-char start)
3513         (while (< (point) (mark t))
3514           (cond ((looking-at ">")
3515                  (insert message-yank-cited-prefix))
3516                 ((looking-at "^$")
3517                  (insert message-yank-empty-prefix))
3518                 (t
3519                  (insert message-yank-prefix)))
3520           (forward-line 1))))
3521     (goto-char start)))
3522
3523 (defun message-list-references (refs-list &rest refs-strs)
3524   "Add `Message-ID's which appear in REFS-STRS but not in REFS-LIST,
3525 to REFS-LIST."
3526   (let (refs ref id saved-id)
3527     (when (and refs-list
3528                (integerp message-list-references-add-position))
3529       (let ((pos message-list-references-add-position))
3530         (while (and refs-list
3531                     (> pos 0))
3532           (push (pop refs-list) saved-id)
3533           (setq pos (1- pos)))))
3534     (while refs-strs
3535       (when (setq refs (pop refs-strs))
3536         (setq refs (std11-parse-msg-ids (std11-lexical-analyze refs)))
3537         (while refs
3538           (when (eq (car (setq ref (pop refs))) 'msg-id)
3539             (setq id (concat "<" (mapconcat 'cdr (cdr ref) "") ">"))
3540             (or (member id refs-list)
3541                 (member id saved-id)
3542                 (push id refs-list))))))
3543     (while saved-id
3544       (push (pop saved-id) refs-list))
3545     refs-list))
3546
3547 (defun message-yank-original (&optional arg)
3548   "Insert the message being replied to, if any.
3549 Puts point before the text and mark after.
3550 Normally indents each nonblank line ARG spaces (default 3).  However,
3551 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3552
3553 This function uses `message-cite-function' to do the actual citing.
3554
3555 Just \\[universal-argument] as argument means don't indent, insert no
3556 prefix, and don't delete any headers.
3557
3558 In addition, if `message-yank-add-new-references' is non-nil and this
3559 command is called interactively, new IDs from the yanked article will
3560 be added to the \"References\" field."
3561   (interactive "P")
3562   (let ((modified (buffer-modified-p)))
3563     (when (let ((buffer (message-eval-parameter message-reply-buffer)))
3564             (and buffer
3565                  message-cite-function
3566                  (prog1
3567                      t
3568                    (delete-windows-on buffer t)
3569                    ; Set the mark at the end of the yanked message.
3570                    (push-mark (save-excursion
3571                                 (insert-buffer-substring buffer)
3572                                 (point))))))
3573       ;; Add new IDs to the References field.
3574       (when (and message-yank-add-new-references
3575                  (interactive-p))
3576         (let ((start (point))
3577               (end (mark t))
3578               refs newrefs)
3579           (save-excursion
3580             (save-restriction
3581               (widen)
3582               (setq refs (message-list-references
3583                           nil
3584                           (or (message-make-references)
3585                               (prog2
3586                                   (message-narrow-to-headers)
3587                                   (message-fetch-field "References")
3588                                 (widen)))))
3589               (narrow-to-region start end)
3590               (std11-narrow-to-header)
3591               (unless (equal (setq newrefs
3592                                    (message-list-references
3593                                     (copy-sequence refs)
3594                                     (unless (eq message-yank-add-new-references
3595                                                 'message-id-only)
3596                                       (or (message-fetch-field "References")
3597                                           (message-fetch-field "In-Reply-To")))
3598                                     (message-fetch-field "Message-ID")))
3599                              refs)
3600                 ;; If the References field has been changed, we make it
3601                 ;; visible in the header.
3602                 (when message-reply-headers
3603                   (mail-header-set-message-id message-reply-headers nil)
3604                   (mail-header-set-references message-reply-headers nil))
3605                 (widen)
3606                 (message-narrow-to-headers)
3607                 (if (let ((case-fold-search t))
3608                       (re-search-forward "^References:\\([\t ]+.+\n\\)+"
3609                                          nil t))
3610                     (replace-match "")
3611                   (goto-char (point-max)))
3612                 (mail-header-format
3613                  (list (or (assq 'References message-header-format-alist)
3614                            '(References . message-fill-references)))
3615                  (list (cons 'References
3616                              (mapconcat 'identity
3617                                         (nreverse newrefs) " ")))))))))
3618       (unless arg
3619         (if (and message-suspend-font-lock-when-citing
3620                  (boundp 'font-lock-mode)
3621                  (symbol-value 'font-lock-mode))
3622             (unwind-protect
3623                 (progn
3624                   (sit-for 0)
3625                   (font-lock-mode 0)
3626                   (funcall message-cite-function))
3627               (font-lock-mode 1))
3628           (funcall message-cite-function)))
3629       (message-exchange-point-and-mark)
3630       (unless (bolp)
3631         (insert ?\n))
3632       (unless modified
3633         (setq message-checksum (message-checksum))))))
3634
3635 (defun message-yank-buffer (buffer)
3636   "Insert BUFFER into the current buffer and quote it."
3637   (interactive "bYank buffer: ")
3638   (let ((message-reply-buffer (get-buffer buffer)))
3639     (save-window-excursion
3640       (message-yank-original))))
3641
3642 (defun message-buffers ()
3643   "Return a list of active message buffers."
3644   (let (buffers)
3645     (save-excursion
3646       (dolist (buffer (buffer-list t))
3647         (set-buffer buffer)
3648         (when (and (eq major-mode 'message-mode)
3649                    (null message-sent-message-via))
3650           (push (buffer-name buffer) buffers))))
3651     (nreverse buffers)))
3652
3653 (eval-when-compile (defvar mail-citation-hook)) ; Compiler directive
3654
3655 (defun message-cite-original-1 (strip-signature)
3656   "Cite an original message.
3657 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3658 original message.
3659
3660 This function uses `mail-citation-hook' if that is non-nil."
3661   (if (and (boundp 'mail-citation-hook)
3662            mail-citation-hook)
3663       (run-hooks 'mail-citation-hook)
3664     (let ((start (point))
3665           (end (mark t))
3666           (x-no-archive nil)
3667           (functions
3668            (when message-indent-citation-function
3669              (if (listp message-indent-citation-function)
3670                  message-indent-citation-function
3671                (list message-indent-citation-function))))
3672           (message-reply-headers (or message-reply-headers
3673                                      (make-mail-header))))
3674       (save-restriction
3675         (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3676                                       (1- (point))
3677                                     (point-max)))
3678         (mail-header-set-from message-reply-headers
3679                               (or (message-fetch-field "from")
3680                                   "unknown sender"))
3681         (setq x-no-archive (message-fetch-field "x-no-archive")))
3682       (goto-char start)
3683       (mapc 'funcall functions)
3684       (when strip-signature
3685         ;; Allow undoing.
3686         (undo-boundary)
3687         (goto-char end)
3688         (when (re-search-backward message-signature-separator start t)
3689           ;; Also peel off any blank lines before the signature.
3690           (forward-line -1)
3691           (while (looking-at "^[ \t]*$")
3692             (forward-line -1))
3693           (forward-line 1)
3694           (delete-region (point) end)
3695           (unless (search-backward "\n\n" start t)
3696             ;; Insert a blank line if it is peeled off.
3697             (insert "\n"))))
3698       (when message-citation-line-function
3699         (unless (bolp)
3700           (insert "\n"))
3701         (funcall message-citation-line-function))
3702       (when (and x-no-archive
3703                  (not message-cite-articles-with-x-no-archive)
3704                  (string-match "yes" x-no-archive))
3705         (undo-boundary)
3706         (delete-region (point) (mark t))
3707         (insert "> [Quoted text removed due to X-No-Archive]\n")
3708         (forward-line -1)))))
3709
3710 (defun message-cite-original ()
3711   "Cite function in the standard Message manner."
3712   (message-cite-original-1 nil))
3713
3714 (defun message-cite-original-without-signature ()
3715   "Cite function in the standard Message manner.
3716 This function strips off the signature from the original message."
3717   (message-cite-original-1 t))
3718
3719 (defun message-insert-citation-line ()
3720   "Insert a simple citation line."
3721   (when message-reply-headers
3722     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
3723
3724 (defun message-position-on-field (header &rest afters)
3725   (let ((case-fold-search t))
3726     (save-restriction
3727       (narrow-to-region
3728        (goto-char (point-min))
3729        (progn
3730          (re-search-forward
3731           (concat "^" (regexp-quote mail-header-separator) "$"))
3732          (match-beginning 0)))
3733       (goto-char (point-min))
3734       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3735           (progn
3736             (re-search-forward "^[^ \t]" nil 'move)
3737             (beginning-of-line)
3738             (skip-chars-backward "\n")
3739             t)
3740         (while (and afters
3741                     (not (re-search-forward
3742                           (concat "^" (regexp-quote (car afters)) ":")
3743                           nil t)))
3744           (pop afters))
3745         (when afters
3746           (re-search-forward "^[^ \t]" nil 'move)
3747           (beginning-of-line))
3748         (insert header ": \n")
3749         (forward-char -1)
3750         nil))))
3751
3752 (defun message-remove-signature ()
3753   "Remove the signature from the text between point and mark.
3754 The text will also be indented the normal way."
3755   (save-excursion
3756     (let ((start (point))
3757           mark)
3758       (if (not (re-search-forward message-signature-separator (mark t) t))
3759           ;; No signature here, so we just indent the cited text.
3760           (message-indent-citation)
3761         ;; Find the last non-empty line.
3762         (forward-line -1)
3763         (while (looking-at "[ \t]*$")
3764           (forward-line -1))
3765         (forward-line 1)
3766         (setq mark (set-marker (make-marker) (point)))
3767         (goto-char start)
3768         (message-indent-citation)
3769         ;; Enable undoing the deletion.
3770         (undo-boundary)
3771         (delete-region mark (mark t))
3772         (set-marker mark nil)))))
3773
3774 \f
3775
3776 ;;;
3777 ;;; Sending messages
3778 ;;;
3779
3780 ;; Avoid byte-compile warning.
3781 (defvar message-encoding-buffer nil)
3782 (defvar message-edit-buffer nil)
3783 (defvar message-mime-mode nil)
3784
3785 (defun message-send-and-exit (&optional arg)
3786   "Send message like `message-send', then, if no errors, exit from mail buffer."
3787   (interactive "P")
3788   (let ((buf (current-buffer))
3789         (actions message-exit-actions)
3790         (frame (selected-frame))
3791         (org-frame message-original-frame))
3792     (when (and (message-send arg)
3793                (buffer-name buf))
3794       (if message-kill-buffer-on-exit
3795           (kill-buffer buf)
3796         (bury-buffer buf)
3797         (when (eq buf (current-buffer))
3798           (message-bury buf)))
3799       (message-do-actions actions)
3800       (message-delete-frame frame org-frame)
3801       t)))
3802
3803 (defun message-dont-send ()
3804   "Don't send the message you have been editing.
3805 Instead, just auto-save the buffer and then bury it."
3806   (interactive)
3807   (set-buffer-modified-p t)
3808   (save-buffer)
3809   (let ((actions message-postpone-actions)
3810         (frame (selected-frame))
3811         (org-frame message-original-frame))
3812     (message-bury (current-buffer))
3813     (message-do-actions actions)
3814     (message-delete-frame frame org-frame)))
3815
3816 (defun message-kill-buffer ()
3817   "Kill the current buffer."
3818   (interactive)
3819   (when (or (not (buffer-modified-p))
3820             (not message-kill-buffer-query)
3821             (eq t message-kill-buffer-query-function)
3822             (funcall message-kill-buffer-query-function
3823                      "The buffer modified; kill anyway? "))
3824     (let ((actions message-kill-actions)
3825           (draft-article message-draft-article)
3826           (auto-save-file-name buffer-auto-save-file-name)
3827           (file-name buffer-file-name)
3828           (modified (buffer-modified-p))
3829           (frame (selected-frame))
3830           (org-frame message-original-frame))
3831       (setq buffer-file-name nil)
3832       (kill-buffer (current-buffer))
3833       (when (and message-kill-buffer-and-remove-file
3834                  (or (and auto-save-file-name
3835                           (file-exists-p auto-save-file-name))
3836                      (and file-name
3837                           (file-exists-p file-name)))
3838                  (progn
3839                    ;; If the message buffer has lived in a dedicated window,
3840                    ;; `kill-buffer' has killed the frame.  Thus the
3841                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
3842                    ;; that the user can see the question by raising the
3843                    ;; current frame:
3844                    (raise-frame)
3845                    (yes-or-no-p (format "Remove the backup file%s? "
3846                                         (if modified " too" "")))))
3847         (ignore-errors
3848           (delete-file auto-save-file-name))
3849         (let ((message-draft-article draft-article))
3850           (message-disassociate-draft)))
3851       (message-do-actions actions)
3852       (message-delete-frame frame org-frame)))
3853   (message ""))
3854
3855 (defun message-mimic-kill-buffer ()
3856   "Kill the current buffer with query.  This is an imitation for
3857 `kill-buffer', but it will delete a message frame."
3858   (interactive)
3859   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
3860                                       (buffer-name))))
3861         message-kill-buffer-and-remove-file)
3862     (when (or (not bufname)
3863               (string-equal bufname "")
3864               (string-equal bufname (buffer-name)))
3865       (message-kill-buffer))))
3866
3867 (defun message-delete-frame (frame org-frame)
3868   "Delete frame for editing message."
3869   (when (and (static-if (featurep 'xemacs)
3870                  (device-on-window-system-p)
3871                window-system)
3872              (or (and (eq message-delete-frame-on-exit t)
3873                       (select-frame frame)
3874                       (or (eq frame org-frame)
3875                           (prog1
3876                               (y-or-n-p "Delete this frame?")
3877                             (message ""))))
3878                  (and (eq message-delete-frame-on-exit 'ask)
3879                       (select-frame frame)
3880                       (prog1
3881                           (y-or-n-p "Delete this frame?")
3882                         (message "")))))
3883     (delete-frame frame)))
3884
3885 (defun message-bury (buffer)
3886   "Bury this mail BUFFER."
3887   (let ((newbuf (other-buffer buffer)))
3888     (bury-buffer buffer)
3889     (if (and (window-dedicated-p (selected-window))
3890              (not (null (delq (selected-frame) (visible-frame-list)))))
3891         (delete-frame (selected-frame))
3892       (switch-to-buffer newbuf))))
3893
3894 (defun message-send (&optional arg)
3895   "Send the message in the current buffer.
3896 If `message-interactive' is non-nil, wait for success indication or
3897 error messages, and inform user.
3898 Otherwise any failure is reported in a message back to the user from
3899 the mailer.
3900 The usage of ARG is defined by the instance that called Message.
3901 It should typically alter the sending method in some way or other."
3902   (interactive "P")
3903   ;; Disabled test.
3904   (when (or (buffer-modified-p)
3905             (message-check-element 'unchanged)
3906             (y-or-n-p "No changes in the buffer; really send? "))
3907     ;; Make it possible to undo the coming changes.
3908     (undo-boundary)
3909     (let ((inhibit-read-only t))
3910       (put-text-property (point-min) (point-max) 'read-only nil))
3911     (run-hooks 'message-send-hook)
3912     (message-fix-before-sending)
3913     (message message-sending-message)
3914     (let ((message-encoding-buffer
3915            (message-generate-new-buffer-clone-locals " message encoding"))
3916           (message-edit-buffer (current-buffer))
3917           (message-mime-mode mime-edit-mode-flag)
3918           (alist message-send-method-alist)
3919           (success t)
3920           elem sent dont-barf-on-no-method
3921           (message-options message-options))
3922       (unwind-protect
3923           (progn
3924             (message-options-set-recipient)
3925             (save-excursion
3926               (set-buffer message-encoding-buffer)
3927               (erase-buffer)
3928               ;; ;; Avoid copying text props (except hard newlines).
3929               ;; T-gnus change: copy all text props from the editing buffer
3930               ;; into the encoding buffer.
3931               (insert-buffer-substring message-edit-buffer)
3932               (funcall message-encode-function)
3933               (while (and success
3934                           (setq elem (pop alist)))
3935                 (when (funcall (cadr elem))
3936                   (when (and
3937                          (or (not (memq (car elem)
3938                                         message-sent-message-via))
3939                              (message-fetch-field "supersedes")
3940                              (if (or (message-gnksa-enable-p 'multiple-copies)
3941                                      (not (eq (car elem) 'news)))
3942                                  (y-or-n-p
3943                                   (format
3944                                    "Already sent message via %s; resend? "
3945                                    (car elem)))
3946                                (error "Denied posting -- multiple copies")))
3947                          (setq success (funcall (caddr elem) arg)))
3948                     (setq sent t)))))
3949             (unless
3950                 (or
3951                  sent
3952                  (not success)
3953                  (let ((fcc (message-fetch-field "Fcc"))
3954                        (gcc (message-fetch-field "Gcc")))
3955                    (when (or fcc gcc)
3956                      (or
3957                       (eq message-allow-no-recipients 'always)
3958                       (and (not (eq message-allow-no-recipients 'never))
3959                            (setq dont-barf-on-no-method
3960                                  (gnus-y-or-n-p
3961                                   (format "No receiver, perform %s anyway? "
3962                                           (cond ((and fcc gcc) "Fcc and Gcc")
3963                                                 (fcc "Fcc")
3964                                                 (t "Gcc"))))))))))
3965               (error "No methods specified to send by"))
3966             (when (or dont-barf-on-no-method
3967                       (and success sent))
3968               (message-do-fcc)
3969               (save-excursion
3970                 (run-hooks 'message-sent-hook))
3971               (message "Sending...done")
3972               ;; Mark the buffer as unmodified and delete auto-save.
3973               (set-buffer-modified-p nil)
3974               (delete-auto-save-file-if-necessary t)
3975               (message-disassociate-draft)
3976               ;; Delete other mail buffers and stuff.
3977               (message-do-send-housekeeping)
3978               (message-do-actions message-send-actions)
3979               ;; Return success.
3980               t))
3981         (kill-buffer message-encoding-buffer)))))
3982
3983 (defun message-send-via-mail (arg)
3984   "Send the current message via mail."
3985   (message-send-mail arg))
3986
3987 (defun message-send-via-news (arg)
3988   "Send the current message via news."
3989   (message-send-news arg))
3990
3991 (defmacro message-check (type &rest forms)
3992   "Eval FORMS if TYPE is to be checked."
3993   `(or (message-check-element ,type)
3994        (save-excursion
3995          ,@forms)))
3996
3997 (put 'message-check 'lisp-indent-function 1)
3998 (put 'message-check 'edebug-form-spec '(form body))
3999
4000 ;; Advise the function `invisible-region'.
4001 (unless noninteractive
4002   (let (current-load-list)
4003     (eval
4004      `(defadvice invisible-region (around add-mime-edit-invisible (start end)
4005                                           activate)
4006         "Advised by T-gnus Message.
4007 Add the text property `mime-edit-invisible' to an invisible text when
4008 the buffer's major mode is `message-mode'.  The added property will be
4009 used to distinguish whether the invisible text is a MIME part or not."
4010         ,(if (featurep 'xemacs)
4011              '(if (eq ?\n (char-after start))
4012                   (setq start (1+ start)))
4013            '(if (eq ?\n (char-after (1- end)))
4014                 (setq end (1- end))))
4015         (setq ad-return-value
4016               (if (eq 'message-mode major-mode)
4017                   (add-text-properties start end
4018                                        '(invisible t mime-edit-invisible t))
4019                 (put-text-property start end 'invisible t)))))))
4020
4021 (defun message-text-with-property (prop &optional start end reverse)
4022   "Return a list of start and end positions where the text has PROP.
4023 START and END bound the search, they default to `point-min' and
4024 `point-max' respectively.  If REVERSE is non-nil, find text which does
4025 not have PROP."
4026   (unless start
4027     (setq start (point-min)))
4028   (unless end
4029     (setq end (point-max)))
4030   (let (next regions)
4031     (if reverse
4032         (while (and start
4033                     (setq start (text-property-any start end prop nil)))
4034           (setq next (next-single-property-change start prop nil end))
4035           (push (cons start (or next end)) regions)
4036           (setq start next))
4037       (while (and start
4038                   (or (get-text-property start prop)
4039                       (and (setq start (next-single-property-change
4040                                         start prop nil end))
4041                            (get-text-property start prop))))
4042         (setq next (text-property-any start end prop nil))
4043         (push (cons start (or next end)) regions)
4044         (setq start next)))
4045     (nreverse regions)))
4046
4047 (defun message-fix-before-sending ()
4048   "Do various things to make the message nice before sending it."
4049   ;; Make sure there's a newline at the end of the message.
4050   (widen)
4051   (goto-char (point-max))
4052   (unless (bolp)
4053     (insert "\n"))
4054   ;; Make the hidden headers visible.
4055   (widen)
4056   ;; Sort headers before sending the message.
4057   (message-sort-headers)
4058   ;; Make invisible text visible except for mime parts which may be
4059   ;; inserted by the MIME-Edit.
4060   ;; It doesn't seem as if this is useful, since the invisible property
4061   ;; is clobbered by an after-change hook anyhow.
4062   (message-check 'invisible-text
4063     ;; FIXME T-gnus: It should also detect invisible overlays.
4064     (let (from
4065           (to (point-min))
4066           mime-from mime-to hidden-start)
4067       (while (setq from (text-property-any to (point-max) 'invisible t))
4068         (setq to (or (text-property-not-all from (point-max) 'invisible t)
4069                      (point-max))
4070               mime-to from)
4071         (while (setq mime-from (text-property-any mime-to to
4072                                                   'mime-edit-invisible t))
4073           (when (> mime-from mime-to)
4074             (setq hidden-start (or hidden-start mime-to))
4075             (add-text-properties mime-to mime-from
4076                                  '(invisible nil face highlight
4077                                              font-lock-face highlight)))
4078           (setq mime-to (or (text-property-not-all mime-from to
4079                                                    'mime-edit-invisible t)
4080                             to)))
4081         (when (< mime-to to)
4082           (setq hidden-start (or hidden-start mime-to))
4083           (add-text-properties mime-to to
4084                                '(invisible nil face highlight
4085                                            font-lock-face highlight))))
4086       (when hidden-start
4087         (goto-char hidden-start)
4088         (set-window-start (selected-window) (point-at-bol))
4089         (unless (yes-or-no-p
4090                  "Invisible text found and made visible; continue sending? ")
4091           (error "Invisible text found and made visible")))))
4092 ;; The following check is needless to T-gnus since T-gnus determines
4093 ;; a MIME charset forcibly (even if it cannot be determined properly,
4094 ;; the value of the `default-mime-charset-for-write' variable is used).
4095 ;;  (message-check 'illegible-text
4096 ;;    (let (found choice)
4097 ;;      (message-goto-body)
4098 ;;      (skip-chars-forward mm-7bit-chars)
4099 ;;      (while (not (eobp))
4100 ;;      (when (let ((char (char-after)))
4101 ;;              (or (< (mm-char-int char) 128)
4102 ;;                  (and (mm-multibyte-p)
4103 ;;                       (memq (char-charset char)
4104 ;;                             '(eight-bit-control eight-bit-graphic
4105 ;;                                                 control-1))
4106 ;;                       (not (get-text-property
4107 ;;                             (point) 'untranslated-utf-8)))))
4108 ;;        (message-overlay-put (message-make-overlay (point) (1+ (point)))
4109 ;;                             'face 'highlight)
4110 ;;        (setq found t))
4111 ;;      (forward-char)
4112 ;;      (skip-chars-forward mm-7bit-chars))
4113 ;;      (when found
4114 ;;      (setq choice
4115 ;;            (gnus-multiple-choice
4116 ;;             "Non-printable characters found.  Continue sending?"
4117 ;;             '((?d "Remove non-printable characters and send")
4118 ;;               (?r "Replace non-printable characters with dots and send")
4119 ;;               (?i "Ignore non-printable characters and send")
4120 ;;               (?e "Continue editing"))))
4121 ;;      (if (eq choice ?e)
4122 ;;          (error "Non-printable characters"))
4123 ;;      (message-goto-body)
4124 ;;      (skip-chars-forward mm-7bit-chars)
4125 ;;      (while (not (eobp))
4126 ;;        (when (let ((char (char-after)))
4127 ;;                (or (< (mm-char-int char) 128)
4128 ;;                    (and (mm-multibyte-p)
4129 ;;                         ;; Fixme: Wrong for Emacs 22 and for things
4130 ;;                         ;; like undecable utf-8.  Should at least
4131 ;;                         ;; use find-coding-systems-region.
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 ;;          (if (eq choice ?i)
4138 ;;              (message-kill-all-overlays)
4139 ;;            (delete-char 1)
4140 ;;            (when (eq choice ?r)
4141 ;;              (insert "."))))
4142 ;;        (forward-char)
4143 ;;        (skip-chars-forward mm-7bit-chars)))))
4144   )
4145
4146 (defun message-add-action (action &rest types)
4147   "Add ACTION to be performed when doing an exit of type TYPES."
4148   (while types
4149     (add-to-list (intern (format "message-%s-actions" (pop types)))
4150                  action)))
4151
4152 (defun message-delete-action (action &rest types)
4153   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4154   (let (var)
4155     (while types
4156       (set (setq var (intern (format "message-%s-actions" (pop types))))
4157            (delq action (symbol-value var))))))
4158
4159 (defun message-do-actions (actions)
4160   "Perform all actions in ACTIONS."
4161   ;; Now perform actions on successful sending.
4162   (dolist (action actions)
4163     (ignore-errors
4164       (cond
4165        ;; A simple function.
4166        ((functionp action)
4167         (funcall action))
4168        ;; Something to be evaled.
4169        (t
4170         (eval action))))))
4171
4172 (defsubst message-maybe-split-and-send-mail ()
4173   "Split a message if necessary, and send it via mail.
4174 Returns nil if sending succeeded, returns any string if sending failed.
4175 This sub function is for exclusive use of `message-send-mail'."
4176   (let ((mime-edit-split-ignored-field-regexp
4177          mime-edit-split-ignored-field-regexp)
4178         (case-fold-search t)
4179         failure)
4180     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4181       (setq mime-edit-split-ignored-field-regexp
4182             (concat (substring mime-edit-split-ignored-field-regexp
4183                                0 (match-beginning 0))
4184                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4185                     "_so_don't_rape_it!"
4186                     (substring mime-edit-split-ignored-field-regexp
4187                                (match-end 0)))))
4188     (setq failure
4189           (or
4190            (catch 'message-sending-mail-failure
4191              (mime-edit-maybe-split-and-send
4192               (function
4193                (lambda ()
4194                  (interactive)
4195                  (save-restriction
4196                    (std11-narrow-to-header mail-header-separator)
4197                    (goto-char (point-min))
4198                    (when (re-search-forward "^Message-ID:" nil t)
4199                      (delete-region (match-end 0) (std11-field-end))
4200                      (insert " " (message-make-message-id))))
4201                  (condition-case err
4202                      (funcall (or message-send-mail-real-function
4203                                   message-send-mail-function))
4204                    (error
4205                     (throw 'message-sending-mail-failure err))))))
4206              nil)
4207            (condition-case err
4208                (progn
4209                  (funcall (or message-send-mail-real-function
4210                               message-send-mail-function))
4211                  nil)
4212              (error err))))
4213     (when failure
4214       (if (eq 'error (car failure))
4215           (cadr failure)
4216         (prin1-to-string failure)))))
4217
4218 (defun message-send-mail-partially ()
4219   "Send mail as message/partial."
4220   ;; replace the header delimiter with a blank line
4221   (goto-char (point-min))
4222   (re-search-forward
4223    (concat "^" (regexp-quote mail-header-separator) "\n"))
4224   (replace-match "\n")
4225   (run-hooks 'message-send-mail-hook)
4226   (let ((p (goto-char (point-min)))
4227         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4228         (curbuf (current-buffer))
4229         (id (message-make-message-id)) (n 1)
4230         plist total  header required-mail-headers)
4231     (while (not (eobp))
4232       (if (< (point-max) (+ p message-send-mail-partially-limit))
4233           (goto-char (point-max))
4234         (goto-char (+ p message-send-mail-partially-limit))
4235         (beginning-of-line)
4236         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4237       (push p plist)
4238       (setq p (point)))
4239     (setq total (length plist))
4240     (push (point-max) plist)
4241     (setq plist (nreverse plist))
4242     (unwind-protect
4243         (save-excursion
4244           (setq p (pop plist))
4245           (while plist
4246             (set-buffer curbuf)
4247             (copy-to-buffer tembuf p (car plist))
4248             (set-buffer tembuf)
4249             (goto-char (point-min))
4250             (if header
4251                 (progn
4252                   (goto-char (point-min))
4253                   (narrow-to-region (point) (point))
4254                   (insert header))
4255               (message-goto-eoh)
4256               (setq header (buffer-substring (point-min) (point)))
4257               (goto-char (point-min))
4258               (narrow-to-region (point) (point))
4259               (insert header)
4260               (message-remove-header "Mime-Version")
4261               (message-remove-header "Content-Type")
4262               (message-remove-header "Content-Transfer-Encoding")
4263               (message-remove-header "Message-ID")
4264               (message-remove-header "Lines")
4265               (goto-char (point-max))
4266               (insert "Mime-Version: 1.0\n")
4267               (setq header (buffer-string)))
4268             (goto-char (point-max))
4269             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4270                             id n total))
4271             (forward-char -1)
4272             (let ((mail-header-separator ""))
4273               (when (memq 'Message-ID message-required-mail-headers)
4274                 (insert "Message-ID: " (message-make-message-id) "\n"))
4275               (when (memq 'Lines message-required-mail-headers)
4276                 (insert "Lines: " (message-make-lines) "\n"))
4277               (message-goto-subject)
4278               (end-of-line)
4279               (insert (format " (%d/%d)" n total))
4280               (widen)
4281               (mm-with-unibyte-current-buffer
4282                 (funcall (or message-send-mail-real-function
4283                              message-send-mail-function))))
4284             (setq n (+ n 1))
4285             (setq p (pop plist))
4286             (erase-buffer)))
4287       (kill-buffer tembuf))))
4288
4289 (defun message-send-mail (&optional arg)
4290   (require 'mail-utils)
4291   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4292          (case-fold-search nil)
4293          (news (message-news-p))
4294          (message-this-is-mail t)
4295          (headers message-required-mail-headers)
4296          failure)
4297     (when message-generate-hashcash
4298       (message "Generating hashcash...")
4299       ;; Wait for calculations already started to finish...
4300       (hashcash-wait-async)
4301       ;; ...and do calculations not already done.  mail-add-payment
4302       ;; will leave existing X-Hashcash headers alone.
4303       (mail-add-payment)
4304       (message "Generating hashcash...done"))
4305     (save-restriction
4306       (message-narrow-to-headers)
4307       ;; Generate the Mail-Followup-To header if the header is not there...
4308       (if (and (message-subscribed-p)
4309                (not (mail-fetch-field "mail-followup-to")))
4310           (setq headers
4311                 (cons
4312                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4313                  message-required-mail-headers))
4314         ;; otherwise, delete the MFT header if the field is empty
4315         (when (equal "" (mail-fetch-field "mail-followup-to"))
4316           (message-remove-header "^Mail-Followup-To:")))
4317       ;; Insert some headers.
4318       (let ((message-deletable-headers
4319              (if news nil message-deletable-headers)))
4320         (message-generate-headers headers))
4321       ;; Let the user do all of the above.
4322       (run-hooks 'message-header-hook))
4323     (if (not (message-check-mail-syntax))
4324         (progn
4325           (message "")
4326           nil)
4327       (unwind-protect
4328           (save-excursion
4329             (set-buffer tembuf)
4330             (erase-buffer)
4331             ;; ;; Avoid copying text props (except hard newlines).
4332             ;; T-gnus change: copy all text props from the editing buffer
4333             ;; into the encoding buffer.
4334             (insert-buffer-substring message-encoding-buffer)
4335             ;; Remove some headers.
4336             (save-restriction
4337               (message-narrow-to-headers)
4338 ;; We Semi-gnus people have no use for it.
4339 ;;            ;; We (re)generate the Lines header.
4340 ;;            (when (memq 'Lines message-required-mail-headers)
4341 ;;              (message-generate-headers '(Lines)))
4342               (message-remove-header message-ignored-mail-headers t))
4343             (goto-char (point-max))
4344             ;; require one newline at the end.
4345             (or (= (preceding-char) ?\n)
4346                 (insert ?\n))
4347             (message-cleanup-headers)
4348             ;; FIXME: we're inserting the courtesy copy after encoding.
4349             ;; This is wrong if the courtesy copy string contains
4350             ;; non-ASCII characters. -- jh
4351             (when
4352                 (save-restriction
4353                   (message-narrow-to-headers)
4354                   (and news
4355                        (or (message-fetch-field "cc")
4356                            (message-fetch-field "bcc")
4357                            (message-fetch-field "to"))
4358                        (let ((content-type (mime-read-Content-Type)))
4359                          (and
4360                           (or
4361                            (not content-type)
4362                            (and
4363                             (eq 'text (cdr (assq 'type content-type)))
4364                             (eq 'plain (cdr (assq 'subtype content-type)))))
4365                           (not
4366                            (string= "base64"
4367                                     (mime-read-Content-Transfer-Encoding)))))))
4368               (message-insert-courtesy-copy))
4369             (setq failure (message-maybe-split-and-send-mail)))
4370         (kill-buffer tembuf))
4371       (set-buffer message-edit-buffer)
4372       (if failure
4373           (progn
4374             (message "Couldn't send message via mail: %s" failure)
4375             nil)
4376         (push 'mail message-sent-message-via)))))
4377
4378 (defun message-send-mail-with-sendmail ()
4379   "Send off the prepared buffer with sendmail."
4380   (let ((errbuf (if message-interactive
4381                     (message-generate-new-buffer-clone-locals
4382                      " sendmail errors")
4383                   0))
4384         resend-to-addresses delimline)
4385     (unwind-protect
4386         (progn
4387           (let ((case-fold-search t))
4388             (save-restriction
4389               (message-narrow-to-headers)
4390               (setq resend-to-addresses (message-fetch-field "resent-to")))
4391             ;; Change header-delimiter to be what sendmail expects.
4392             (goto-char (point-min))
4393             (re-search-forward
4394              (concat "^" (regexp-quote mail-header-separator) "\n"))
4395             (replace-match "\n")
4396             (backward-char 1)
4397             (setq delimline (point-marker))
4398             (run-hooks 'message-send-mail-hook)
4399             ;; Insert an extra newline if we need it to work around
4400             ;; Sun's bug that swallows newlines.
4401             (goto-char (1+ delimline))
4402             (when (eval message-mailer-swallows-blank-line)
4403               (newline))
4404             (when message-interactive
4405               (with-current-buffer errbuf
4406                 (erase-buffer))))
4407           (let* ((default-directory "/")
4408                  (cpr (as-binary-process
4409                        (apply
4410                         'call-process-region
4411                         (append
4412                          (list (point-min) (point-max)
4413                                (if (boundp 'sendmail-program)
4414                                    sendmail-program
4415                                  "/usr/lib/sendmail")
4416                                nil errbuf nil "-oi")
4417                          ;; Always specify who from,
4418                          ;; since some systems have broken sendmails.
4419                          ;; But some systems are more broken with -f, so
4420                          ;; we'll let users override this.
4421                          (if (null message-sendmail-f-is-evil)
4422                              (list "-f" (message-sendmail-envelope-from)))
4423                          ;; These mean "report errors by mail"
4424                          ;; and "deliver in background".
4425                          (if (null message-interactive) '("-oem" "-odb"))
4426                          ;; Get the addresses from the message
4427                          ;; unless this is a resend.
4428                          ;; We must not do that for a resend
4429                          ;; because we would find the original addresses.
4430                          ;; For a resend, include the specific addresses.
4431                          (if resend-to-addresses
4432                              (list resend-to-addresses)
4433                            '("-t")))))))
4434             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4435               (error "Sending...failed with exit value %d" cpr)))
4436           (when message-interactive
4437             (save-excursion
4438               (set-buffer errbuf)
4439               (goto-char (point-min))
4440               (while (re-search-forward "\n+ *" nil t)
4441                 (replace-match "; "))
4442               (if (not (zerop (buffer-size)))
4443                   (error "Sending...failed to %s"
4444                          (buffer-string))))))
4445       (when (bufferp errbuf)
4446         (kill-buffer errbuf)))))
4447
4448 (defun message-send-mail-with-qmail ()
4449   "Pass the prepared message buffer to qmail-inject.
4450 Refer to the documentation for the variable `message-send-mail-function'
4451 to find out how to use this."
4452   ;; replace the header delimiter with a blank line
4453   (goto-char (point-min))
4454   (re-search-forward
4455    (concat "^" (regexp-quote mail-header-separator) "\n"))
4456   (replace-match "\n")
4457   (backward-char 1)
4458   (run-hooks 'message-send-mail-hook)
4459   ;; send the message
4460   (case
4461       (as-binary-process
4462        (apply
4463         'call-process-region (point-min) (point-max)
4464         message-qmail-inject-program nil nil nil
4465         ;; qmail-inject's default behaviour is to look for addresses on the
4466         ;; command line; if there're none, it scans the headers.
4467         ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4468         ;;
4469         ;; in general, ALL of qmail-inject's defaults are perfect for simply
4470         ;; reading a formatted (i. e., at least a To: or Resent-To header)
4471         ;; message from stdin.
4472         ;;
4473         ;; qmail also has the advantage of not having been raped by
4474         ;; various vendors, so we don't have to allow for that, either --
4475         ;; compare this with message-send-mail-with-sendmail and weep
4476         ;; for sendmail's lost innocence.
4477         ;;
4478         ;; all this is way cool coz it lets us keep the arguments entirely
4479         ;; free for -inject-arguments -- a big win for the user and for us
4480         ;; since we don't have to play that double-guessing game and the user
4481         ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4482         (if (functionp message-qmail-inject-args)
4483             (funcall message-qmail-inject-args)
4484           message-qmail-inject-args)))
4485     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4486     ;; we have to look at the retval instead
4487     (0 nil)
4488     (100 (error "qmail-inject reported permanent failure"))
4489     (111 (error "qmail-inject reported transient failure"))
4490     ;; should never happen
4491     (t   (error "qmail-inject reported unknown failure"))))
4492
4493 (defun message-send-mail-with-mh ()
4494   "Send the prepared message buffer with mh."
4495   (let ((mh-previous-window-config nil)
4496         (name (mh-new-draft-name)))
4497     (setq buffer-file-name name)
4498     ;; MH wants to generate these headers itself.
4499     (when message-mh-deletable-headers
4500       (let ((headers message-mh-deletable-headers))
4501         (while headers
4502           (goto-char (point-min))
4503           (and (re-search-forward
4504                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4505                (message-delete-line))
4506           (pop headers))))
4507     (run-hooks 'message-send-mail-hook)
4508     ;; Pass it on to mh.
4509     (mh-send-letter)))
4510
4511 (defun message-send-mail-with-smtp ()
4512   "Send off the prepared buffer with SMTP."
4513   (require 'smtp) ; XXX
4514   (let ((case-fold-search t)
4515         recipients)
4516     (save-restriction
4517       (message-narrow-to-headers)
4518       (setq recipients
4519             ;; XXX: Should be replaced by better one.
4520             (smtp-deduce-address-list (current-buffer)
4521                                       (point-min) (point-max)))
4522       ;; Remove BCC lines.
4523       (message-remove-header "bcc"))
4524     ;; replace the header delimiter with a blank line.
4525     (goto-char (point-min))
4526     (re-search-forward
4527      (concat "^" (regexp-quote mail-header-separator) "\n"))
4528     (replace-match "\n")
4529     (backward-char 1)
4530     (run-hooks 'message-send-mail-hook)
4531     (if recipients
4532         (smtp-send-buffer user-mail-address recipients (current-buffer))
4533       (error "Sending failed; no recipients"))))
4534
4535 (defsubst message-maybe-split-and-send-news (method)
4536   "Split a message if necessary, and send it via news.
4537 Returns nil if sending succeeded, returns t if sending failed.
4538 This sub function is for exclusive use of `message-send-news'."
4539   (let ((mime-edit-split-ignored-field-regexp
4540          mime-edit-split-ignored-field-regexp)
4541         (case-fold-search t))
4542     (while (string-match "Message-ID" mime-edit-split-ignored-field-regexp)
4543       (setq mime-edit-split-ignored-field-regexp
4544             (concat (substring mime-edit-split-ignored-field-regexp
4545                                0 (match-beginning 0))
4546                     "Hey_MIME-Edit,_there_is_an_inviolable_Message_ID"
4547                     "_so_don't_rape_it!"
4548                     (substring mime-edit-split-ignored-field-regexp
4549                                (match-end 0)))))
4550     (or
4551      (catch 'message-sending-news-failure
4552        (mime-edit-maybe-split-and-send
4553         (function
4554          (lambda ()
4555            (interactive)
4556            (save-restriction
4557              (std11-narrow-to-header mail-header-separator)
4558              (goto-char (point-min))
4559              (when (re-search-forward "^Message-ID:" nil t)
4560                (delete-region (match-end 0) (std11-field-end))
4561                (insert " " (message-make-message-id))))
4562            (unless (funcall message-send-news-function method)
4563              (throw 'message-sending-news-failure t)))))
4564        nil)
4565      (not (funcall message-send-news-function method)))))
4566
4567 (defun message-smtpmail-send-it ()
4568   "Send the prepared message buffer with `smtpmail-send-it'.
4569 This only differs from `smtpmail-send-it' that this command evaluates
4570 `message-send-mail-hook' just before sending a message.  It is useful
4571 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4572 manual for details."
4573   (run-hooks 'message-send-mail-hook)
4574   (smtpmail-send-it))
4575
4576 (defun message-canlock-generate ()
4577   "Return a string that is non-trivial to guess.
4578 Do not use this for anything important, it is cryptographically weak."
4579   (require 'sha1)
4580   (let (sha1-maximum-internal-length)
4581     (sha1 (concat (message-unique-id)
4582                   (format "%x%x%x" (random) (random t) (random))
4583                   (prin1-to-string (recent-keys))
4584                   (prin1-to-string (garbage-collect))))))
4585
4586 (defun message-canlock-password ()
4587   "The password used by message for cancel locks.
4588 This is the value of `canlock-password', if that option is non-nil.
4589 Otherwise, generate and save a value for `canlock-password' first."
4590   (unless canlock-password
4591     (customize-save-variable 'canlock-password (message-canlock-generate))
4592     (setq canlock-password-for-verify canlock-password))
4593   canlock-password)
4594
4595 (defun message-insert-canlock ()
4596   (when message-insert-canlock
4597     (message-canlock-password)
4598     (canlock-insert-header)))
4599
4600 (defun message-send-news (&optional arg)
4601   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4602          (case-fold-search nil)
4603          (method (if (functionp message-post-method)
4604                      (funcall message-post-method arg)
4605                    message-post-method))
4606          (newsgroups-field (save-restriction
4607                              (message-narrow-to-headers-or-head)
4608                              (message-fetch-field "Newsgroups")))
4609          (followup-field (save-restriction
4610                            (message-narrow-to-headers-or-head)
4611                            (message-fetch-field "Followup-To")))
4612          ;; BUG: We really need to get the charset for each name in the
4613          ;; Newsgroups and Followup-To lines to allow crossposting
4614          ;; between group namess with incompatible character sets.
4615          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4616          (group-field-charset
4617           (gnus-group-name-charset method newsgroups-field))
4618          (followup-field-charset
4619           (gnus-group-name-charset method (or followup-field "")))
4620          (mime-field-encoding-method-alist
4621           (append (when group-field-charset
4622                     (list (cons "Newsgroups" group-field-charset)))
4623                   (when followup-field-charset
4624                     (list (cons "Followup-To" followup-field-charset)))
4625                   mime-field-encoding-method-alist))
4626          (message-syntax-checks
4627           (if (and arg
4628                    (listp message-syntax-checks))
4629               (cons '(existing-newsgroups . disabled)
4630                     message-syntax-checks)
4631             message-syntax-checks))
4632          (message-this-is-news t)
4633          result)
4634     (save-restriction
4635       (message-narrow-to-headers)
4636       ;; Insert some headers.
4637       (message-generate-headers message-required-news-headers)
4638       (message-insert-canlock)
4639       ;; Let the user do all of the above.
4640       (run-hooks 'message-header-hook))
4641     ;; Note: This check will be disabled by the ".*" default value for
4642     ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4643     (when (and group-field-charset
4644                (listp message-syntax-checks))
4645       (setq message-syntax-checks
4646             (cons '(valid-newsgroups . disabled)
4647                   message-syntax-checks)))
4648     (message-cleanup-headers)
4649     (if (not (let ((message-post-method method))
4650                (message-check-news-syntax)))
4651         nil
4652       (unwind-protect
4653           (save-excursion
4654             (set-buffer tembuf)
4655             (buffer-disable-undo)
4656             (erase-buffer)
4657             (insert-buffer-substring message-encoding-buffer)
4658             ;; Remove some headers.
4659             (save-restriction
4660               (message-narrow-to-headers)
4661 ;; We Semi-gnus people have no use for it.
4662 ;;            ;; We (re)generate the Lines header.
4663 ;;            (when (memq 'Lines message-required-mail-headers)
4664 ;;              (message-generate-headers '(Lines)))
4665               ;; Remove some headers.
4666               (message-remove-header message-ignored-news-headers t))
4667             (goto-char (point-max))
4668             ;; require one newline at the end.
4669             (or (= (preceding-char) ?\n)
4670                 (insert ?\n))
4671             (setq result (message-maybe-split-and-send-news method)))
4672         (kill-buffer tembuf))
4673       (set-buffer message-edit-buffer)
4674       (if result
4675           (progn
4676             (message "Couldn't send message via news: %s"
4677                      (nnheader-get-report (car method)))
4678             nil)
4679         (push 'news message-sent-message-via)))))
4680
4681 ;; 1997-09-29 by MORIOKA Tomohiko
4682 (defun message-send-news-with-gnus (method)
4683   (let ((case-fold-search t))
4684     ;; Remove the delimiter.
4685     (goto-char (point-min))
4686     (re-search-forward
4687      (concat "^" (regexp-quote mail-header-separator) "\n"))
4688     (replace-match "\n")
4689     (backward-char 1)
4690     (run-hooks 'message-send-news-hook)
4691     (gnus-open-server method)
4692     (message "Sending news via %s..." (gnus-server-string method))
4693     (gnus-request-post method)
4694     ))
4695
4696 ;;;
4697 ;;; Header generation & syntax checking.
4698 ;;;
4699
4700 (defun message-check-element (type)
4701   "Return non-nil if this TYPE is not to be checked."
4702   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4703       t
4704     (let ((able (assq type message-syntax-checks)))
4705       (and (consp able)
4706            (eq (cdr able) 'disabled)))))
4707
4708 (defun message-check-news-syntax ()
4709   "Check the syntax of the message."
4710   (save-excursion
4711     (save-restriction
4712       (widen)
4713       (and
4714        ;; We narrow to the headers and check them first.
4715        (save-excursion
4716          (save-restriction
4717            (message-narrow-to-headers)
4718            (message-check-news-header-syntax)))
4719        ;; Check the body.
4720        (save-excursion
4721          (set-buffer message-edit-buffer)
4722          (message-check-news-body-syntax))))))
4723
4724 (defun message-check-news-header-syntax ()
4725   (and
4726    ;; Check Newsgroups header.
4727    (message-check 'newsgroups
4728      (let ((group (message-fetch-field "newsgroups")))
4729        (or
4730         (and group
4731              (not (string-match "\\`[ \t]*\\'" group)))
4732         (ignore
4733          (message
4734           "The newsgroups field is empty or missing.  Posting is denied.")))))
4735    ;; Check the Subject header.
4736    (message-check 'subject
4737      (let* ((case-fold-search t)
4738             (subject (message-fetch-field "subject")))
4739        (or
4740         (and subject
4741              (not (string-match "\\`[ \t]*\\'" subject)))
4742         (ignore
4743          (message
4744           "The subject field is empty or missing.  Posting is denied.")))))
4745    ;; Check for commands in Subject.
4746    (message-check 'subject-cmsg
4747      (if (string-match "^cmsg " (message-fetch-field "subject"))
4748          (y-or-n-p
4749           "The control code \"cmsg\" is in the subject.  Really post? ")
4750        t))
4751    ;; Check long header lines.
4752    (message-check 'long-header-lines
4753      (let ((start (point))
4754            (header nil)
4755            (length 0)
4756            found)
4757        (while (and (not found)
4758                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4759          (if (> (- (point) (match-beginning 0)) 998)
4760              (setq found t
4761                    length (- (point) (match-beginning 0)))
4762            (setq header (match-string-no-properties 1)))
4763          (setq start (match-beginning 0))
4764          (forward-line 1))
4765        (if found
4766            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4767                              header length))
4768          t)))
4769    ;; Check for multiple identical headers.
4770    (message-check 'multiple-headers
4771      (let (found)
4772        (while (and (not found)
4773                    (re-search-forward "^[^ \t:]+: " nil t))
4774          (save-excursion
4775            (or (re-search-forward
4776                 (concat "^"
4777                         (regexp-quote
4778                          (setq found
4779                                (buffer-substring
4780                                 (match-beginning 0) (- (match-end 0) 2))))
4781                         ":")
4782                 nil t)
4783                (setq found nil))))
4784        (if found
4785            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4786          t)))
4787    ;; Check for Version and Sendsys.
4788    (message-check 'sendsys
4789      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4790          (y-or-n-p
4791           (format "The article contains a %s command.  Really post? "
4792                   (buffer-substring (match-beginning 0)
4793                                     (1- (match-end 0)))))
4794        t))
4795    ;; See whether we can shorten Followup-To.
4796    (message-check 'shorten-followup-to
4797      (let ((newsgroups (message-fetch-field "newsgroups"))
4798            (followup-to (message-fetch-field "followup-to"))
4799            to)
4800        (when (and newsgroups
4801                   (string-match "," newsgroups)
4802                   (not followup-to)
4803                   (not
4804                    (zerop
4805                     (length
4806                      (setq to (completing-read
4807                                "Followups to (default: no Followup-To header) "
4808                                (mapcar #'list
4809                                        (cons "poster"
4810                                              (message-tokenize-header
4811                                               newsgroups)))))))))
4812          (goto-char (point-min))
4813          (insert "Followup-To: " to "\n"))
4814        t))
4815    ;; Check "Shoot me".
4816    (message-check 'shoot
4817      (if (re-search-forward
4818           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4819          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4820        t))
4821    ;; Check for Approved.
4822    (message-check 'approved
4823      (if (re-search-forward "^Approved:" nil t)
4824          (y-or-n-p "The article contains an Approved header.  Really post? ")
4825        t))
4826    ;; Check the Message-ID header.
4827    (message-check 'message-id
4828      (let* ((case-fold-search t)
4829             (message-id (message-fetch-field "message-id" t)))
4830        (or (not message-id)
4831            ;; Is there an @ in the ID?
4832            (and (string-match "@" message-id)
4833                 ;; Is there a dot in the ID?
4834                 (string-match "@[^.]*\\." message-id)
4835                 ;; Does the ID end with a dot?
4836                 (not (string-match "\\.>" message-id)))
4837            (y-or-n-p
4838             (format "The Message-ID looks strange: \"%s\".  Really post? "
4839                     message-id)))))
4840    ;; Check the Newsgroups & Followup-To headers.
4841    (message-check 'existing-newsgroups
4842      (let* ((case-fold-search t)
4843             (newsgroups (message-fetch-field "newsgroups"))
4844             (followup-to (message-fetch-field "followup-to"))
4845             (groups (message-tokenize-header
4846                      (if followup-to
4847                          (concat newsgroups "," followup-to)
4848                        newsgroups)))
4849             (post-method (if (functionp message-post-method)
4850                              (funcall message-post-method)
4851                            message-post-method))
4852             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4853             ;; would probably involve a new nnoo function.
4854             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4855             (method (if (and (consp post-method)
4856                              (eq (car post-method) 'nnvirtual)
4857                              gnus-message-group-art)
4858                         (let ((group (car (nnvirtual-find-group-art
4859                                            (car gnus-message-group-art)
4860                                            (cdr gnus-message-group-art)))))
4861                           (gnus-find-method-for-group group))
4862                       post-method))
4863             (known-groups
4864              (mapcar (lambda (n)
4865                        (gnus-group-name-decode
4866                         (gnus-group-real-name n)
4867                         (gnus-group-name-charset method n)))
4868                      (gnus-groups-from-server method)))
4869             errors)
4870        (while groups
4871          (when (and (not (equal (car groups) "poster"))
4872                     (not (member (car groups) known-groups))
4873                     (not (member (car groups) errors)))
4874            (push (car groups) errors))
4875          (pop groups))
4876        (cond
4877         ;; Gnus is not running.
4878         ((or (not (and (boundp 'gnus-active-hashtb)
4879                        gnus-active-hashtb))
4880              (not (boundp 'gnus-read-active-file)))
4881          t)
4882         ;; We don't have all the group names.
4883         ((and (or (not gnus-read-active-file)
4884                   (eq gnus-read-active-file 'some))
4885               errors)
4886          (y-or-n-p
4887           (format
4888            "Really use %s possibly unknown group%s: %s? "
4889            (if (= (length errors) 1) "this" "these")
4890            (if (= (length errors) 1) "" "s")
4891            (mapconcat 'identity errors ", "))))
4892         ;; There were no errors.
4893         ((not errors)
4894          t)
4895         ;; There are unknown groups.
4896         (t
4897          (y-or-n-p
4898           (format
4899            "Really post to %s unknown group%s: %s? "
4900            (if (= (length errors) 1) "this" "these")
4901            (if (= (length errors) 1) "" "s")
4902            (mapconcat 'identity errors ", ")))))))
4903    ;; Check continuation headers.
4904    (message-check 'continuation-headers
4905      (goto-char (point-min))
4906      (let ((do-posting t))
4907        (while (re-search-forward "^[^ \t\n][^:\n]*$" nil t)
4908          (if (y-or-n-p "Fix continuation lines? ")
4909              (progn
4910                (goto-char (match-beginning 0))
4911                (insert " "))
4912            (unless (y-or-n-p "Send anyway? ")
4913              (setq do-posting nil))))
4914        do-posting))
4915    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4916    (message-check 'valid-newsgroups
4917      (let ((case-fold-search t)
4918            (headers '("Newsgroups" "Followup-To"))
4919            header error)
4920        (while (and headers (not error))
4921          (when (setq header (mail-fetch-field (car headers)))
4922            (if (or
4923                 (not
4924                  (string-match
4925                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4926                   header))
4927                 (memq
4928                  nil (mapcar
4929                       (lambda (g)
4930                         (not (string-match "\\.\\'\\|\\.\\." g)))
4931                       (message-tokenize-header header ","))))
4932                (setq error t)))
4933          (unless error
4934            (pop headers)))
4935        (if (not error)
4936            t
4937          (y-or-n-p
4938           (format "The %s header looks odd: \"%s\".  Really post? "
4939                   (car headers) header)))))
4940    (message-check 'repeated-newsgroups
4941      (let ((case-fold-search t)
4942            (headers '("Newsgroups" "Followup-To"))
4943            header error groups group)
4944        (while (and headers
4945                    (not error))
4946          (when (setq header (mail-fetch-field (pop headers)))
4947            (setq groups (message-tokenize-header header ","))
4948            (while (setq group (pop groups))
4949              (when (member group groups)
4950                (setq error group
4951                      groups nil)))))
4952        (if (not error)
4953            t
4954          (y-or-n-p
4955           (format "Group %s is repeated in headers.  Really post? " error)))))
4956    ;; Check the From header.
4957    (message-check 'from
4958      (let* ((case-fold-search t)
4959             (from (message-fetch-field "from"))
4960             ad)
4961        (cond
4962         ((not from)
4963          (message "There is no From line.  Posting is denied.")
4964          nil)
4965         ((or (not (string-match
4966                    "@[^\\.]*\\."
4967                    (setq ad (nth 1 (std11-extract-address-components
4968                                     from))))) ;larsi@ifi
4969              (string-match "\\.\\." ad) ;larsi@ifi..uio
4970              (string-match "@\\." ad)   ;larsi@.ifi.uio
4971              (string-match "\\.$" ad)   ;larsi@ifi.uio.
4972              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
4973              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
4974          (message
4975           "Denied posting -- the From looks strange: \"%s\"." from)
4976          nil)
4977         ((let ((addresses (rfc822-addresses from)))
4978            (while (and addresses
4979                        (not (eq (string-to-char (car addresses)) ?\()))
4980              (setq addresses (cdr addresses)))
4981            addresses)
4982          (message
4983           "Denied posting -- bad From address: \"%s\"." from)
4984          nil)
4985         (t t))))
4986    ;; Check the Reply-To header.
4987    (message-check 'reply-to
4988      (let* ((case-fold-search t)
4989             (reply-to (message-fetch-field "reply-to"))
4990             ad)
4991        (cond
4992         ((not reply-to)
4993          t)
4994         ((string-match "," reply-to)
4995          (y-or-n-p
4996           (format "Multiple Reply-To addresses: \"%s\". Really post? "
4997                   reply-to)))
4998         ((or (not (string-match
4999                    "@[^\\.]*\\."
5000                    (setq ad (nth 1 (std11-extract-address-components
5001                                     reply-to))))) ;larsi@ifi
5002              (string-match "\\.\\." ad) ;larsi@ifi..uio
5003              (string-match "@\\." ad)   ;larsi@.ifi.uio
5004              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5005              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5006              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5007          (y-or-n-p
5008           (format
5009            "The Reply-To looks strange: \"%s\". Really post? "
5010            reply-to)))
5011         (t t))))))
5012
5013 (defun message-check-news-body-syntax ()
5014   (and
5015    ;; Check for long lines.
5016    (message-check 'long-lines
5017      (goto-char (point-min))
5018      (re-search-forward
5019       (concat "^" (regexp-quote mail-header-separator) "$"))
5020      (forward-line 1)
5021      (while (and
5022              (or (looking-at
5023                   mime-edit-tag-regexp)
5024                  (let ((p (point)))
5025                    (end-of-line)
5026                    (< (- (point) p) 80)))
5027              (zerop (forward-line 1))))
5028      (or (bolp)
5029          (eobp)
5030          (y-or-n-p
5031           "You have lines longer than 79 characters.  Really post? ")))
5032    ;; Check whether the article is empty.
5033    (message-check 'empty
5034      (goto-char (point-min))
5035      (re-search-forward
5036       (concat "^" (regexp-quote mail-header-separator) "$"))
5037      (forward-line 1)
5038      (let ((b (point)))
5039        (goto-char (point-max))
5040        (re-search-backward message-signature-separator nil t)
5041        (beginning-of-line)
5042        (or (re-search-backward "[^ \n\t]" b t)
5043            (if (message-gnksa-enable-p 'empty-article)
5044                (y-or-n-p "Empty article.  Really post? ")
5045              (message "Denied posting -- Empty article.")
5046              nil))))
5047    ;; Check for control characters.
5048    (message-check 'control-chars
5049      (if (re-search-forward
5050           (string-as-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5051           nil t)
5052          (y-or-n-p
5053           "The article contains control characters.  Really post? ")
5054        t))
5055    ;; Check 8bit characters.
5056    (message-check '8bit
5057      (message-check-8bit))
5058    ;; Check excessive size.
5059    (message-check 'size
5060      (if (> (buffer-size) 60000)
5061          (y-or-n-p
5062           (format "The article is %d octets long.  Really post? "
5063                   (buffer-size)))
5064        t))
5065    ;; Check whether any new text has been added.
5066    (message-check 'new-text
5067      (or
5068       (not message-checksum)
5069       (not (eq (message-checksum) message-checksum))
5070       (if (message-gnksa-enable-p 'quoted-text-only)
5071           (y-or-n-p
5072            "It looks like no new text has been added.  Really post? ")
5073         (message "Denied posting -- no new text has been added.")
5074         nil)))
5075    ;; Check the length of the signature.
5076    (message-check 'signature
5077      (goto-char (point-max))
5078      (if (> (count-lines (point) (point-max)) 5)
5079          (y-or-n-p
5080           (format
5081            "Your .sig is %d lines; it should be max 4.  Really post? "
5082            (1- (count-lines (point) (point-max)))))
5083        t))
5084    ;; Ensure that text follows last quoted portion.
5085    (message-check 'quoting-style
5086      (goto-char (point-max))
5087      (let ((no-problem t))
5088        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5089          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5090        (if no-problem
5091            t
5092          (if (message-gnksa-enable-p 'quoted-text-only)
5093              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5094            ;; Ensure that
5095            (goto-char (point-min))
5096            (re-search-forward
5097             (concat "^" (regexp-quote mail-header-separator) "$"))
5098            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5099                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5100              (message "Denied posting -- only quoted text.")
5101              nil)))))))
5102
5103 (defun message-check-mail-syntax ()
5104   "Check the syntax of the message."
5105   (save-excursion
5106     (save-restriction
5107       (widen)
5108       (and
5109        ;; We narrow to the headers and check them first.
5110        (save-excursion
5111          (save-restriction
5112            (message-narrow-to-headers)
5113            (message-check-mail-header-syntax)))
5114        ;; Check the body.
5115        (save-excursion
5116          (set-buffer message-edit-buffer)
5117          (message-check-mail-body-syntax))))))
5118
5119 (defun message-check-mail-header-syntax ()
5120   t)
5121
5122 (defun message-check-mail-body-syntax ()
5123   (and
5124    ;; Check 8bit characters.
5125    (message-check '8bit
5126      (message-check-8bit)
5127      )))
5128
5129 (defun message-check-8bit ()
5130   "Check the article contains 8bit characters."
5131   (save-excursion
5132     (set-buffer message-encoding-buffer)
5133     (message-narrow-to-headers)
5134     (let* ((case-fold-search t)
5135            (field-value (message-fetch-field "content-transfer-encoding")))
5136       (if (and field-value
5137                (member (downcase field-value) message-8bit-encoding-list))
5138           t
5139         (widen)
5140         (set-buffer (get-buffer-create " message syntax"))
5141         (erase-buffer)
5142         (goto-char (point-min))
5143         (set-buffer-multibyte nil)
5144         (insert-buffer-substring message-encoding-buffer)
5145         (goto-char (point-min))
5146         (if (re-search-forward "[^\x00-\x7f]" nil t)
5147             (y-or-n-p
5148              "The article contains 8bit characters.  Really post? ")
5149           t)))))
5150
5151 (defun message-checksum ()
5152   "Return a \"checksum\" for the current buffer."
5153   (let ((sum 0))
5154     (save-excursion
5155       (goto-char (point-min))
5156       (re-search-forward
5157        (concat "^" (regexp-quote mail-header-separator) "$"))
5158       (while (not (eobp))
5159         (when (not (looking-at "[ \t\n]"))
5160           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5161                             (char-after))))
5162         (forward-char 1)))
5163     sum))
5164
5165 (defun message-do-fcc ()
5166   "Process Fcc headers in the current buffer."
5167   (let ((case-fold-search t)
5168         (coding-system-for-write 'raw-text)
5169         list file
5170         (mml-externalize-attachments message-fcc-externalize-attachments))
5171     (save-excursion
5172       (save-restriction
5173         (message-narrow-to-headers)
5174         (setq file (message-fetch-field "fcc" t)))
5175       (when file
5176         (set-buffer (get-buffer-create " *message temp*"))
5177         (erase-buffer)
5178         (insert-buffer-substring message-encoding-buffer)
5179         (save-restriction
5180           (message-narrow-to-headers)
5181           (while (setq file (message-fetch-field "fcc"))
5182             (push file list)
5183             (message-remove-header "fcc" nil t)))
5184         (goto-char (point-min))
5185         (when (re-search-forward
5186                (concat "^" (regexp-quote mail-header-separator) "$")
5187                nil t)
5188           (replace-match "" t t))
5189         ;; Process FCC operations.
5190         (while list
5191           (setq file (pop list))
5192           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5193               ;; Pipe the article to the program in question.
5194               (call-process-region (point-min) (point-max) shell-file-name
5195                                    nil nil nil shell-command-switch
5196                                    (match-string 1 file))
5197             ;; Save the article.
5198             (setq file (expand-file-name file))
5199             (unless (file-exists-p (file-name-directory file))
5200               (make-directory (file-name-directory file) t))
5201             (if (and message-fcc-handler-function
5202                      (not (eq message-fcc-handler-function 'rmail-output)))
5203                 (funcall message-fcc-handler-function file)
5204               (if (and (file-readable-p file) (mail-file-babyl-p file))
5205                   (rmail-output file 1 nil t)
5206                 (let ((mail-use-rfc822 t))
5207                   (rmail-output file 1 t t))))))
5208         (kill-buffer (current-buffer))))))
5209
5210 (defun message-output (filename)
5211   "Append this article to Unix/babyl mail file FILENAME."
5212   (if (and (file-readable-p filename)
5213            (mail-file-babyl-p filename))
5214       (gnus-output-to-rmail filename t)
5215     (gnus-output-to-mail filename t)))
5216
5217 (defun message-cleanup-headers ()
5218   "Do various automatic cleanups of the headers."
5219   ;; Remove empty lines in the header.
5220   (save-restriction
5221     (message-narrow-to-headers)
5222     ;; Remove blank lines.
5223     (while (re-search-forward "^[ \t]*\n" nil t)
5224       (replace-match "" t t))
5225
5226     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5227     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5228     ;; embedded line breaks.
5229     (goto-char (point-min))
5230     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5231       (save-restriction
5232         (narrow-to-region
5233          (point)
5234          (if (re-search-forward "^[^ \t]" nil t)
5235              (match-beginning 0)
5236            (forward-line 1)
5237            (point)))
5238         (goto-char (point-min))
5239         (while (re-search-forward "\n[ \t]+" nil t)
5240           (replace-match " " t t))      ;No line breaks (too confusing)
5241         (goto-char (point-min))
5242         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5243           (replace-match "," t t))
5244         (goto-char (point-min))
5245         ;; Remove trailing commas.
5246         (when (re-search-forward ",+$" nil t)
5247           (replace-match "" t t))))))
5248
5249 (defun message-make-date (&optional now)
5250   "Make a valid data header.
5251 If NOW, use that time instead."
5252   (let ((system-time-locale "C"))
5253     (format-time-string "%a, %d %b %Y %T %z" now)))
5254
5255 (defun message-make-followup-subject (subject)
5256   "Make a followup Subject."
5257   (cond
5258    ((and (eq message-use-subject-re 'guess)
5259          (string-match message-subject-encoded-re-regexp subject))
5260     subject)
5261    (message-use-subject-re
5262     (concat "Re: " (message-strip-subject-re subject)))
5263    (t subject)))
5264
5265 (defun message-make-message-id ()
5266   "Make a unique Message-ID."
5267   (concat "<" (message-unique-id)
5268           (let ((psubject (save-excursion (message-fetch-field "subject")))
5269                 (psupersedes
5270                  (save-excursion (message-fetch-field "supersedes"))))
5271             (if (or
5272                  (and message-reply-headers
5273                       (mail-header-references message-reply-headers)
5274                       (mail-header-subject message-reply-headers)
5275                       psubject
5276                       (not (string=
5277                             (message-strip-subject-re
5278                              (mail-header-subject message-reply-headers))
5279                             (message-strip-subject-re psubject))))
5280                  (and psupersedes
5281                       (string-match "_-_@" psupersedes)))
5282                 "_-_" ""))
5283           "@" (message-make-fqdn) ">"))
5284
5285 (defvar message-unique-id-char nil)
5286
5287 ;; If you ever change this function, make sure the new version
5288 ;; cannot generate IDs that the old version could.
5289 ;; You might for example insert a "." somewhere (not next to another dot
5290 ;; or string boundary), or modify the "fsf" string.
5291 (defun message-unique-id ()
5292   ;; Don't use microseconds from (current-time), they may be unsupported.
5293   ;; Instead we use this randomly inited counter.
5294   (setq message-unique-id-char
5295         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5296            ;; (current-time) returns 16-bit ints,
5297            ;; and 2^16*25 just fits into 4 digits i base 36.
5298            (* 25 25)))
5299   (let ((tm (current-time)))
5300     (concat
5301      (if (memq system-type '(ms-dos emx vax-vms))
5302          (let ((user (downcase (user-login-name))))
5303            (while (string-match "[^a-z0-9_]" user)
5304              (aset user (match-beginning 0) ?_))
5305            user)
5306        (message-number-base36 (user-uid) -1))
5307      (message-number-base36 (+ (car tm)
5308                                (lsh (% message-unique-id-char 25) 16)) 4)
5309      (message-number-base36 (+ (nth 1 tm)
5310                                (lsh (/ message-unique-id-char 25) 16)) 4)
5311      ;; Append a given name, because while the generated ID is unique
5312      ;; to this newsreader, other newsreaders might otherwise generate
5313      ;; the same ID via another algorithm.
5314      ".fsf")))
5315
5316 (defun message-number-base36 (num len)
5317   (if (if (< len 0)
5318           (<= num 0)
5319         (= len 0))
5320       ""
5321     (concat (message-number-base36 (/ num 36) (1- len))
5322             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5323                                   (% num 36))))))
5324
5325 (defun message-make-organization ()
5326   "Make an Organization header."
5327   (let* ((organization
5328           (when message-user-organization
5329             (if (functionp message-user-organization)
5330                 (funcall message-user-organization)
5331               message-user-organization))))
5332     (with-temp-buffer
5333       (set-buffer-multibyte t)
5334       (cond ((stringp organization)
5335              (insert organization))
5336             ((and (eq t organization)
5337                   message-user-organization-file
5338                   (file-exists-p message-user-organization-file))
5339              (insert-file-contents message-user-organization-file)))
5340       (goto-char (point-min))
5341       (while (re-search-forward "[\t\n]+" nil t)
5342         (replace-match "" t t))
5343       (unless (zerop (buffer-size))
5344         (buffer-string)))))
5345
5346 (defun message-make-lines ()
5347   "Count the number of lines and return numeric string."
5348   (save-excursion
5349     (save-restriction
5350       (widen)
5351       (message-goto-body)
5352       (int-to-string (count-lines (point) (point-max))))))
5353
5354 (defun message-make-references ()
5355   "Return the References header for this message."
5356   (when message-reply-headers
5357     (let ((message-id (mail-header-message-id message-reply-headers))
5358           (references (mail-header-references message-reply-headers))
5359           new-references)
5360       (if (or references message-id)
5361           (concat (or references "") (and references " ")
5362                   (or message-id ""))
5363         nil))))
5364
5365 (defun message-make-in-reply-to ()
5366   "Return the In-Reply-To header for this message."
5367   (when message-reply-headers
5368     (let ((from (mail-header-from message-reply-headers))
5369           (date (mail-header-date message-reply-headers))
5370           (msg-id (mail-header-message-id message-reply-headers)))
5371       (when from
5372         (let ((name (std11-extract-address-components from)))
5373           (concat msg-id (if msg-id " (")
5374                   (or (car name)
5375                       (nth 1 name))
5376                   "'s message of \""
5377                   (if (or (not date) (string= date ""))
5378                       "(unknown date)" date)
5379                   "\"" (if msg-id ")")))))))
5380
5381 (defun message-make-distribution ()
5382   "Make a Distribution header."
5383   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5384     (cond ((functionp message-distribution-function)
5385            (funcall message-distribution-function))
5386           (t orig-distribution))))
5387
5388 (defun message-make-expires ()
5389   "Return an Expires header based on `message-expires'."
5390   (let ((current (current-time))
5391         (future (* 1.0 message-expires 60 60 24)))
5392     ;; Add the future to current.
5393     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5394     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5395     (message-make-date current)))
5396
5397 (defun message-make-path ()
5398   "Return uucp path."
5399   (let ((login-name (user-login-name)))
5400     (cond ((null message-user-path)
5401            (concat (system-name) "!" login-name))
5402           ((stringp message-user-path)
5403            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5404            (concat message-user-path "!" login-name))
5405           (t login-name))))
5406
5407 (defun message-make-from ()
5408   "Make a From header."
5409   (let* ((style message-from-style)
5410          (login (message-make-address))
5411          (fullname
5412           (or (and (boundp 'user-full-name)
5413                    user-full-name)
5414               (user-full-name))))
5415     (when (string= fullname "&")
5416       (setq fullname (user-login-name)))
5417     (with-temp-buffer
5418       (set-buffer-multibyte t)
5419       (cond
5420        ((or (null style)
5421             (equal fullname ""))
5422         (insert login))
5423        ((or (eq style 'angles)
5424             (and (not (eq style 'parens))
5425                  ;; Use angles if no quoting is needed, or if parens would
5426                  ;; need quoting too.
5427                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5428                      (let ((tmp (concat fullname nil)))
5429                        (while (string-match "([^()]*)" tmp)
5430                          (aset tmp (match-beginning 0) ?-)
5431                          (aset tmp (1- (match-end 0)) ?-))
5432                        (string-match "[\\()]" tmp)))))
5433         (insert fullname)
5434         (goto-char (point-min))
5435         ;; Look for a character that cannot appear unquoted
5436         ;; according to RFC 822.
5437         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5438           ;; Quote fullname, escaping specials.
5439           (goto-char (point-min))
5440           (insert "\"")
5441           (while (re-search-forward "[\"\\]" nil 1)
5442             (replace-match "\\\\\\&" t))
5443           (insert "\""))
5444         (insert " <" login ">"))
5445        (t                               ; 'parens or default
5446         (insert login " (")
5447         (let ((fullname-start (point)))
5448           (insert fullname)
5449           (goto-char fullname-start)
5450           ;; RFC 822 says \ and nonmatching parentheses
5451           ;; must be escaped in comments.
5452           ;; Escape every instance of ()\ ...
5453           (while (re-search-forward "[()\\]" nil 1)
5454             (replace-match "\\\\\\&" t))
5455           ;; ... then undo escaping of matching parentheses,
5456           ;; including matching nested parentheses.
5457           (goto-char fullname-start)
5458           (while (re-search-forward
5459                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5460                   nil 1)
5461             (replace-match "\\1(\\3)" t)
5462             (goto-char fullname-start)))
5463         (insert ")")))
5464       (buffer-string))))
5465
5466 (defun message-make-sender ()
5467   "Return the \"real\" user address.
5468 This function tries to ignore all user modifications, and
5469 give as trustworthy answer as possible."
5470   (concat (user-login-name) "@" (system-name)))
5471
5472 (defun message-make-address ()
5473   "Make the address of the user."
5474   (or (message-user-mail-address)
5475       (concat (user-login-name) "@" (message-make-domain))))
5476
5477 (defun message-user-mail-address ()
5478   "Return the pertinent part of `user-mail-address'."
5479   (when (and user-mail-address
5480              (string-match "@.*\\." user-mail-address))
5481     (if (string-match " " user-mail-address)
5482         (nth 1 (std11-extract-address-components user-mail-address))
5483       user-mail-address)))
5484
5485 (defun message-sendmail-envelope-from ()
5486   "Return the envelope from."
5487   (cond ((eq message-sendmail-envelope-from 'header)
5488          (nth 1 (std11-extract-address-components
5489                  (message-fetch-field "from"))))
5490         ((stringp message-sendmail-envelope-from)
5491          message-sendmail-envelope-from)
5492         (t
5493          (message-make-address))))
5494
5495 (defun message-make-fqdn ()
5496   "Return user's fully qualified domain name."
5497   (let* ((system-name (system-name))
5498          (user-mail (message-user-mail-address))
5499          (user-domain
5500           (if (and user-mail
5501                    (string-match "@\\(.*\\)\\'" user-mail))
5502               (match-string 1 user-mail)))
5503          (case-fold-search t))
5504     (cond
5505      ((and message-user-fqdn
5506            (stringp message-user-fqdn)
5507            (string-match message-valid-fqdn-regexp message-user-fqdn)
5508            (not (string-match message-bogus-system-names message-user-fqdn)))
5509       message-user-fqdn)
5510      ;; `message-user-fqdn' seems to be valid
5511      ((and (string-match message-valid-fqdn-regexp system-name)
5512            (not (string-match message-bogus-system-names system-name)))
5513       ;; `system-name' returned the right result.
5514       system-name)
5515      ;; Try `mail-host-address'.
5516      ((and (boundp 'mail-host-address)
5517            (stringp mail-host-address)
5518            (string-match message-valid-fqdn-regexp mail-host-address)
5519            (not (string-match message-bogus-system-names mail-host-address)))
5520       mail-host-address)
5521      ;; We try `user-mail-address' as a backup.
5522      ((and user-domain
5523            (stringp user-domain)
5524            (string-match message-valid-fqdn-regexp user-domain)
5525            (not (string-match message-bogus-system-names user-domain)))
5526       user-domain)
5527      ;; Default to this bogus thing.
5528      (t
5529       (concat system-name
5530               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5531
5532 (defun message-make-host-name ()
5533   "Return the name of the host."
5534   (let ((fqdn (message-make-fqdn)))
5535     (string-match "^[^.]+\\." fqdn)
5536     (substring fqdn 0 (1- (match-end 0)))))
5537
5538 (defun message-make-domain ()
5539   "Return the domain name."
5540   (or mail-host-address
5541       (message-make-fqdn)))
5542
5543 (defun message-to-list-only ()
5544   "Send a message to the list only.
5545 Remove all addresses but the list address from To and Cc headers."
5546   (interactive)
5547   (let ((listaddr (message-make-mail-followup-to t)))
5548     (when listaddr
5549       (save-excursion
5550         (message-remove-header "to")
5551         (message-remove-header "cc")
5552         (message-position-on-field "To" "X-Draft-From")
5553         (insert listaddr)))))
5554
5555 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5556   "Return the Mail-Followup-To header.
5557 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5558 subscribed address (and not the additional To and Cc header contents)."
5559   (let* ((case-fold-search t)
5560          (to (message-fetch-field "To"))
5561          (cc (message-fetch-field "cc"))
5562          (msg-recipients (concat to (and to cc ", ") cc))
5563          (recipients
5564           (mapcar 'mail-strip-quoted-names
5565                   (message-tokenize-header msg-recipients)))
5566          (file-regexps
5567           (if message-subscribed-address-file
5568               (let (begin end item re)
5569                 (save-excursion
5570                   (with-temp-buffer
5571                     (insert-file-contents message-subscribed-address-file)
5572                     (while (not (eobp))
5573                       (setq begin (point))
5574                       (forward-line 1)
5575                       (setq end (point))
5576                       (if (bolp) (setq end (1- end)))
5577                       (setq item (regexp-quote (buffer-substring begin end)))
5578                       (if re (setq re (concat re "\\|" item))
5579                         (setq re (concat "\\`\\(" item))))
5580                     (and re (list (concat re "\\)\\'"))))))))
5581          (mft-regexps (apply 'append message-subscribed-regexps
5582                              (mapcar 'regexp-quote
5583                                      message-subscribed-addresses)
5584                              file-regexps
5585                              (mapcar 'funcall
5586                                      message-subscribed-address-functions))))
5587     (save-match-data
5588       (let ((subscribed-lists nil)
5589             (list
5590              (loop for recipient in recipients
5591                when (loop for regexp in mft-regexps
5592                       when (string-match regexp recipient) return t)
5593                return recipient)))
5594         (when list
5595           (if only-show-subscribed
5596               list
5597             msg-recipients))))))
5598
5599 ;; Dummy to avoid byte-compile warning.
5600 (defvar mule-version)
5601 (defvar emacs-beta-version)
5602 (defvar xemacs-codename)
5603 (defvar gnus-inviolable-extended-version)
5604
5605 (defun message-make-user-agent ()
5606   "Return user-agent info if the value `message-user-agent' is non-nil. If the
5607 \"User-Agent\" field has already exist, remove it."
5608   (when message-user-agent
5609     (save-excursion
5610       (goto-char (point-min))
5611       (let ((case-fold-search t))
5612         (when (re-search-forward "^User-Agent:[\t ]*" nil t)
5613           (delete-region (match-beginning 0) (1+ (std11-field-end)))))))
5614   message-user-agent)
5615
5616 (defun message-idna-to-ascii-rhs-1 (header)
5617   "Interactively potentially IDNA encode domain names in HEADER."
5618   (let ((field (message-fetch-field header))
5619         rhs ace  address)
5620     (when field
5621       (dolist (address (mail-header-parse-addresses field))
5622         (setq address (car address)
5623               rhs (downcase (or (cadr (split-string address "@")) ""))
5624               ace (downcase (idna-to-ascii rhs)))
5625         (when (and (not (equal rhs ace))
5626                    (or (not (eq message-use-idna 'ask))
5627                        (y-or-n-p (format "Replace %s with %s? " rhs ace))))
5628           (goto-char (point-min))
5629           (while (re-search-forward (concat "^" header ":") nil t)
5630             (message-narrow-to-field)
5631             (while (search-forward (concat "@" rhs) nil t)
5632               (replace-match (concat "@" ace) t t))
5633             (goto-char (point-max))
5634             (widen)))))))
5635
5636 (defun message-idna-to-ascii-rhs ()
5637   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5638 See `message-idna-encode'."
5639   (interactive)
5640   (when message-use-idna
5641     (save-excursion
5642       (save-restriction
5643         (message-narrow-to-head)
5644         (message-idna-to-ascii-rhs-1 "From")
5645         (message-idna-to-ascii-rhs-1 "To")
5646         (message-idna-to-ascii-rhs-1 "Reply-To")
5647         (message-idna-to-ascii-rhs-1 "Cc")))))
5648
5649 (defun message-generate-headers (headers)
5650   "Prepare article HEADERS.
5651 Headers already prepared in the buffer are not modified."
5652   (setq headers (append headers message-required-headers))
5653   (save-restriction
5654     (message-narrow-to-headers)
5655     (let* ((Date (message-make-date))
5656            (Message-ID (message-make-message-id))
5657            (Organization (message-make-organization))
5658            (From (message-make-from))
5659            (Path (message-make-path))
5660            (Subject nil)
5661            (Newsgroups nil)
5662            (In-Reply-To (message-make-in-reply-to))
5663            (References (message-make-references))
5664            (To nil)
5665            (Distribution (message-make-distribution))
5666            (Lines (message-make-lines))
5667            (User-Agent (message-make-user-agent))
5668            (Expires (message-make-expires))
5669            (case-fold-search t)
5670            (optionalp nil)
5671            header value elem header-string)
5672       ;; First we remove any old generated headers.
5673       (let ((headers message-deletable-headers))
5674         (unless (buffer-modified-p)
5675           (setq headers (delq 'Message-ID (copy-sequence headers))))
5676         (while headers
5677           (goto-char (point-min))
5678           (and (re-search-forward
5679                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5680                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5681                (message-delete-line))
5682           (pop headers)))
5683       ;; Go through all the required headers and see if they are in the
5684       ;; articles already.  If they are not, or are empty, they are
5685       ;; inserted automatically - except for Subject, Newsgroups and
5686       ;; Distribution.
5687       (while headers
5688         (goto-char (point-min))
5689         (setq elem (pop headers))
5690         (if (consp elem)
5691             (if (eq (car elem) 'optional)
5692                 (setq header (cdr elem)
5693                       optionalp t)
5694               (setq header (car elem)))
5695           (setq header elem))
5696         (setq header-string  (if (stringp header)
5697                                  header
5698                                (symbol-name header)))
5699         (when (or (not (re-search-forward
5700                         (concat "^"
5701                                 (regexp-quote (downcase header-string))
5702                                 ":")
5703                         nil t))
5704                   (progn
5705                     ;; The header was found.  We insert a space after the
5706                     ;; colon, if there is none.
5707                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5708                     ;; Find out whether the header is empty.
5709                     (looking-at "[ \t]*\n[^ \t]")))
5710           ;; So we find out what value we should insert.
5711           (setq value
5712                 (cond
5713                  ((and (consp elem)
5714                        (eq (car elem) 'optional)
5715                        (not (member header-string message-inserted-headers)))
5716                   ;; This is an optional header.  If the cdr of this
5717                   ;; is something that is nil, then we do not insert
5718                   ;; this header.
5719                   (setq header (cdr elem))
5720                   (or (and (functionp (cdr elem))
5721                            (funcall (cdr elem)))
5722                       (and (boundp (cdr elem))
5723                            (symbol-value (cdr elem)))))
5724                  ((consp elem)
5725                   ;; The element is a cons.  Either the cdr is a
5726                   ;; string to be inserted verbatim, or it is a
5727                   ;; function, and we insert the value returned from
5728                   ;; this function.
5729                   (or (and (stringp (cdr elem))
5730                            (cdr elem))
5731                       (and (functionp (cdr elem))
5732                            (funcall (cdr elem)))))
5733                  ((and (boundp header)
5734                        (symbol-value header))
5735                   ;; The element is a symbol.  We insert the value
5736                   ;; of this symbol, if any.
5737                   (symbol-value header))
5738                  ((not (message-check-element header))
5739                   ;; We couldn't generate a value for this header,
5740                   ;; so we just ask the user.
5741                   (read-from-minibuffer
5742                    (format "Empty header for %s; enter value: " header)))))
5743           ;; Finally insert the header.
5744           (when (and value
5745                      (not (equal value "")))
5746             (save-excursion
5747               (if (bolp)
5748                   (progn
5749                     ;; This header didn't exist, so we insert it.
5750                     (goto-char (point-max))
5751                     (let ((formatter
5752                            (cdr (assq header message-header-format-alist))))
5753                       (if formatter
5754                           (funcall formatter header value)
5755                         (insert header-string ": " value))
5756                       (goto-char (message-fill-field))
5757                       ;; We check whether the value was ended by a
5758                       ;; newline.  If not, we insert one.
5759                       (unless (bolp)
5760                         (insert "\n"))
5761                       (forward-line -1)))
5762                 ;; The value of this header was empty, so we clear
5763                 ;; totally and insert the new value.
5764                 (delete-region (point) (point-at-eol))
5765                 ;; If the header is optional, and the header was
5766                 ;; empty, we can't insert it anyway.
5767                 (unless optionalp
5768                   (push header-string message-inserted-headers)
5769                   (insert value)
5770                   (message-fill-field)))
5771               ;; Add the deletable property to the headers that require it.
5772               (and (memq header message-deletable-headers)
5773                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5774                    (add-text-properties
5775                     (point) (match-end 0)
5776                     '(message-deletable t face italic) (current-buffer)))))))
5777       ;; Insert new Sender if the From is strange.
5778       (let ((from (message-fetch-field "from"))
5779             (sender (message-fetch-field "sender"))
5780             (secure-sender (message-make-sender)))
5781         (when (and from
5782                    (not (message-check-element 'sender))
5783                    (not (string=
5784                          (downcase
5785                           (cadr (std11-extract-address-components from)))
5786                          (downcase secure-sender)))
5787                    (or (null sender)
5788                        (not
5789                         (string=
5790                          (downcase
5791                           (cadr (std11-extract-address-components sender)))
5792                          (downcase secure-sender)))))
5793           (goto-char (point-min))
5794           ;; Rename any old Sender headers to Original-Sender.
5795           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5796             (beginning-of-line)
5797             (insert "Original-")
5798             (beginning-of-line))
5799           (when (or (message-news-p)
5800                     (string-match "@.+\\.." secure-sender))
5801             (insert "Sender: " secure-sender "\n"))))
5802       ;; Check for IDNA
5803       (message-idna-to-ascii-rhs))))
5804
5805 (defun message-insert-courtesy-copy ()
5806   "Insert a courtesy message in mail copies of combined messages."
5807   (let (newsgroups)
5808     (save-excursion
5809       (save-restriction
5810         (message-narrow-to-headers)
5811         (when (setq newsgroups (message-fetch-field "newsgroups"))
5812           (goto-char (point-max))
5813           (insert "Posted-To: " newsgroups "\n")))
5814       (forward-line 1)
5815       (when message-courtesy-message
5816         (cond
5817          ((string-match "%s" message-courtesy-message)
5818           (insert (format message-courtesy-message newsgroups)))
5819          (t
5820           (insert message-courtesy-message)))))))
5821
5822 ;;;
5823 ;;; Setting up a message buffer
5824 ;;;
5825
5826 (defun message-skip-to-next-address ()
5827   (let ((end (save-excursion
5828                (message-next-header)
5829                (point)))
5830         quoted char)
5831     (when (looking-at ",")
5832       (forward-char 1))
5833     (while (and (not (= (point) end))
5834                 (or (not (eq char ?,))
5835                     quoted))
5836       (skip-chars-forward "^,\"" (point-max))
5837       (when (eq (setq char (following-char)) ?\")
5838         (setq quoted (not quoted)))
5839       (unless (= (point) end)
5840         (forward-char 1)))
5841     (skip-chars-forward " \t\n")))
5842
5843 (defun message-fill-address (header value)
5844   (insert (capitalize (symbol-name header))
5845           ": "
5846           (if (consp value) (car value) value)
5847           "\n")
5848   (message-fill-field-address))
5849
5850 (defun message-fill-references (header value)
5851   (insert (capitalize (symbol-name header))
5852           ": "
5853           (std11-fill-msg-id-list-string
5854            (if (consp value) (car value) value))))
5855
5856 (defun message-split-line ()
5857   "Split current line, moving portion beyond point vertically down.
5858 If the current line has `message-yank-prefix', insert it on the new line."
5859   (interactive "*")
5860   (condition-case nil
5861       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
5862     (error
5863      (split-line))))
5864
5865 (defun message-insert-header (header value)
5866   (insert (capitalize (symbol-name header))
5867           ": "
5868           (if (consp value) (car value) value)))
5869
5870 (defun message-field-name ()
5871   (save-excursion
5872     (goto-char (point-min))
5873     (when (looking-at "\\([^:]+\\):")
5874       (intern (capitalize (match-string 1))))))
5875
5876 (defun message-fill-field ()
5877   (save-excursion
5878     (save-restriction
5879       (message-narrow-to-field)
5880       (let ((field-name (message-field-name)))
5881         (funcall (or (cadr (assq field-name message-field-fillers))
5882                      'message-fill-field-general)))
5883       (point-max))))
5884
5885 (defun message-fill-field-address ()
5886   (while (not (eobp))
5887     (message-skip-to-next-address)
5888     (let (last)
5889       (if (and (> (current-column) 78)
5890                last)
5891           (progn
5892             (save-excursion
5893               (goto-char last)
5894               (insert "\n\t"))
5895             (setq last (1+ (point))))
5896         (setq last (1+ (point)))))))
5897
5898 (defun message-fill-field-general ()
5899   (let ((begin (point))
5900         (fill-column 78)
5901         (fill-prefix " "))
5902     (while (and (search-forward "\n" nil t)
5903                 (not (eobp)))
5904       (replace-match " " t t))
5905     (fill-region-as-paragraph begin (point-max))
5906     ;; Tapdance around looong Message-IDs.
5907     (forward-line -1)
5908     (when (looking-at "[ \t]*$")
5909       (message-delete-line))
5910     (goto-char begin)
5911     (search-forward ":" nil t)
5912     (when (looking-at "\n[ \t]+")
5913       (replace-match " " t t))
5914     (goto-char (point-max))))
5915
5916 (defun message-shorten-1 (list cut surplus)
5917   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5918   (setcdr (nthcdr (- cut 2) list)
5919           (nthcdr (+ (- cut 2) surplus 1) list)))
5920
5921 (defun message-shorten-references (header references)
5922   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5923 When sending via news, also check that the REFERENCES are less
5924 than 988 characters long, and if they are not, trim them until
5925 they are."
5926   (let ((maxcount 21)
5927         (count 0)
5928         (cut 2)
5929         refs)
5930     (with-temp-buffer
5931       (insert references)
5932       (goto-char (point-min))
5933       ;; Cons a list of valid references.
5934       (while (re-search-forward "<[^>]+>" nil t)
5935         (push (match-string 0) refs))
5936       (setq refs (nreverse refs)
5937             count (length refs)))
5938
5939     ;; If the list has more than MAXCOUNT elements, trim it by
5940     ;; removing the CUTth element and the required number of
5941     ;; elements that follow.
5942     (when (> count maxcount)
5943       (let ((surplus (- count maxcount)))
5944         (message-shorten-1 refs cut surplus)
5945         (decf count surplus)))
5946
5947     ;; When sending via news, make sure the total folded length will
5948     ;; be less than 998 characters.  This is to cater to broken INN
5949     ;; 2.3 which counts the total number of characters in a header
5950     ;; rather than the physical line length of each line, as it should.
5951     ;;
5952     ;; This hack should be removed when it's believed than INN 2.3 is
5953     ;; no longer widely used.
5954     ;;
5955     ;; At this point the headers have not been generated, thus we use
5956     ;; message-this-is-news directly.
5957     (when message-this-is-news
5958       (while (< 998
5959                 (with-temp-buffer
5960                   (message-insert-header
5961                    header (mapconcat #'identity refs " "))
5962                   (buffer-size)))
5963         (message-shorten-1 refs cut 1)))
5964     ;; Finally, collect the references back into a string and insert
5965     ;; it into the buffer.
5966     (message-insert-header header (mapconcat #'identity refs " "))))
5967
5968 (defun message-position-point ()
5969   "Move point to where the user probably wants to find it."
5970   (message-narrow-to-headers)
5971   (cond
5972    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5973     (search-backward ":" )
5974     (widen)
5975     (forward-char 1)
5976     (if (eq (char-after) ? )
5977         (forward-char 1)
5978       (insert " ")))
5979    (t
5980     (goto-char (point-max))
5981     (widen)
5982     (forward-line 1)
5983     (unless (looking-at "$")
5984       (forward-line 2)))
5985    (sit-for 0)))
5986
5987 (defcustom message-beginning-of-line t
5988   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5989  goes to beginning of header values."
5990   :version "22.1"
5991   :group 'message-buffers
5992   :link '(custom-manual "(message)Movement")
5993   :type 'boolean)
5994
5995 (defun message-beginning-of-line (&optional n)
5996   "Move point to beginning of header value or to beginning of line.
5997 The prefix argument N is passed directly to `beginning-of-line'.
5998
5999 This command is identical to `beginning-of-line' if point is
6000 outside the message header or if the option `message-beginning-of-line'
6001 is nil.
6002
6003 If point is in the message header and on a (non-continued) header
6004 line, move point to the beginning of the header value or the beginning of line,
6005 whichever is closer.  If point is already at beginning of line, move point to
6006 beginning of header value.  Therefore, repeated calls will toggle point
6007 between beginning of field and beginning of line."
6008   (interactive "p")
6009   (let ((zrs 'zmacs-region-stays))
6010     (when (and (interactive-p) (boundp zrs))
6011       (set zrs t)))
6012   (if (and message-beginning-of-line
6013            (message-point-in-header-p))
6014       (let* ((here (point))
6015              (bol (progn (beginning-of-line n) (point)))
6016              (eol (point-at-eol))
6017              (eoh (re-search-forward ": *" eol t)))
6018         (goto-char
6019          (if (and eoh (or (< eoh here) (= bol here)))
6020              eoh bol)))
6021     (beginning-of-line n)))
6022
6023 (defun message-buffer-name (type &optional to group)
6024   "Return a new (unique) buffer name based on TYPE and TO."
6025   (cond
6026    ;; Generate a new buffer name The Message Way.
6027    ((eq message-generate-new-buffers 'unique)
6028     (generate-new-buffer-name
6029      (concat "*" type
6030              (if to
6031                  (concat " to "
6032                          (or (car (std11-extract-address-components to))
6033                              to) "")
6034                "")
6035              (if (and group (not (string= group ""))) (concat " on " group) "")
6036              "*")))
6037    ;; Check whether `message-generate-new-buffers' is a function,
6038    ;; and if so, call it.
6039    ((functionp message-generate-new-buffers)
6040     (funcall message-generate-new-buffers type to group))
6041    ((eq message-generate-new-buffers 'unsent)
6042     (generate-new-buffer-name
6043      (concat "*unsent " type
6044              (if to
6045                  (concat " to "
6046                          (or (car (std11-extract-address-components to))
6047                              to) "")
6048                "")
6049              (if (and group (not (string= group ""))) (concat " on " group) "")
6050              "*")))
6051    ;; Use standard name.
6052    (t
6053     (format "*%s message*" type))))
6054
6055 (defmacro message-pop-to-buffer-1 (buffer)
6056   `(if pop-up-frames
6057        (let (special-display-buffer-names
6058              special-display-regexps
6059              same-window-buffer-names
6060              same-window-regexps)
6061          (pop-to-buffer ,buffer))
6062      (pop-to-buffer ,buffer)))
6063
6064 (defun message-pop-to-buffer (name)
6065   "Pop to buffer NAME, and warn if it already exists and is modified."
6066   (let ((buffer (get-buffer name))
6067         (pop-up-frames (and (static-if (featurep 'xemacs)
6068                                 (device-on-window-system-p)
6069                               window-system)
6070                             message-use-multi-frames)))
6071     (if (and buffer
6072              (buffer-name buffer))
6073         (progn
6074           (message-pop-to-buffer-1 buffer)
6075           (when (and (buffer-modified-p)
6076                      (not (y-or-n-p
6077                            "Message already being composed; erase? ")))
6078             (error "Message being composed")))
6079       (message-pop-to-buffer-1 name))
6080     (erase-buffer)
6081     (message-mode)
6082     (when pop-up-frames
6083       (set (make-local-variable 'message-original-frame) (selected-frame)))))
6084
6085 (defun message-do-send-housekeeping ()
6086   "Kill old message buffers."
6087   ;; We might have sent this buffer already.  Delete it from the
6088   ;; list of buffers.
6089   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6090   (while (and message-max-buffers
6091               message-buffer-list
6092               (>= (length message-buffer-list) message-max-buffers))
6093     ;; Kill the oldest buffer -- unless it has been changed.
6094     (let ((buffer (pop message-buffer-list)))
6095       (when (and (buffer-name buffer)
6096                  (not (buffer-modified-p buffer)))
6097         (kill-buffer buffer))))
6098   ;; Rename the buffer.
6099   (if message-send-rename-function
6100       (funcall message-send-rename-function)
6101     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6102     (when (string-match
6103            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6104            (buffer-name))
6105       (let ((name (match-string 2 (buffer-name)))
6106             to group)
6107         (if (not (or (null name)
6108                      (string-equal name "mail")
6109                      (string-equal name "posting")))
6110             (setq name (concat "*sent " name "*"))
6111           (message-narrow-to-headers)
6112           (setq to (message-fetch-field "to"))
6113           (setq group (message-fetch-field "newsgroups"))
6114           (widen)
6115           (setq name
6116                 (cond
6117                  (to (concat "*sent mail to "
6118                              (or (car (std11-extract-address-components to))
6119                                  to) "*"))
6120                  ((and group (not (string= group "")))
6121                   (concat "*sent posting on " group "*"))
6122                  (t "*sent mail*"))))
6123         (unless (string-equal name (buffer-name))
6124           (rename-buffer name t)))))
6125   ;; Push the current buffer onto the list.
6126   (when message-max-buffers
6127     (setq message-buffer-list
6128           (nconc message-buffer-list (list (current-buffer))))))
6129
6130 (defun message-mail-user-agent ()
6131   (let ((mua (cond
6132               ((not message-mail-user-agent) nil)
6133               ((eq message-mail-user-agent t) mail-user-agent)
6134               (t message-mail-user-agent))))
6135     (if (memq mua '(message-user-agent gnus-user-agent))
6136         nil
6137       mua)))
6138
6139 (defun message-setup (headers &optional replybuffer actions switch-function)
6140   (let ((mua (message-mail-user-agent))
6141         subject to field yank-action)
6142     (if (not (and message-this-is-mail mua))
6143         (message-setup-1 headers replybuffer actions)
6144       (if replybuffer
6145           (setq yank-action (list 'insert-buffer replybuffer)))
6146       (setq headers (copy-sequence headers))
6147       (setq field (assq 'Subject headers))
6148       (when field
6149         (setq subject (cdr field))
6150         (setq headers (delq field headers)))
6151       (setq field (assq 'To headers))
6152       (when field
6153         (setq to (cdr field))
6154         (setq headers (delq field headers)))
6155       (let ((mail-user-agent mua))
6156         (compose-mail to subject
6157                       (mapcar (lambda (item)
6158                                 (cons
6159                                  (format "%s" (car item))
6160                                  (cdr item)))
6161                               headers)
6162                       nil switch-function yank-action actions)))))
6163
6164 (defun message-headers-to-generate (headers included-headers excluded-headers)
6165   "Return a list that includes all headers from HEADERS.
6166 If INCLUDED-HEADERS is a list, just include those headers.  If if is
6167 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6168 are not included."
6169   (let ((result nil)
6170         header-name)
6171     (dolist (header headers)
6172       (setq header-name (cond
6173                          ((and (consp header)
6174                                (eq (car header) 'optional))
6175                           ;; On the form (optional . Header)
6176                           (cdr header))
6177                          ((consp header)
6178                           ;; On the form (Header . function)
6179                           (car header))
6180                          (t
6181                           ;; Just a Header.
6182                           header)))
6183       (when (and (not (memq header-name excluded-headers))
6184                  (or (eq included-headers t)
6185                      (memq header-name included-headers)))
6186         (push header result)))
6187     (nreverse result)))
6188
6189 (defun message-setup-1 (headers &optional replybuffer actions)
6190   (dolist (action actions)
6191     (condition-case nil
6192         (add-to-list 'message-send-actions
6193                      `(apply ',(car action) ',(cdr action)))))
6194   (setq message-reply-buffer
6195         (or (message-get-parameter 'reply-buffer)
6196             replybuffer))
6197   (goto-char (point-min))
6198   ;; Insert all the headers.
6199   (mail-header-format
6200    (let ((h headers)
6201          (alist message-header-format-alist))
6202      (while h
6203        (unless (assq (caar h) message-header-format-alist)
6204          (push (list (caar h)) alist))
6205        (pop h))
6206      alist)
6207    headers)
6208   (delete-region (point) (progn (forward-line -1) (point)))
6209   (when message-default-headers
6210     (insert message-default-headers)
6211     (or (bolp) (insert ?\n)))
6212   (insert mail-header-separator "\n")
6213   (forward-line -1)
6214   (when (message-news-p)
6215     (when message-default-news-headers
6216       (insert message-default-news-headers)
6217       (or (bolp) (insert ?\n)))
6218     (when message-generate-headers-first
6219       (message-generate-headers
6220        (message-headers-to-generate
6221         (append message-required-news-headers
6222                 message-required-headers)
6223         message-generate-headers-first
6224         '(Lines Subject)))))
6225   (when (message-mail-p)
6226     (when message-default-mail-headers
6227       (insert message-default-mail-headers)
6228       (or (bolp) (insert ?\n)))
6229     (save-restriction
6230       (message-narrow-to-headers)
6231       (if (and replybuffer
6232                message-alternative-emails)
6233           (message-use-alternative-email-as-from)))
6234     (when message-generate-headers-first
6235       (message-generate-headers
6236        (message-headers-to-generate
6237         (append message-required-mail-headers
6238                 message-required-headers)
6239         message-generate-headers-first
6240         '(Lines Subject)))))
6241   (run-hooks 'message-signature-setup-hook)
6242   (message-insert-signature)
6243   (save-restriction
6244     (message-narrow-to-headers)
6245     (run-hooks 'message-header-setup-hook))
6246   (set-buffer-modified-p nil)
6247   (setq buffer-undo-list nil)
6248   (when message-generate-hashcash
6249     ;; Generate hashcash headers for recipients already known
6250     (mail-add-payment-async))
6251   (run-hooks 'message-setup-hook)
6252   (message-position-point)
6253   (undo-boundary))
6254
6255 (defun message-set-auto-save-file-name ()
6256   "Associate the message buffer with a file in the drafts directory."
6257   (when message-auto-save-directory
6258     (unless (file-directory-p
6259              (directory-file-name message-auto-save-directory))
6260       (make-directory message-auto-save-directory t))
6261     (if (gnus-alive-p)
6262         (setq message-draft-article
6263               (nndraft-request-associate-buffer "drafts"))
6264       (setq buffer-file-name (expand-file-name
6265                               (if (memq system-type
6266                                         '(ms-dos ms-windows windows-nt
6267                                                  cygwin cygwin32 win32 w32
6268                                                  mswindows))
6269                                   "message"
6270                                 "*message*")
6271                               message-auto-save-directory))
6272       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6273     (clear-visited-file-modtime)
6274     (setq buffer-file-coding-system message-draft-coding-system)))
6275
6276 (defun message-disassociate-draft ()
6277   "Disassociate the message buffer from the drafts directory."
6278   (when message-draft-article
6279     (nndraft-request-expire-articles
6280      (list message-draft-article) "drafts" nil t)))
6281
6282 (defun message-insert-headers ()
6283   "Generate the headers for the article."
6284   (interactive)
6285   (save-excursion
6286     (save-restriction
6287       (message-narrow-to-headers)
6288       (when (message-news-p)
6289         (message-generate-headers
6290          (delq 'Lines
6291                (delq 'Subject
6292                      (copy-sequence message-required-news-headers)))))
6293       (when (message-mail-p)
6294         (message-generate-headers
6295          (delq 'Lines
6296                (delq 'Subject
6297                      (copy-sequence message-required-mail-headers))))))))
6298
6299 \f
6300
6301 ;;;
6302 ;;; Commands for interfacing with message
6303 ;;;
6304
6305 ;;;###autoload
6306 (defun message-mail (&optional to subject
6307                                other-headers continue switch-function
6308                                yank-action send-actions)
6309   "Start editing a mail message to be sent.
6310 OTHER-HEADERS is an alist of header/value pairs."
6311   (interactive)
6312   (let ((message-this-is-mail t) replybuffer)
6313     (unless (message-mail-user-agent)
6314       (message-pop-to-buffer (message-buffer-name "mail" to)))
6315     ;; FIXME: message-mail should do something if YANK-ACTION is not
6316     ;; insert-buffer.
6317     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6318          (setq replybuffer (nth 1 yank-action)))
6319     (message-setup
6320      (nconc
6321       `((To . ,(or to "")) (Subject . ,(or subject "")))
6322       (when other-headers other-headers))
6323      replybuffer send-actions)
6324     ;; FIXME: Should return nil if failure.
6325     t))
6326
6327 ;;;###autoload
6328 (defun message-news (&optional newsgroups subject)
6329   "Start editing a news article to be sent."
6330   (interactive)
6331   (let ((message-this-is-news t))
6332     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6333     (message-setup `((Newsgroups . ,(or newsgroups ""))
6334                      (Subject . ,(or subject ""))))))
6335
6336 (defun message-get-reply-headers (wide &optional to-address address-headers)
6337   (let (follow-to mct never-mct to cc author mft recipients extra)
6338     ;; Find all relevant headers we need.
6339     (save-restriction
6340       (message-narrow-to-headers-or-head)
6341       (let ((mrt (when message-use-mail-reply-to
6342                    (message-fetch-field "mail-reply-to")))
6343             (reply-to (message-fetch-field "reply-to")))
6344         ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6345         ;; message-header-synonyms.
6346         (setq to (or (message-fetch-field "to")
6347                      (and (loop for synonym in message-header-synonyms
6348                                 when (memq 'Original-To synonym)
6349                                 return t)
6350                           (message-fetch-field "original-to")))
6351               cc (message-fetch-field "cc")
6352               extra (when message-extra-wide-headers
6353                       (mapconcat 'identity
6354                                  (mapcar 'message-fetch-field
6355                                          message-extra-wide-headers)
6356                                  ", "))
6357               mct (when message-use-mail-copies-to
6358                     (message-fetch-field "mail-copies-to"))
6359               author (or mrt
6360                          reply-to
6361                          (message-fetch-field "from")
6362                          "")
6363               mft (when (and (not (or to-address mrt reply-to))
6364                              message-use-mail-followup-to)
6365                     (message-fetch-field "mail-followup-to")))))
6366
6367     (save-match-data
6368       ;; Handle special values of Mail-Copies-To.
6369       (when mct
6370         (cond ((or (equal (downcase mct) "never")
6371                    (equal (downcase mct) "nobody"))
6372                (when (or (not (eq message-use-mail-copies-to 'ask))
6373                          (message-y-or-n-p
6374                           (concat "Obey Mail-Copies-To: never? ") t "\
6375 You should normally obey the Mail-Copies-To: header.
6376
6377         `Mail-Copies-To: " mct "'
6378 directs you not to send your response to the author."))
6379                  (setq never-mct t))
6380                (setq mct nil))
6381               ((or (equal (downcase mct) "always")
6382                    (equal (downcase mct) "poster"))
6383                (if (or (not (eq message-use-mail-copies-to 'ask))
6384                        (message-y-or-n-p
6385                         (concat "Obey Mail-Copies-To: always? ") t "\
6386 You should normally obey the Mail-Copies-To: header.
6387
6388         `Mail-Copies-To: " mct "'
6389 sends a copy of your response to the author."))
6390                    (setq mct author)
6391                  (setq mct nil)))
6392               ((and (eq message-use-mail-copies-to 'ask)
6393                     (not (message-y-or-n-p
6394                           (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6395 You should normally obey the Mail-Copies-To: header.
6396
6397         `Mail-Copies-To: " mct "'
6398 sends a copy of your response to " (if (string-match "," mct)
6399                                        "the specified addresses"
6400                                      "that address") ".")))
6401                (setq mct nil))))
6402
6403       ;; Build (textual) list of new recipient addresses.
6404       (cond
6405        ((not wide)
6406         (setq recipients (concat ", " author)))
6407        (address-headers
6408         (dolist (header address-headers)
6409           (let ((value (message-fetch-field header)))
6410             (when value
6411               (setq recipients (concat recipients ", " value))))))
6412        ((and mft
6413              (string-match "[^ \t,]" mft)
6414              (or (not (eq message-use-mail-followup-to 'ask))
6415                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6416 You should normally obey the Mail-Followup-To: header.  In this
6417 article, it has the value of
6418
6419 " mft "
6420
6421 which directs your response to " (if (string-match "," mft)
6422                                      "the specified addresses"
6423                                    "that address only") ".
6424
6425 Most commonly, Mail-Followup-To is used by a mailing list poster to
6426 express that responses should be sent to just the list, and not the
6427 poster as well.
6428
6429 If a message is posted to several mailing lists, Mail-Followup-To may
6430 also be used to direct the following discussion to one list only,
6431 because discussions that are spread over several lists tend to be
6432 fragmented and very difficult to follow.
6433
6434 Also, some source/announcement lists are not intended for discussion;
6435 responses here are directed to other addresses.
6436
6437 You may customize the variable `message-use-mail-followup-to', if you
6438 want to get rid of this query permanently.")))
6439         (setq recipients (concat ", " mft)))
6440        (to-address
6441         (setq recipients (concat ", " to-address))
6442         ;; If the author explicitly asked for a copy, we don't deny it to them.
6443         (if mct (setq recipients (concat recipients ", " mct))))
6444        (t
6445         (setq recipients (if never-mct "" (concat ", " author)))
6446         (if to (setq recipients (concat recipients ", " to)))
6447         (if cc (setq recipients (concat recipients ", " cc)))
6448         (if extra (setq recipients (concat recipients ", " extra)))
6449         (if mct (setq recipients (concat recipients ", " mct)))))
6450       (if (>= (length recipients) 2)
6451           ;; Strip the leading ", ".
6452           (setq recipients (substring recipients 2)))
6453       ;; Squeeze whitespace.
6454       (while (string-match "[ \t][ \t]+" recipients)
6455         (setq recipients (replace-match " " t t recipients)))
6456       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6457       (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
6458         (setq recipients (rmail-dont-reply-to recipients)))
6459       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6460       (if (string-equal recipients "")
6461           (setq recipients author))
6462       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6463       (setq recipients
6464             (mapcar
6465              (lambda (addr)
6466                (cons (downcase (mail-strip-quoted-names addr)) addr))
6467              (message-tokenize-header recipients)))
6468       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6469       (let ((s recipients))
6470         (while s
6471           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6472
6473       ;; Remove hierarchical lists that are contained within each other,
6474       ;; if message-hierarchical-addresses is defined.
6475       (when message-hierarchical-addresses
6476         (let ((plain-addrs (mapcar 'car recipients))
6477               subaddrs recip)
6478           (while plain-addrs
6479             (setq subaddrs (assoc (car plain-addrs)
6480                                   message-hierarchical-addresses)
6481                   plain-addrs (cdr plain-addrs))
6482             (when subaddrs
6483               (setq subaddrs (cdr subaddrs))
6484               (while subaddrs
6485                 (setq recip (assoc (car subaddrs) recipients)
6486                       subaddrs (cdr subaddrs))
6487                 (if recip
6488                     (setq recipients (delq recip recipients))))))))
6489
6490       ;; Build the header alist.  Allow the user to be asked whether
6491       ;; or not to reply to all recipients in a wide reply.
6492       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6493       (when (and recipients
6494                  (or (not message-wide-reply-confirm-recipients)
6495                      (y-or-n-p "Reply to all recipients? ")))
6496         (setq recipients (mapconcat
6497                           (lambda (addr) (cdr addr)) recipients ", "))
6498         (if (string-match "^ +" recipients)
6499             (setq recipients (substring recipients (match-end 0))))
6500         (push (cons 'Cc recipients) follow-to)))
6501     follow-to))
6502
6503 ;;;###autoload
6504 (defun message-reply (&optional to-address wide)
6505   "Start editing a reply to the article in the current buffer."
6506   (interactive)
6507   (require 'gnus-sum)                   ; for gnus-list-identifiers
6508   (let ((cur (current-buffer))
6509         from subject date
6510         references message-id follow-to
6511         (inhibit-point-motion-hooks t)
6512         (message-this-is-mail t)
6513         gnus-warning in-reply-to)
6514     (save-restriction
6515       (message-narrow-to-head-1)
6516       ;; Allow customizations to have their say.
6517       (if (not wide)
6518           ;; This is a regular reply.
6519           (when (functionp message-reply-to-function)
6520             (save-excursion
6521               (setq follow-to (funcall message-reply-to-function))))
6522         ;; This is a followup.
6523         (when (functionp message-wide-reply-to-function)
6524           (save-excursion
6525             (setq follow-to
6526                   (funcall message-wide-reply-to-function)))))
6527       (setq message-id (message-fetch-field "message-id" t)
6528             references (message-fetch-field "references")
6529             date (message-fetch-field "date")
6530             from (message-fetch-field "from")
6531             subject (or (message-fetch-field "subject") "none"))
6532       (when gnus-list-identifiers
6533         (setq subject (message-strip-list-identifiers subject)))
6534       (setq subject (message-make-followup-subject subject))
6535       (when message-subject-trailing-was-query
6536         (setq subject (message-strip-subject-trailing-was subject)))
6537
6538       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6539                  (string-match "<[^>]+>" gnus-warning))
6540         (setq message-id (match-string 0 gnus-warning)))
6541
6542       (unless follow-to
6543         (setq follow-to (message-get-reply-headers wide to-address)))
6544
6545       ;; Get the references from "In-Reply-To" field if there were
6546       ;; no references and "In-Reply-To" field looks promising.
6547       (unless references
6548         (when (and (setq in-reply-to (message-fetch-field "in-reply-to"))
6549                    (string-match "<[^>]+>" in-reply-to))
6550           (setq references (match-string 0 in-reply-to)))))
6551
6552     (unless (message-mail-user-agent)
6553       (message-pop-to-buffer
6554        (message-buffer-name
6555         (if wide "wide reply" "reply") from
6556         (if wide to-address nil))))
6557
6558     (setq message-reply-headers
6559           (make-full-mail-header-from-decoded-header
6560            0 subject from date message-id references 0 0 ""))
6561
6562     (message-setup
6563      `((Subject . ,subject)
6564        ,@follow-to)
6565      cur)))
6566
6567 ;;;###autoload
6568 (defun message-wide-reply (&optional to-address)
6569   "Make a \"wide\" reply to the message in the current buffer."
6570   (interactive)
6571   (message-reply to-address t))
6572
6573 ;;;###autoload
6574 (defun message-followup (&optional to-newsgroups)
6575   "Follow up to the message in the current buffer.
6576 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6577   (interactive)
6578   (require 'gnus-sum)                   ; for gnus-list-identifiers
6579   (let ((cur (current-buffer))
6580         from subject date reply-to mrt mct mft
6581         references message-id follow-to
6582         (inhibit-point-motion-hooks t)
6583         (message-this-is-news t)
6584         followup-to distribution newsgroups gnus-warning posted-to)
6585     (save-restriction
6586       (message-narrow-to-head)
6587       (when (functionp message-followup-to-function)
6588         (setq follow-to
6589               (funcall message-followup-to-function)))
6590       (setq from (message-fetch-field "from")
6591             date (message-fetch-field "date")
6592             subject (or (message-fetch-field "subject") "none")
6593             references (message-fetch-field "references")
6594             message-id (message-fetch-field "message-id" t)
6595             followup-to (message-fetch-field "followup-to")
6596             newsgroups (message-fetch-field "newsgroups")
6597             posted-to (message-fetch-field "posted-to")
6598             reply-to (message-fetch-field "reply-to")
6599             mrt (when message-use-mail-reply-to
6600                   (message-fetch-field "mail-reply-to"))
6601             distribution (message-fetch-field "distribution")
6602             mct (when message-use-mail-copies-to
6603                   (message-fetch-field "mail-copies-to"))
6604             mft (when message-use-mail-followup-to
6605                   (message-fetch-field "mail-followup-to")))
6606       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6607                  (string-match "<[^>]+>" gnus-warning))
6608         (setq message-id (match-string 0 gnus-warning)))
6609       ;; Remove bogus distribution.
6610       (when (and (stringp distribution)
6611                  (let ((case-fold-search t))
6612                    (string-match "world" distribution)))
6613         (setq distribution nil))
6614       (if gnus-list-identifiers
6615           (setq subject (message-strip-list-identifiers subject)))
6616       (setq subject (message-make-followup-subject subject))
6617       (when message-subject-trailing-was-query
6618         (setq subject (message-strip-subject-trailing-was subject)))
6619       (widen))
6620
6621     ;; Handle special values of Mail-Copies-To.
6622     (when mct
6623       (cond
6624        ((and (or (equal (downcase mct) "never")
6625                  (equal (downcase mct) "nobody")))
6626         (setq mct nil))
6627        ((and (or (equal (downcase mct) "always")
6628                  (equal (downcase mct) "poster")))
6629         (if (or (not (eq message-use-mail-copies-to 'ask))
6630                 (message-y-or-n-p
6631                  (concat "Obey Mail-Copies-To: always? ") t "\
6632 You should normally obey the Mail-Copies-To: header.
6633
6634         `Mail-Copies-To: " mct "'
6635 sends a copy of your response to the author."))
6636             (setq mct (or mrt reply-to from))
6637           (setq mct nil)))
6638        ((and (eq message-use-mail-copies-to 'ask)
6639              (not
6640               (message-y-or-n-p
6641                (concat "Obey Mail-Copies-To: " mct " ? ") t "\
6642 You should normally obey the Mail-Copies-To: header.
6643
6644         `Mail-Copies-To: " mct "'
6645 sends a copy of your response to " (if (string-match "," mct)
6646                                        "the specified addresses"
6647                                      "that address") ".")))
6648         (setq mct nil))))
6649
6650     (unless follow-to
6651       (cond
6652        (to-newsgroups (setq follow-to (list (cons 'Newsgroups to-newsgroups))))
6653        ;; Handle Followup-To.
6654        (followup-to
6655         (cond
6656          ((equal (downcase followup-to) "poster")
6657           (if (or (and followup-to (eq message-use-followup-to 'use))
6658                   (message-y-or-n-p "Obey Followup-To: poster? " t "\
6659 You should normally obey the Followup-To: header.
6660
6661         `Followup-To: poster'
6662 sends your response via e-mail instead of news.
6663
6664 A typical situation where `Followup-To: poster' is used is when the poster
6665 does not read the newsgroup, so he wouldn't see any replies sent to it.
6666
6667 You may customize the variable `message-use-followup-to', if you
6668 want to get rid of this query permanently."))
6669               (setq message-this-is-news nil
6670                     distribution nil
6671                     follow-to (list (cons 'To (or mrt reply-to from ""))))
6672             (setq follow-to (list (cons 'Newsgroups newsgroups)))))
6673          (t
6674           (if (or (equal followup-to newsgroups)
6675                   (not (and followup-to (eq message-use-followup-to 'ask)))
6676                   (message-y-or-n-p
6677                    (concat "Obey Followup-To: " followup-to "? ") t "\
6678 You should normally obey the Followup-To: header.
6679
6680         `Followup-To: " followup-to "'
6681 directs your response to " (if (string-match "," followup-to)
6682                                "the specified newsgroups"
6683                              "that newsgroup only") ".
6684
6685 If a message is posted to several newsgroups, Followup-To is often
6686 used to direct the following discussion to one newsgroup only,
6687 because discussions that are spread over several newsgroup tend to
6688 be fragmented and very difficult to follow.
6689
6690 Also, some source/announcement newsgroups are not intended for discussion;
6691 responses here are directed to other newsgroups.
6692
6693 You may customize the variable `message-use-followup-to', if you
6694 want to get rid of this query permanently."))
6695               (setq follow-to (list (cons 'Newsgroups followup-to)))
6696             (setq follow-to (list (cons 'Newsgroups newsgroups)))))))
6697        ;; Handle Mail-Followup-To, followup via e-mail.
6698        ((and mft
6699              (or (not (eq message-use-mail-followup-to 'ask))
6700                  (message-y-or-n-p
6701                   (concat "Obey Mail-Followup-To: " mft "? ") t "\
6702 You should normally obey the Mail-Followup-To: header.
6703
6704         `Mail-Followup-To: " mft "'
6705 directs your response to " (if (string-match "," mft)
6706                                "the specified addresses"
6707                              "that address only") " instead of news.
6708
6709 A typical situation where Mail-Followup-To is used is when the author thinks
6710 that further discussion should take place only in "
6711                              (if (string-match "," mft)
6712                                  "the specified mailing lists"
6713                                "that mailing list") ".")))
6714         (setq message-this-is-news nil
6715               distribution nil
6716               follow-to (list (cons 'To mft))))
6717        (posted-to (setq follow-to (list (cons 'Newsgroups posted-to))))
6718        (t
6719         (setq follow-to (list (cons 'Newsgroups newsgroups))))))
6720
6721     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6722
6723     (setq message-reply-headers
6724           (make-full-mail-header-from-decoded-header
6725            0 subject from date message-id references 0 0 ""))
6726
6727     (message-setup
6728      `((Subject . ,subject)
6729        ,@follow-to
6730        ,@(and mct (list (cons 'Cc mct)))
6731        ,@(and distribution (list (cons 'Distribution distribution))))
6732      cur)))
6733
6734 (defun message-is-yours-p ()
6735   "Non-nil means current article is yours.
6736 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6737 are yours except those that have Cancel-Lock header not belonging to you.
6738 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6739 regexp to match all of yours addresses."
6740   ;; Canlock-logic as suggested by Per Abrahamsen
6741   ;; <abraham@dina.kvl.dk>
6742   ;;
6743   ;; IF article has cancel-lock THEN
6744   ;;   IF we can verify it THEN
6745   ;;     issue cancel
6746   ;;   ELSE
6747   ;;     error: cancellock: article is not yours
6748   ;; ELSE
6749   ;;   Use old rules, comparing sender...
6750   (save-excursion
6751     (save-restriction
6752       (message-narrow-to-head-1)
6753       (if (message-fetch-field "Cancel-Lock")
6754           (if (null (canlock-verify))
6755               t
6756             (error "Failed to verify Cancel-lock: This article is not yours"))
6757         (let (sender from)
6758           (or
6759            (message-gnksa-enable-p 'cancel-messages)
6760            (and (setq sender (message-fetch-field "sender"))
6761                 (string-equal (downcase sender)
6762                               (downcase (message-make-sender))))
6763            ;; Email address in From field equals to our address
6764            (and (setq from (message-fetch-field "from"))
6765                 (string-equal
6766                  (downcase (cadr (std11-extract-address-components from)))
6767                  (downcase (cadr (std11-extract-address-components
6768                                   (message-make-from))))))
6769            ;; Email address in From field matches
6770            ;; 'message-alternative-emails' regexp
6771            (and from
6772                 message-alternative-emails
6773                 (string-match
6774                  message-alternative-emails
6775                  (cadr (std11-extract-address-components from))))))))))
6776
6777 ;;;###autoload
6778 (defun message-cancel-news (&optional arg)
6779   "Cancel an article you posted.
6780 If ARG, allow editing of the cancellation message."
6781   (interactive "P")
6782   (unless (message-news-p)
6783     (error "This is not a news article; canceling is impossible"))
6784   (let (from newsgroups message-id distribution buf)
6785     (save-excursion
6786       ;; Get header info from original article.
6787       (save-restriction
6788         (message-narrow-to-head-1)
6789         (setq from (message-fetch-field "from")
6790               newsgroups (message-fetch-field "newsgroups")
6791               message-id (message-fetch-field "message-id" t)
6792               distribution (message-fetch-field "distribution")))
6793       ;; Make sure that this article was written by the user.
6794       (unless (message-is-yours-p)
6795         (error "This article is not yours"))
6796       (when (yes-or-no-p "Do you really want to cancel this article? ")
6797         ;; Make control message.
6798         (if arg
6799             (message-news)
6800           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6801         (erase-buffer)
6802         (insert "Newsgroups: " newsgroups "\n"
6803                 "From: " from "\n"
6804                 "Subject: cmsg cancel " message-id "\n"
6805                 "Control: cancel " message-id "\n"
6806                 (if distribution
6807                     (concat "Distribution: " distribution "\n")
6808                   "")
6809                 mail-header-separator "\n"
6810                 message-cancel-message)
6811         (run-hooks 'message-cancel-hook)
6812         (unless arg
6813           (message "Canceling your article...")
6814           (if (let ((message-syntax-checks
6815                      'dont-check-for-anything-just-trust-me)
6816                     (message-encoding-buffer (current-buffer))
6817                     (message-edit-buffer (current-buffer)))
6818                 (message-send-news))
6819               (message "Canceling your article...done"))
6820           (kill-buffer buf))))))
6821
6822 (defun message-supersede-setup-for-mime-edit ()
6823   (set (make-local-variable 'message-setup-hook) nil)
6824   (mime-edit-again))
6825
6826 ;;;###autoload
6827 (defun message-supersede ()
6828   "Start composing a message to supersede the current message.
6829 This is done simply by taking the old article and adding a Supersedes
6830 header line with the old Message-ID."
6831   (interactive)
6832   (let ((cur (current-buffer)))
6833     ;; Check whether the user owns the article that is to be superseded.
6834     (unless (message-is-yours-p)
6835       (error "This article is not yours"))
6836     ;; Get a normal message buffer.
6837     (message-pop-to-buffer (message-buffer-name "supersede"))
6838     (insert-buffer-substring cur)
6839     (message-narrow-to-head-1)
6840     ;; Remove unwanted headers.
6841     (when message-ignored-supersedes-headers
6842       (message-remove-header message-ignored-supersedes-headers t))
6843     (goto-char (point-min))
6844     (if (not (re-search-forward "^Message-ID: " nil t))
6845         (error "No Message-ID in this article")
6846       (replace-match "Supersedes: " t t))
6847     (goto-char (point-max))
6848     (insert mail-header-separator)
6849     (widen)
6850     (when message-supersede-setup-function
6851       (funcall message-supersede-setup-function))
6852     (run-hooks 'message-supersede-setup-hook)
6853     (goto-char (point-min))
6854     (search-forward (concat "\n" mail-header-separator "\n") nil t)))
6855
6856 ;;;###autoload
6857 (defun message-recover ()
6858   "Reread contents of current buffer from its last auto-save file."
6859   (interactive)
6860   (let ((file-name (make-auto-save-file-name)))
6861     (cond ((save-window-excursion
6862              (if (not (eq system-type 'vax-vms))
6863                  (with-output-to-temp-buffer "*Directory*"
6864                    (with-current-buffer standard-output
6865                      (fundamental-mode)) ; for Emacs 20.4+
6866                    (buffer-disable-undo standard-output)
6867                    (let ((default-directory "/"))
6868                      (call-process
6869                       "ls" nil standard-output nil "-l" file-name))))
6870              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6871            (let ((buffer-read-only nil))
6872              (erase-buffer)
6873              (insert-file-contents file-name nil)))
6874           (t (error "message-recover cancelled")))))
6875
6876 ;;; Washing Subject:
6877
6878 (defun message-wash-subject (subject)
6879   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6880 Previous forwarders, replyers, etc. may add it."
6881   (with-temp-buffer
6882     (insert subject)
6883     (goto-char (point-min))
6884     ;; strip Re/Fwd stuff off the beginning
6885     (while (re-search-forward
6886             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6887       (replace-match ""))
6888
6889     ;; and gnus-style forwards [foo@bar.com] subject
6890     (goto-char (point-min))
6891     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6892       (replace-match ""))
6893
6894     ;; and off the end
6895     (goto-char (point-max))
6896     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6897       (replace-match ""))
6898
6899     ;; and finally, any whitespace that was left-over
6900     (goto-char (point-min))
6901     (while (re-search-forward "^[ \t]+" nil t)
6902       (replace-match ""))
6903     (goto-char (point-max))
6904     (while (re-search-backward "[ \t]+$" nil t)
6905       (replace-match ""))
6906
6907     (buffer-string)))
6908
6909 ;;; Forwarding messages.
6910
6911 (defvar message-forward-decoded-p nil
6912   "Non-nil means the original message is decoded.")
6913
6914 (defun message-forward-subject-name-subject (subject)
6915   "Generate a SUBJECT for a forwarded message.
6916 The form is: [Source] Subject, where if the original message was mail,
6917 Source is the name of the sender, and if the original message was
6918 news, Source is the list of newsgroups is was posted to."
6919   (concat "["
6920           (let ((group (message-fetch-field "newsgroups"))
6921                 from)
6922             (if group
6923                 (gnus-group-decoded-name group)
6924               (or (and (setq from (message-fetch-field "from"))
6925                        (car (std11-extract-address-components
6926                              (nnheader-decode-from from))))
6927                   "(nowhere)")))
6928           "] " subject))
6929
6930 (defun message-forward-subject-author-subject (subject)
6931   "Generate a SUBJECT for a forwarded message.
6932 The form is: [Source] Subject, where if the original message was mail,
6933 Source is the sender, and if the original message was news, Source is
6934 the list of newsgroups is was posted to."
6935   (concat "["
6936           (let ((group (message-fetch-field "newsgroups"))
6937                 from)
6938             (if group
6939                 (gnus-group-decoded-name group)
6940               (if (setq from (message-fetch-field "from"))
6941                   (nnheader-decode-from from)
6942                 "(nowhere)")))
6943           "] " subject))
6944
6945 (defun message-forward-subject-fwd (subject)
6946   "Generate a SUBJECT for a forwarded message.
6947 The form is: Fwd: Subject, where Subject is the original subject of
6948 the message."
6949   (if (string-match "^Fwd: " subject)
6950       subject
6951     (concat "Fwd: " subject)))
6952
6953 (defun message-make-forward-subject ()
6954   "Return a Subject header suitable for the message in the current buffer."
6955   (save-excursion
6956     (save-restriction
6957       (message-narrow-to-head-1)
6958       (let ((funcs message-make-forward-subject-function)
6959             (subject (message-fetch-field "Subject")))
6960         (setq subject
6961               (if subject
6962                   (if message-forward-decoded-p
6963                       subject
6964                     (nnheader-decode-subject subject))
6965                 ""))
6966         (when message-wash-forwarded-subjects
6967           (setq subject (message-wash-subject subject)))
6968         ;; Make sure funcs is a list.
6969         (and funcs
6970              (not (listp funcs))
6971              (setq funcs (list funcs)))
6972         ;; Apply funcs in order, passing subject generated by previous
6973         ;; func to the next one.
6974         (dolist (func funcs)
6975           (when (functionp func)
6976             (setq subject (funcall func subject))))
6977         subject))))
6978
6979 ;;;###autoload
6980 (defun message-forward (&optional news)
6981   "Forward the current message via mail.
6982 Optional NEWS will use news to forward instead of mail."
6983   (interactive "P")
6984   (let ((cur (current-buffer))
6985         (subject (message-make-forward-subject)))
6986     (if news
6987         (message-news nil subject)
6988       (message-mail nil subject))
6989     (message-forward-make-body cur)))
6990
6991 (defun message-forward-make-body-plain (forward-buffer)
6992   (insert
6993    "\n-------------------- Start of forwarded message --------------------\n")
6994   (let ((b (point)) e)
6995     (insert
6996      (with-temp-buffer
6997        (mm-disable-multibyte)
6998        (insert
6999         (with-current-buffer forward-buffer
7000           (mm-with-unibyte-current-buffer (buffer-string))))
7001        (mm-enable-multibyte)
7002        (mime-to-mml)
7003        (goto-char (point-min))
7004        (when (looking-at "From ")
7005          (replace-match "X-From-Line: "))
7006        (buffer-string)))
7007     (setq e (point))
7008     (insert
7009      "\n-------------------- End of forwarded message --------------------\n")
7010     (when message-forward-ignored-headers
7011       (save-restriction
7012         (narrow-to-region b e)
7013         (goto-char b)
7014         (narrow-to-region (point)
7015                           (or (search-forward "\n\n" nil t) (point)))
7016         (message-remove-header message-forward-ignored-headers t)))))
7017
7018 (defun message-forward-make-body-mime (forward-buffer)
7019   (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7020   (let ((b (point)) e)
7021     (save-restriction
7022       (narrow-to-region (point) (point))
7023       (mml-insert-buffer forward-buffer)
7024       (goto-char (point-min))
7025       (when (looking-at "From ")
7026         (replace-match "X-From-Line: "))
7027       (goto-char (point-max)))
7028     (setq e (point))
7029     (insert "<#/part>\n")))
7030
7031 (defun message-forward-make-body-mml (forward-buffer)
7032   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7033   (let ((b (point)) e)
7034     (if (not message-forward-decoded-p)
7035         (insert
7036          (with-temp-buffer
7037            (mm-disable-multibyte)
7038            (insert
7039             (with-current-buffer forward-buffer
7040               (mm-with-unibyte-current-buffer (buffer-string))))
7041            (mm-enable-multibyte)
7042            (mime-to-mml)
7043            (goto-char (point-min))
7044            (when (looking-at "From ")
7045              (replace-match "X-From-Line: "))
7046            (buffer-string)))
7047       (save-restriction
7048         (narrow-to-region (point) (point))
7049         (mml-insert-buffer forward-buffer)
7050         (goto-char (point-min))
7051         (when (looking-at "From ")
7052           (replace-match "X-From-Line: "))
7053         (goto-char (point-max))))
7054     (setq e (point))
7055     (insert "<#/mml>\n")
7056     (when (and (not message-forward-decoded-p)
7057                message-forward-ignored-headers)
7058       (save-restriction
7059         (narrow-to-region b e)
7060         (goto-char b)
7061         (narrow-to-region (point)
7062                           (or (search-forward "\n\n" nil t) (point)))
7063         (message-remove-header message-forward-ignored-headers t)))))
7064
7065 (defun message-forward-make-body-digest-plain (forward-buffer)
7066   (insert
7067    "\n-------------------- Start of forwarded message --------------------\n")
7068   (let ((b (point)) e)
7069     (mml-insert-buffer forward-buffer)
7070     (setq e (point))
7071     (insert
7072      "\n-------------------- End of forwarded message --------------------\n")))
7073
7074 (defun message-forward-make-body-digest-mime (forward-buffer)
7075   (insert "\n<#multipart type=digest>\n")
7076   (let ((b (point)) e)
7077     (insert-buffer-substring forward-buffer)
7078     (setq e (point))
7079     (insert "<#/multipart>\n")
7080     (save-restriction
7081       (narrow-to-region b e)
7082       (goto-char b)
7083       (narrow-to-region (point)
7084                         (or (search-forward "\n\n" nil t) (point)))
7085       (delete-region (point-min) (point-max)))))
7086
7087 (defun message-forward-make-body-digest (forward-buffer)
7088   (if message-forward-as-mime
7089       (message-forward-make-body-digest-mime forward-buffer)
7090     (message-forward-make-body-digest-plain forward-buffer)))
7091
7092 ;;;###autoload
7093 (defun message-forward-make-body (forward-buffer)
7094   ;; Put point where we want it before inserting the forwarded
7095   ;; message.
7096   ;; Note that this function definition for T-gnus is totally different
7097   ;; from the original Gnus."
7098   (if message-forward-before-signature
7099       (message-goto-body)
7100     (goto-char (point-max)))
7101   ;; Make sure we're at the start of the line.
7102   (unless (bolp)
7103     (insert "\n"))
7104   ;; Narrow to the area we are to insert.
7105   (narrow-to-region (point) (point))
7106   ;; Insert the separators and the forwarded buffer.
7107   (insert message-forward-start-separator)
7108   (let ((art-beg (point)))
7109     (insert-buffer-substring forward-buffer)
7110     (goto-char (point-max))
7111     (insert message-forward-end-separator)
7112     (set-text-properties (point-min) (point-max) nil)
7113     ;; Remove all unwanted headers.
7114     (goto-char art-beg)
7115     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
7116                                   (1- (point))
7117                                 (point)))
7118     (goto-char (point-min))
7119     (message-remove-header message-included-forward-headers t nil t)
7120     (widen)
7121     (message-position-point)))
7122
7123 ;;;###autoload
7124 (defun message-forward-rmail-make-body (forward-buffer)
7125   (save-window-excursion
7126     (set-buffer forward-buffer)
7127     (if (rmail-msg-is-pruned)
7128         (rmail-msg-restore-non-pruned-header)))
7129   (message-forward-make-body forward-buffer))
7130
7131 (eval-when-compile (defvar rmail-enable-mime-composing))
7132
7133 ;; Fixme: Should have defcustom.
7134 ;;;###autoload
7135 (defun message-insinuate-rmail ()
7136   "Let RMAIL use message to forward."
7137   (interactive)
7138   (setq rmail-enable-mime-composing t)
7139   (setq rmail-insert-mime-forwarded-message-function
7140         'message-forward-rmail-make-body))
7141
7142 ;;;###autoload
7143 (defun message-resend (address)
7144   "Resend the current article to ADDRESS."
7145   (interactive
7146    (list (message-read-from-minibuffer "Resend message to: ")))
7147   (message "Resending message to %s..." address)
7148   (save-excursion
7149     (let ((cur (current-buffer))
7150           beg)
7151       ;; We first set up a normal mail buffer.
7152       (unless (message-mail-user-agent)
7153         (set-buffer (get-buffer-create " *message resend*"))
7154         (erase-buffer))
7155       (let ((message-this-is-mail t)
7156             message-setup-hook)
7157         (message-setup `((To . ,address))))
7158       ;; Insert our usual headers.
7159       (message-generate-headers '(From Date To Message-ID))
7160       (message-narrow-to-headers)
7161       ;; Remove X-Draft-From header etc.
7162       (message-remove-header message-ignored-mail-headers t)
7163       ;; Rename them all to "Resent-*".
7164       (goto-char (point-min))
7165       (while (re-search-forward "^[A-Za-z]" nil t)
7166         (forward-char -1)
7167         (insert "Resent-"))
7168       (widen)
7169       (forward-line)
7170       (delete-region (point) (point-max))
7171       (setq beg (point))
7172       ;; Insert the message to be resent.
7173       (insert-buffer-substring cur)
7174       (goto-char (point-min))
7175       (search-forward "\n\n")
7176       (forward-char -1)
7177       (save-restriction
7178         (narrow-to-region beg (point))
7179         (message-remove-header message-ignored-resent-headers t)
7180         (goto-char (point-max)))
7181       (insert mail-header-separator)
7182       ;; Rename all old ("Also-")Resent headers.
7183       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7184         (beginning-of-line)
7185         (insert "Also-"))
7186       ;; Quote any "From " lines at the beginning.
7187       (goto-char beg)
7188       (when (looking-at "From ")
7189         (replace-match "X-From-Line: "))
7190       ;; Send it.
7191       (let ((message-encoding-buffer (current-buffer))
7192             (message-edit-buffer (current-buffer))
7193             message-required-mail-headers)
7194         (message-send-mail))
7195       (kill-buffer (current-buffer)))
7196     (message "Resending message to %s...done" address)))
7197
7198 (defun message-bounce-setup-for-mime-edit ()
7199   (set (make-local-variable 'message-setup-hook) nil)
7200   (mime-edit-again))
7201
7202 ;;;###autoload
7203 (defun message-bounce ()
7204   "Re-mail the current message.
7205 This only makes sense if the current message is a bounce message that
7206 contains some mail you have written which has been bounced back to
7207 you."
7208   (interactive)
7209   (let ((cur (current-buffer))
7210         mime-boundary boundary)
7211     (message-pop-to-buffer (message-buffer-name "bounce"))
7212     (insert-buffer-substring cur)
7213     (undo-boundary)
7214     (message-narrow-to-head)
7215     (if (and (message-fetch-field "MIME-Version")
7216              (setq mime-boundary (message-fetch-field "Content-Type")))
7217         (if (string-match "boundary=\"\\([^\"]+\\)\"" mime-boundary)
7218             (setq mime-boundary (concat (regexp-quote
7219                                          (match-string 1 mime-boundary))
7220                                         " *\nContent-Type: message/rfc822"))
7221           (setq mime-boundary nil)))
7222     (widen)
7223     (goto-char (point-min))
7224     (re-search-forward "\n\n+" nil t)
7225     (setq boundary (point))
7226     ;; We remove everything before the bounced mail.
7227     (if (or (and mime-boundary
7228                  (re-search-forward mime-boundary nil t)
7229                  (forward-line 1))
7230             (re-search-forward message-unsent-separator nil t)
7231             (progn
7232               (search-forward "\n\n" nil 'move)
7233               (re-search-backward "^Return-Path:.*\n" boundary t)))
7234         (progn
7235           (forward-line 1)
7236           (delete-region (point-min)
7237                          (if (re-search-forward "^[^ \n\t]+:" nil t)
7238                              (match-beginning 0)
7239                            (point))))
7240       (when (re-search-backward "^.?From .*\n" nil t)
7241         (delete-region (match-beginning 0) (match-end 0))))
7242     (save-restriction
7243       (message-narrow-to-head-1)
7244       (message-remove-header message-ignored-bounced-headers t)
7245       (goto-char (point-max))
7246       (insert mail-header-separator))
7247     (when message-bounce-setup-function
7248       (funcall message-bounce-setup-function))
7249     (run-hooks 'message-bounce-setup-hook)
7250     (message-position-point)))
7251
7252 ;;;
7253 ;;; Interactive entry points for new message buffers.
7254 ;;;
7255
7256 ;;;###autoload
7257 (defun message-mail-other-window (&optional to subject)
7258   "Like `message-mail' command, but display mail buffer in another window."
7259   (interactive)
7260   (unless (message-mail-user-agent)
7261     (let ((pop-up-windows t)
7262           (special-display-buffer-names nil)
7263           (special-display-regexps nil)
7264           (same-window-buffer-names nil)
7265           (same-window-regexps nil))
7266       (message-pop-to-buffer (message-buffer-name "mail" to))))
7267   (let ((message-this-is-mail t))
7268     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7269                    nil nil 'switch-to-buffer-other-window)))
7270
7271 ;;;###autoload
7272 (defun message-mail-other-frame (&optional to subject)
7273   "Like `message-mail' command, but display mail buffer in another frame."
7274   (interactive)
7275   (unless (message-mail-user-agent)
7276     (let ((pop-up-frames t)
7277           (special-display-buffer-names nil)
7278           (special-display-regexps nil)
7279           (same-window-buffer-names nil)
7280           (same-window-regexps nil))
7281       (message-pop-to-buffer (message-buffer-name "mail" to))))
7282   (let ((message-this-is-mail t))
7283     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7284                    nil nil 'switch-to-buffer-other-frame)))
7285
7286 ;;;###autoload
7287 (defun message-news-other-window (&optional newsgroups subject)
7288   "Start editing a news article to be sent."
7289   (interactive)
7290   (let ((pop-up-windows t)
7291         (special-display-buffer-names nil)
7292         (special-display-regexps nil)
7293         (same-window-buffer-names nil)
7294         (same-window-regexps nil))
7295     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7296   (let ((message-this-is-news t))
7297     (message-setup `((Newsgroups . ,(or newsgroups ""))
7298                      (Subject . ,(or subject ""))))))
7299
7300 ;;;###autoload
7301 (defun message-news-other-frame (&optional newsgroups subject)
7302   "Start editing a news article to be sent."
7303   (interactive)
7304   (let ((pop-up-frames t)
7305         (special-display-buffer-names nil)
7306         (special-display-regexps nil)
7307         (same-window-buffer-names nil)
7308         (same-window-regexps nil))
7309     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7310   (let ((message-this-is-news t))
7311     (message-setup `((Newsgroups . ,(or newsgroups ""))
7312                      (Subject . ,(or subject ""))))))
7313
7314 ;;; underline.el
7315
7316 ;; This code should be moved to underline.el (from which it is stolen).
7317
7318 ;;;###autoload
7319 (defun bold-region (start end)
7320   "Bold all nonblank characters in the region.
7321 Works by overstriking characters.
7322 Called from program, takes two arguments START and END
7323 which specify the range to operate on."
7324   (interactive "r")
7325   (save-excursion
7326     (let ((end1 (make-marker)))
7327       (move-marker end1 (max start end))
7328       (goto-char (min start end))
7329       (while (< (point) end1)
7330         (or (looking-at "[_\^@- ]")
7331             (insert (char-after) "\b"))
7332         (forward-char 1)))))
7333
7334 ;;;###autoload
7335 (defun unbold-region (start end)
7336   "Remove all boldness (overstruck characters) in the region.
7337 Called from program, takes two arguments START and END
7338 which specify the range to operate on."
7339   (interactive "r")
7340   (save-excursion
7341     (let ((end1 (make-marker)))
7342       (move-marker end1 (max start end))
7343       (goto-char (min start end))
7344       (while (search-forward "\b" end1 t)
7345         (if (eq (char-after) (char-after (- (point) 2)))
7346             (delete-char -2))))))
7347
7348 (defun message-exchange-point-and-mark ()
7349   "Exchange point and mark, but don't activate region if it was inactive."
7350   (unless (prog1
7351               (message-mark-active-p)
7352             (exchange-point-and-mark))
7353     (setq mark-active nil)))
7354
7355 (defalias 'message-make-overlay 'make-overlay)
7356 (defalias 'message-delete-overlay 'delete-overlay)
7357 (defalias 'message-overlay-put 'overlay-put)
7358 (defun message-kill-all-overlays ()
7359   (if (featurep 'xemacs)
7360       (map-extents (lambda (extent ignore) (delete-extent extent)))
7361     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7362
7363 ;; Support for toolbar
7364 (eval-when-compile
7365   (defvar tool-bar-map)
7366   (defvar tool-bar-mode))
7367
7368 (defun message-tool-bar-local-item-from-menu (command icon in-map &optional from-map &rest props)
7369   ;; We need to make tool bar entries in local keymaps with
7370   ;; `tool-bar-local-item-from-menu' in Emacs > 21.3
7371   (if (fboundp 'tool-bar-local-item-from-menu)
7372       ;; This is for Emacs 21.3
7373       (tool-bar-local-item-from-menu command icon in-map from-map props)
7374     (tool-bar-add-item-from-menu command icon from-map props)))
7375
7376 (defun message-tool-bar-map ()
7377   (or message-tool-bar-map
7378       (setq message-tool-bar-map
7379             (and
7380              (condition-case nil (require 'tool-bar) (error nil))
7381              (fboundp 'tool-bar-add-item-from-menu)
7382              tool-bar-mode
7383              (let ((tool-bar-map (copy-keymap tool-bar-map))
7384                    (load-path (mm-image-load-path)))
7385                ;; Zap some items which aren't so relevant and take
7386                ;; up space.
7387                (dolist (key '(print-buffer kill-buffer save-buffer
7388                                            write-file dired open-file))
7389                  (define-key tool-bar-map (vector key) nil))
7390                (message-tool-bar-local-item-from-menu
7391                 'message-send-and-exit "mail_send" tool-bar-map message-mode-map)
7392                (message-tool-bar-local-item-from-menu
7393                 'message-kill-buffer "close" tool-bar-map message-mode-map)
7394                (message-tool-bar-local-item-from-menu
7395                 'message-dont-send "cancel" tool-bar-map message-mode-map)
7396 ;;             (message-tool-bar-local-item-from-menu
7397 ;;              'mime-edit-insert-file "attach"
7398 ;;              tool-bar-map mime-edit-mode-map)
7399                (message-tool-bar-local-item-from-menu
7400                 'ispell-message "spell" tool-bar-map message-mode-map)
7401 ;;             (message-tool-bar-local-item-from-menu
7402 ;;              'mime-edit-preview-message "preview"
7403 ;;              tool-bar-map mime-edit-mode-map)
7404                (message-tool-bar-local-item-from-menu
7405                 'message-insert-importance-high "important"
7406                 tool-bar-map message-mode-map)
7407                (message-tool-bar-local-item-from-menu
7408                 'message-insert-importance-low "unimportant"
7409                 tool-bar-map message-mode-map)
7410                (message-tool-bar-local-item-from-menu
7411                 'message-insert-disposition-notification-to "receipt"
7412                 tool-bar-map message-mode-map)
7413                tool-bar-map)))))
7414
7415 ;;; Group name completion.
7416
7417 (defcustom message-newgroups-header-regexp
7418   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7419   "Regexp that match headers that lists groups."
7420   :group 'message
7421   :type 'regexp)
7422
7423 (defcustom message-completion-alist
7424   (list (cons message-newgroups-header-regexp 'message-expand-group)
7425         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7426         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7427           . message-expand-name)
7428         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7429           . message-expand-name))
7430   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7431   :version "22.1"
7432   :group 'message
7433   :type '(alist :key-type regexp :value-type function))
7434
7435 (defcustom message-expand-name-databases
7436   (list 'bbdb 'eudc 'lsdb)
7437   "List of databases to try for name completion (`message-expand-name').
7438 Each element is a symbol and can be `bbdb', `eudc' or `lsdb'."
7439   :group 'message
7440   :type '(set (const bbdb) (const eudc) (const lsdb)))
7441
7442 (defcustom message-expand-name-function
7443   (cond ((and (boundp 'eudc-protocol)
7444               eudc-protocol)
7445          'eudc-expand-inline)
7446         ((fboundp 'bbdb-complete-name)
7447          'bbdb-complete-name)
7448         ((fboundp 'lsdb-complete-name)
7449          'lsdb-complete-name)
7450         (t 'expand-abbrev))
7451   "*A function called to expand addresses in field body.
7452 This variable is semi-obsolete, set it as nil and use
7453 `message-expand-name-databases' instead."
7454   :group 'message
7455   :type '(radio (const :format "Invalidate it: %v\n" nil)
7456                 (function-item :format "eudc: %v\n" eudc-expand-inline)
7457                 (function-item :format "bbdb: %v\n" bbdb-complete-name)
7458                 (function-item :format "lsdb: %v\n" lsdb-complete-name)
7459                 (function :value expand-abbrev)))
7460
7461 (defcustom message-tab-body-function nil
7462   "*Function to execute when `message-tab' (TAB) is executed in the body.
7463 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7464   :version "22.1"
7465   :group 'message
7466   :link '(custom-manual "(message)Various Commands")
7467   :type '(choice (const nil)
7468                  function))
7469
7470 (defun message-tab ()
7471   "Complete names according to `message-completion-alist'.
7472 Execute function specified by `message-tab-body-function' when not in
7473 those headers."
7474   (interactive)
7475   (let ((alist message-completion-alist))
7476     (while (and alist
7477                 (let ((mail-abbrev-mode-regexp (caar alist)))
7478                   (not (mail-abbrev-in-expansion-header-p))))
7479       (setq alist (cdr alist)))
7480     (funcall (or (cdar alist) message-tab-body-function
7481                  (lookup-key text-mode-map "\t")
7482                  (lookup-key global-map "\t")
7483                  'indent-relative))))
7484
7485 (defun message-expand-group ()
7486   "Expand the group name under point."
7487   (let* ((b (save-excursion
7488               (save-restriction
7489                 (narrow-to-region
7490                  (save-excursion
7491                    (beginning-of-line)
7492                    (skip-chars-forward "^:")
7493                    (1+ (point)))
7494                  (point))
7495                 (skip-chars-backward "^, \t\n") (point))))
7496          (completion-ignore-case t)
7497          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7498                                             (point))))
7499          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7500          (completions (all-completions string hashtb))
7501          comp)
7502     (delete-region b (point))
7503     (cond
7504      ((= (length completions) 1)
7505       (if (string= (car completions) string)
7506           (progn
7507             (insert string)
7508             (message "Only matching group"))
7509         (insert (car completions))))
7510      ((and (setq comp (try-completion string hashtb))
7511            (not (string= comp string)))
7512       (insert comp))
7513      (t
7514       (insert string)
7515       (if (not comp)
7516           (message "No matching groups")
7517         (save-selected-window
7518           (pop-to-buffer "*Completions*")
7519           (buffer-disable-undo)
7520           (let ((buffer-read-only nil))
7521             (erase-buffer)
7522             (let ((standard-output (current-buffer)))
7523               (display-completion-list (sort completions 'string<)))
7524             (goto-char (point-min))
7525             (delete-region (point) (progn (forward-line 3) (point))))))))))
7526
7527 (defun message-expand-name ()
7528   (cond (message-expand-name-function
7529          (funcall message-expand-name-function))
7530         ((and (memq 'eudc message-expand-name-databases)
7531               (boundp 'eudc-protocol)
7532               eudc-protocol)
7533          (eudc-expand-inline))
7534         ((and (memq 'bbdb message-expand-name-databases)
7535               (fboundp 'bbdb-complete-name))
7536          (bbdb-complete-name))
7537         ((and (memq 'lsdb message-expand-name-databases)
7538               (fboundp 'lsdb-complete-name))
7539          (lsdb-complete-name))
7540         (t 'expand-abbrev)))
7541
7542 ;;; Help stuff.
7543
7544 (defun message-talkative-question (ask question show &rest text)
7545   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7546 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7547 The following arguments may contain lists of values."
7548   (if (and show
7549            (setq text (message-flatten-list text)))
7550       (save-window-excursion
7551         (save-excursion
7552           (with-output-to-temp-buffer " *MESSAGE information message*"
7553             (set-buffer " *MESSAGE information message*")
7554             (fundamental-mode)          ; for Emacs 20.4+
7555             (mapcar 'princ text)
7556             (goto-char (point-min))))
7557         (funcall ask question))
7558     (funcall ask question)))
7559
7560 (defun message-flatten-list (list)
7561   "Return a new, flat list that contains all elements of LIST.
7562
7563 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7564 => (1 2 3 4 5 6 7)"
7565   (cond ((consp list)
7566          (apply 'append (mapcar 'message-flatten-list list)))
7567         (list
7568          (list list))))
7569
7570 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7571   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7572 Then clone the local variables and values from the old buffer to the
7573 new one, cloning only the locals having a substring matching the
7574 regexp VARSTR."
7575   (let ((oldbuf (current-buffer)))
7576     (save-excursion
7577       (set-buffer (generate-new-buffer name))
7578       (message-clone-locals oldbuf varstr)
7579       (current-buffer))))
7580
7581 (defun message-clone-locals (buffer &optional varstr)
7582   "Clone the local variables from BUFFER to the current buffer."
7583   (let ((locals (save-excursion
7584                   (set-buffer buffer)
7585                   (buffer-local-variables)))
7586         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address\\|^user-full-name"))
7587     (mapcar
7588      (lambda (local)
7589        (when (and (consp local)
7590                   (car local)
7591                   (string-match regexp (symbol-name (car local)))
7592                   (or (null varstr)
7593                       (string-match varstr (symbol-name (car local)))))
7594          (ignore-errors
7595            (set (make-local-variable (car local))
7596                 (cdr local)))))
7597      locals)))
7598
7599 ;;; @ for MIME Edit mode
7600 ;;;
7601
7602 (defun message-maybe-encode ()
7603   (when message-mime-mode
7604     ;; Inherit the buffer local variable `mime-edit-pgp-processing'.
7605     (let ((pgp-processing (with-current-buffer message-edit-buffer
7606                             mime-edit-pgp-processing)))
7607       (setq mime-edit-pgp-processing pgp-processing))
7608     (run-hooks 'mime-edit-translate-hook)
7609     (if (catch 'mime-edit-error
7610           (save-excursion
7611             (mime-edit-pgp-enclose-buffer)
7612             (mime-edit-translate-body)))
7613         (error "Translation error!"))
7614     (run-hooks 'mime-edit-exit-hook)))
7615
7616 (defun message-mime-insert-article (&optional full-headers)
7617   (interactive "P")
7618   (let ((message-cite-function 'mime-edit-inserted-message-filter)
7619         (message-reply-buffer
7620          (message-get-parameter-with-eval 'original-buffer))
7621         (start (point)))
7622     (message-yank-original nil)
7623     (save-excursion
7624       (narrow-to-region (goto-char start)
7625                         (if (search-forward "\n\n" nil t)
7626                             (1- (point))
7627                           (point-max)))
7628       (goto-char (point-min))
7629       (let ((message-included-forward-headers
7630              (if full-headers "" message-included-forward-headers)))
7631         (message-remove-header message-included-forward-headers t nil t))
7632       (widen))))
7633
7634 (set-alist 'mime-edit-message-inserter-alist
7635            'message-mode (function message-mime-insert-article))
7636
7637 ;;;
7638 ;;; MIME functions
7639 ;;;
7640
7641 (defvar message-inhibit-body-encoding t)
7642
7643 (defun message-encode-message-body ()
7644   (unless message-inhibit-body-encoding
7645     (let ((mail-parse-charset (or mail-parse-charset
7646                                   message-default-charset))
7647           (case-fold-search t)
7648           lines content-type-p)
7649       (message-goto-body)
7650       (save-restriction
7651         (narrow-to-region (point) (point-max))
7652         (let ((new (mml-generate-mime)))
7653           (when new
7654             (delete-region (point-min) (point-max))
7655             (insert new)
7656             (goto-char (point-min))
7657             (if (eq (aref new 0) ?\n)
7658                 (delete-char 1)
7659               (search-forward "\n\n")
7660               (setq lines (buffer-substring (point-min) (1- (point))))
7661               (delete-region (point-min) (point))))))
7662       (save-restriction
7663         (message-narrow-to-headers-or-head)
7664         (message-remove-header "Mime-Version")
7665         (goto-char (point-max))
7666         (insert "MIME-Version: 1.0\n")
7667         (when lines
7668           (insert lines))
7669         (setq content-type-p
7670               (or mml-boundary
7671                   (re-search-backward "^Content-Type:" nil t))))
7672       (save-restriction
7673         (message-narrow-to-headers-or-head)
7674         (message-remove-first-header "Content-Type")
7675         (message-remove-first-header "Content-Transfer-Encoding"))
7676       ;; We always make sure that the message has a Content-Type
7677       ;; header.  This is because some broken MTAs and MUAs get
7678       ;; awfully confused when confronted with a message with a
7679       ;; MIME-Version header and without a Content-Type header.  For
7680       ;; instance, Solaris' /usr/bin/mail.
7681       (unless content-type-p
7682         (goto-char (point-min))
7683         ;; For unknown reason, MIME-Version doesn't exist.
7684         (when (re-search-forward "^MIME-Version:" nil t)
7685           (forward-line 1)
7686           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7687
7688 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7689   "Read from the minibuffer while providing abbrev expansion."
7690   (if (fboundp 'mail-abbrevs-setup)
7691       (let ((mail-abbrev-mode-regexp "")
7692             (minibuffer-setup-hook 'mail-abbrevs-setup)
7693             (minibuffer-local-map message-minibuffer-local-map))
7694         (read-from-minibuffer prompt initial-contents))
7695     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7696           (minibuffer-local-map message-minibuffer-local-map))
7697       (read-string prompt initial-contents))))
7698
7699 (defun message-use-alternative-email-as-from ()
7700   (require 'mail-utils)
7701   (let* ((fields '("To" "Cc" "From"))
7702          (emails
7703           (split-string
7704            (mail-strip-quoted-names
7705             (mapconcat 'message-fetch-reply-field fields ","))
7706            "[ \f\t\n\r\v,]+"))
7707          email)
7708     (while emails
7709       (if (string-match message-alternative-emails (car emails))
7710           (setq email (car emails)
7711                 emails nil))
7712       (pop emails))
7713     (unless (or (not email) (equal email user-mail-address))
7714       (goto-char (point-max))
7715       (insert "From: " (let ((user-mail-address email)) (message-make-from))
7716               "\n"))))
7717
7718 (defun message-options-get (symbol)
7719   (cdr (assq symbol message-options)))
7720
7721 (defun message-options-set (symbol value)
7722   (let ((the-cons (assq symbol message-options)))
7723     (if the-cons
7724         (if value
7725             (setcdr the-cons value)
7726           (setq message-options (delq the-cons message-options)))
7727       (and value
7728            (push (cons symbol value) message-options))))
7729   value)
7730
7731 (defun message-options-set-recipient ()
7732   (save-restriction
7733     (message-narrow-to-headers-or-head)
7734     (message-options-set 'message-sender
7735                          (mail-strip-quoted-names
7736                           (message-fetch-field "from")))
7737     (message-options-set 'message-recipients
7738                          (mail-strip-quoted-names
7739                           (let ((to (message-fetch-field "to"))
7740                                 (cc (message-fetch-field "cc"))
7741                                 (bcc (message-fetch-field "bcc")))
7742                             (concat
7743                              (or to "")
7744                              (if (and to cc) ", ")
7745                              (or cc "")
7746                              (if (and (or to cc) bcc) ", ")
7747                              (or bcc "")))))))
7748
7749 (defun message-hide-headers ()
7750   "Hide headers based on the `message-hidden-headers' variable."
7751   (let ((regexps (if (stringp message-hidden-headers)
7752                      (list message-hidden-headers)
7753                    message-hidden-headers))
7754         (inhibit-point-motion-hooks t)
7755         (after-change-functions nil)
7756         (end-of-headers 0))
7757     (when regexps
7758       (save-excursion
7759         (save-restriction
7760           (message-narrow-to-headers)
7761           (goto-char (point-min))
7762           (while (not (eobp))
7763             (if (not (message-hide-header-p regexps))
7764                 (message-next-header)
7765               (let ((begin (point))
7766                     header header-len)
7767                 (message-next-header)
7768                 (setq header (buffer-substring begin (point))
7769                       header-len (- (point) begin))
7770                 (delete-region begin (point))
7771                 (goto-char (1+ end-of-headers))
7772                 (insert header)
7773                 (setq end-of-headers
7774                       (+ end-of-headers header-len))))))))
7775     (narrow-to-region (1+ end-of-headers) (point-max))))
7776
7777 (defun message-hide-header-p (regexps)
7778   (let ((result nil)
7779         (reverse nil))
7780     (when (eq (car regexps) 'not)
7781       (setq reverse t)
7782       (pop regexps))
7783     (dolist (regexp regexps)
7784       (setq result (or result (looking-at regexp))))
7785     (if reverse
7786         (not result)
7787       result)))
7788
7789 (when (featurep 'xemacs)
7790   (require 'messagexmas)
7791   (message-xmas-redefine))
7792
7793 (provide 'message)
7794
7795 (run-hooks 'message-load-hook)
7796
7797 ;; Local Variables:
7798 ;; coding: iso-8859-1
7799 ;; End:
7800
7801 ;;; message.el ends here