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