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