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