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