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