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