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