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