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