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