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