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