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