b3660c6cc4e8bcdf702d84857338dd7d10a27053
[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   (while (looking-at "^<#secure") (forward-line 1)))
3104
3105 (defun message-in-body-p ()
3106   "Return t if point is in the message body."
3107   (let ((body (save-excursion (message-goto-body) (point))))
3108     (>= (point) body)))
3109
3110 (defun message-goto-eoh ()
3111   "Move point to the end of the headers."
3112   (interactive)
3113   (message-goto-body)
3114   (forward-line -1))
3115
3116 (defun message-goto-signature ()
3117   "Move point to the beginning of the message signature.
3118 If there is no signature in the article, go to the end and
3119 return nil."
3120   (interactive)
3121   (goto-char (point-min))
3122   (if (re-search-forward message-signature-separator nil t)
3123       (forward-line 1)
3124     (goto-char (point-max))
3125     nil))
3126
3127 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
3128   "Insert a reasonable MFT header in a post to an unsubscribed list.
3129 When making original posts to a mailing list you are not subscribed to,
3130 you have to type in a MFT header by hand.  The contents, usually, are
3131 the addresses of the list and your own address.  This function inserts
3132 such a header automatically.  It fetches the contents of the To: header
3133 in the current mail buffer, and appends the current `user-mail-address'.
3134
3135 If the optional argument INCLUDE-CC is non-nil, the addresses in the
3136 Cc: header are also put into the MFT."
3137
3138   (interactive "P")
3139   (let* (cc tos)
3140     (save-restriction
3141       (message-narrow-to-headers)
3142       (message-remove-header "Mail-Followup-To")
3143       (setq cc (and include-cc (message-fetch-field "Cc")))
3144       (setq tos (if cc
3145                     (concat (message-fetch-field "To") "," cc)
3146                   (message-fetch-field "To"))))
3147     (message-goto-mail-followup-to)
3148     (insert (concat tos ", " user-mail-address))))
3149
3150 \f
3151
3152 (defun message-insert-to (&optional force)
3153   "Insert a To header that points to the author of the article being replied to.
3154 If the original author requested not to be sent mail, don't insert unless the
3155 prefix FORCE is given."
3156   (interactive "P")
3157   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
3158          (dont (and mct (or (equal (downcase mct) "never")
3159                             (equal (downcase mct) "nobody"))))
3160          (to (or (message-fetch-reply-field "mail-reply-to")
3161                  (message-fetch-reply-field "reply-to")
3162                  (message-fetch-reply-field "from"))))
3163     (when (and dont to)
3164       (message
3165        (if force
3166            "Ignoring the user request not to have copies sent via mail"
3167          "Complying with the user request not to have copies sent via mail")))
3168     (when (and force (not to))
3169       (error "No mail address in the article"))
3170     (when (and to (or force (not dont)))
3171       (message-carefully-insert-headers (list (cons 'To to))))))
3172
3173 (defun message-insert-wide-reply ()
3174   "Insert To and Cc headers as if you were doing a wide reply."
3175   (interactive)
3176   (let ((headers (message-with-reply-buffer
3177                    (message-get-reply-headers t))))
3178     (message-carefully-insert-headers headers)))
3179
3180 (defcustom message-header-synonyms
3181   '((To Cc Bcc)
3182     (Original-To))
3183   "List of lists of header synonyms.
3184 E.g., if this list contains a member list with elements `Cc' and `To',
3185 then `message-carefully-insert-headers' will not insert a `To' header
3186 when the message is already `Cc'ed to the recipient."
3187   :version "22.1"
3188   :group 'message-headers
3189   :link '(custom-manual "(message)Message Headers")
3190   :type '(repeat sexp))
3191
3192 (defun message-carefully-insert-headers (headers)
3193   "Insert the HEADERS, an alist, into the message buffer.
3194 Does not insert the headers when they are already present there
3195 or in the synonym headers, defined by `message-header-synonyms'."
3196   ;; FIXME: Should compare only the address and not the full name.  Comparison
3197   ;; should be done case-folded (and with `string=' rather than
3198   ;; `string-match').
3199   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
3200   (dolist (header headers)
3201     (let* ((header-name (symbol-name (car header)))
3202            (new-header (cdr header))
3203            (synonyms (loop for synonym in message-header-synonyms
3204                            when (memq (car header) synonym) return synonym))
3205            (old-header
3206             (loop for synonym in synonyms
3207                   for old-header = (mail-fetch-field (symbol-name synonym))
3208                   when (and old-header (string-match new-header old-header))
3209                   return synonym)))
3210       (if old-header
3211           (message "already have `%s' in `%s'" new-header old-header)
3212         (when (and (message-position-on-field header-name)
3213                    (setq old-header (mail-fetch-field header-name))
3214                    (not (string-match "\\` *\\'" old-header)))
3215           (insert ", "))
3216         (insert new-header)))))
3217
3218 (defun message-widen-reply ()
3219   "Widen the reply to include maximum recipients."
3220   (interactive)
3221   (let ((follow-to
3222          (and (bufferp message-reply-buffer)
3223               (buffer-name message-reply-buffer)
3224               (with-current-buffer message-reply-buffer
3225                 (message-get-reply-headers t)))))
3226     (save-excursion
3227       (save-restriction
3228         (message-narrow-to-headers)
3229         (dolist (elem follow-to)
3230           (message-remove-header (symbol-name (car elem)))
3231           (goto-char (point-min))
3232           (insert (symbol-name (car elem)) ": "
3233                   (cdr elem) "\n"))))))
3234
3235 (defun message-insert-newsgroups ()
3236   "Insert the Newsgroups header from the article being replied to."
3237   (interactive)
3238   (when (and (message-position-on-field "Newsgroups")
3239              (mail-fetch-field "newsgroups")
3240              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
3241     (insert ","))
3242   (insert (or (message-fetch-reply-field "newsgroups") "")))
3243
3244 \f
3245
3246 ;;; Various commands
3247
3248 (defun message-delete-not-region (beg end)
3249   "Delete everything in the body of the current message outside of the region."
3250   (interactive "r")
3251   (let (citeprefix)
3252     (save-excursion
3253       (goto-char beg)
3254       ;; snarf citation prefix, if appropriate
3255       (unless (eq (point) (progn (beginning-of-line) (point)))
3256         (when (looking-at message-cite-prefix-regexp)
3257           (setq citeprefix (match-string 0))))
3258       (goto-char end)
3259       (delete-region (point) (if (not (message-goto-signature))
3260                                  (point)
3261                                (forward-line -2)
3262                                (point)))
3263       (insert "\n")
3264       (goto-char beg)
3265       (delete-region beg (progn (message-goto-body)
3266                                 (forward-line 2)
3267                                 (point)))
3268       (when citeprefix
3269         (insert citeprefix))))
3270   (when (message-goto-signature)
3271     (forward-line -2)))
3272
3273 (defun message-kill-to-signature (&optional arg)
3274   "Kill all text up to the signature.
3275 If a numeric argument or prefix arg is given, leave that number
3276 of lines before the signature intact."
3277   (interactive "P")
3278   (save-excursion
3279     (save-restriction
3280       (let ((point (point)))
3281         (narrow-to-region point (point-max))
3282         (message-goto-signature)
3283         (unless (eobp)
3284           (if (and arg (numberp arg))
3285               (forward-line (- -1 arg))
3286             (end-of-line -1)))
3287         (unless (= point (point))
3288           (kill-region point (point))
3289           (unless (bolp)
3290             (insert "\n")))))))
3291
3292 (defun message-newline-and-reformat (&optional arg not-break)
3293   "Insert four newlines, and then reformat if inside quoted text.
3294 Prefix arg means justify as well."
3295   (interactive (list (if current-prefix-arg 'full)))
3296   (let (quoted point beg end leading-space bolp fill-paragraph-function)
3297     (setq point (point))
3298     (beginning-of-line)
3299     (setq beg (point))
3300     (setq bolp (= beg point))
3301     ;; Find first line of the paragraph.
3302     (if not-break
3303         (while (and (not (eobp))
3304                     (not (looking-at message-cite-prefix-regexp))
3305                     (looking-at paragraph-start))
3306           (forward-line 1)))
3307     ;; Find the prefix
3308     (when (looking-at message-cite-prefix-regexp)
3309       (setq quoted (match-string 0))
3310       (goto-char (match-end 0))
3311       (looking-at "[ \t]*")
3312       (setq leading-space (match-string 0)))
3313     (if (and quoted
3314              (not not-break)
3315              (not bolp)
3316              (< (- point beg) (length quoted)))
3317         ;; break inside the cite prefix.
3318         (setq quoted nil
3319               end nil))
3320     (if quoted
3321         (progn
3322           (forward-line 1)
3323           (while (and (not (eobp))
3324                       (not (looking-at paragraph-separate))
3325                       (looking-at message-cite-prefix-regexp)
3326                       (equal quoted (match-string 0)))
3327             (goto-char (match-end 0))
3328             (looking-at "[ \t]*")
3329             (if (> (length leading-space) (length (match-string 0)))
3330                 (setq leading-space (match-string 0)))
3331             (forward-line 1))
3332           (setq end (point))
3333           (goto-char beg)
3334           (while (and (if (bobp) nil (forward-line -1) t)
3335                       (not (looking-at paragraph-start))
3336                       (looking-at message-cite-prefix-regexp)
3337                       (equal quoted (match-string 0)))
3338             (setq beg (point))
3339             (goto-char (match-end 0))
3340             (looking-at "[ \t]*")
3341             (if (> (length leading-space) (length (match-string 0)))
3342                 (setq leading-space (match-string 0)))))
3343       (while (and (not (eobp))
3344                   (not (looking-at paragraph-separate))
3345                   (not (looking-at message-cite-prefix-regexp)))
3346         (forward-line 1))
3347       (setq end (point))
3348       (goto-char beg)
3349       (while (and (if (bobp) nil (forward-line -1) t)
3350                   (not (looking-at paragraph-start))
3351                   (not (looking-at message-cite-prefix-regexp)))
3352         (setq beg (point))))
3353     (goto-char point)
3354     (save-restriction
3355       (narrow-to-region beg end)
3356       (if not-break
3357           (setq point nil)
3358         (if bolp
3359             (newline)
3360           (newline)
3361           (newline))
3362         (setq point (point))
3363         ;; (newline 2) doesn't mark both newline's as hard, so call
3364         ;; newline twice. -jas
3365         (newline)
3366         (newline)
3367         (delete-region (point) (re-search-forward "[ \t]*"))
3368         (when (and quoted (not bolp))
3369           (insert quoted leading-space)))
3370       (undo-boundary)
3371       (if quoted
3372           (let* ((adaptive-fill-regexp
3373                   (regexp-quote (concat quoted leading-space)))
3374                  (adaptive-fill-first-line-regexp
3375                   adaptive-fill-regexp ))
3376             (fill-paragraph arg))
3377         (fill-paragraph arg))
3378       (if point (goto-char point)))))
3379
3380 (defun message-fill-paragraph (&optional arg)
3381   "Message specific function to fill a paragraph.
3382 This function is used as the value of `fill-paragraph-function' in
3383 Message buffers and is not meant to be called directly."
3384   (interactive (list (if current-prefix-arg 'full)))
3385   (if (if (boundp 'filladapt-mode) filladapt-mode)
3386       nil
3387     (if (message-point-in-header-p)
3388         (message-fill-field)
3389       (message-newline-and-reformat arg t))
3390     t))
3391
3392 (defun message-point-in-header-p ()
3393   "Return t if point is in the header."
3394   (save-excursion
3395     (not (re-search-backward
3396           (concat "^" (regexp-quote mail-header-separator) "\n") nil t))))
3397
3398 (defun message-do-auto-fill ()
3399   "Like `do-auto-fill', but don't fill in message header."
3400   (unless (message-point-in-header-p)
3401     (do-auto-fill)))
3402
3403 (defun message-insert-signature (&optional force)
3404   "Insert a signature.  See documentation for variable `message-signature'."
3405   (interactive (list 0))
3406   (let* ((signature
3407           (cond
3408            ((and (null message-signature)
3409                  (eq force 0))
3410             (save-excursion
3411               (goto-char (point-max))
3412               (not (re-search-backward message-signature-separator nil t))))
3413            ((and (null message-signature)
3414                  force)
3415             t)
3416            ((functionp message-signature)
3417             (funcall message-signature))
3418            ((listp message-signature)
3419             (eval message-signature))
3420            (t message-signature)))
3421          signature-file)
3422     (setq signature
3423           (cond ((stringp signature)
3424                  signature)
3425                 ((and (eq t signature) message-signature-file)
3426                  (setq signature-file
3427                        (if (and message-signature-directory
3428                                 ;; don't actually use the signature directory
3429                                 ;; if message-signature-file contains a path.
3430                                 (not (file-name-directory
3431                                       message-signature-file)))
3432                            (expand-file-name message-signature-file
3433                                              message-signature-directory)
3434                          message-signature-file))
3435                  (file-exists-p signature-file))))
3436     (when signature
3437       (goto-char (point-max))
3438       ;; Insert the signature.
3439       (unless (bolp)
3440         (insert "\n"))
3441       (when message-signature-insert-empty-line
3442         (insert "\n"))
3443       (insert "-- \n")
3444       (if (eq signature t)
3445           (insert-file-contents signature-file)
3446         (insert signature))
3447       (goto-char (point-max))
3448       (or (bolp) (insert "\n")))))
3449
3450 (defun message-insert-importance-high ()
3451   "Insert header to mark message as important."
3452   (interactive)
3453   (save-excursion
3454     (save-restriction
3455       (message-narrow-to-headers)
3456       (message-remove-header "Importance"))
3457     (message-goto-eoh)
3458     (insert "Importance: high\n")))
3459
3460 (defun message-insert-importance-low ()
3461   "Insert header to mark message as unimportant."
3462   (interactive)
3463   (save-excursion
3464     (save-restriction
3465       (message-narrow-to-headers)
3466       (message-remove-header "Importance"))
3467     (message-goto-eoh)
3468     (insert "Importance: low\n")))
3469
3470 (defun message-insert-or-toggle-importance ()
3471   "Insert a \"Importance: high\" header, or cycle through the header values.
3472 The three allowed values according to RFC 1327 are `high', `normal'
3473 and `low'."
3474   (interactive)
3475   (save-excursion
3476     (let ((new "high")
3477           cur)
3478       (save-restriction
3479         (message-narrow-to-headers)
3480         (when (setq cur (message-fetch-field "Importance"))
3481           (message-remove-header "Importance")
3482           (setq new (cond ((string= cur "high")
3483                            "low")
3484                           ((string= cur "low")
3485                            "normal")
3486                           (t
3487                            "high")))))
3488       (message-goto-eoh)
3489       (insert (format "Importance: %s\n" new)))))
3490
3491 (defun message-insert-disposition-notification-to ()
3492   "Request a disposition notification (return receipt) to this message.
3493 Note that this should not be used in newsgroups."
3494   (interactive)
3495   (save-excursion
3496     (save-restriction
3497       (message-narrow-to-headers)
3498       (message-remove-header "Disposition-Notification-To"))
3499     (message-goto-eoh)
3500     (insert (format "Disposition-Notification-To: %s\n"
3501                     (or (message-field-value "Reply-to")
3502                         (message-field-value "From")
3503                         (message-make-from))))))
3504
3505 (defun message-elide-region (b e)
3506   "Elide the text in the region.
3507 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3508 text was killed."
3509   (interactive "r")
3510   (kill-region b e)
3511   (insert message-elide-ellipsis))
3512
3513 (defvar message-caesar-translation-table nil)
3514
3515 (defun message-caesar-region (b e &optional n)
3516   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3517   (interactive
3518    (list
3519     (min (point) (or (mark t) (point)))
3520     (max (point) (or (mark t) (point)))
3521     (when current-prefix-arg
3522       (prefix-numeric-value current-prefix-arg))))
3523
3524   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3525   (unless (or (zerop n)                 ; no action needed for a rot of 0
3526               (= b e))                  ; no region to rotate
3527     ;; We build the table, if necessary.
3528     (when (or (not message-caesar-translation-table)
3529               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3530       (setq message-caesar-translation-table
3531             (message-make-caesar-translation-table n)))
3532     (translate-region b e message-caesar-translation-table)))
3533
3534 (defun message-make-caesar-translation-table (n)
3535   "Create a rot table with offset N."
3536   (let ((i -1)
3537         (table (make-string 256 0)))
3538     (while (< (incf i) 256)
3539       (aset table i i))
3540     (concat
3541      (substring table 0 ?A)
3542      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3543      (substring table ?A (+ ?A n))
3544      (substring table (+ ?A 26) ?a)
3545      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3546      (substring table ?a (+ ?a n))
3547      (substring table (+ ?a 26) 255))))
3548
3549 (defun message-caesar-buffer-body (&optional rotnum wide)
3550   "Caesar rotate all letters in the current buffer by 13 places.
3551 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3552 With prefix arg, specifies the number of places to rotate each letter forward.
3553 Mail and USENET news headers are not rotated unless WIDE is non-nil."
3554   (interactive (if current-prefix-arg
3555                    (list (prefix-numeric-value current-prefix-arg))
3556                  (list nil)))
3557   (save-excursion
3558     (save-restriction
3559       (when (and (not wide) (message-goto-body))
3560         (narrow-to-region (point) (point-max)))
3561       (message-caesar-region (point-min) (point-max) rotnum))))
3562
3563 (defun message-pipe-buffer-body (program)
3564   "Pipe the message body in the current buffer through PROGRAM."
3565   (save-excursion
3566     (save-restriction
3567       (when (message-goto-body)
3568         (narrow-to-region (point) (point-max)))
3569       (shell-command-on-region
3570        (point-min) (point-max) program nil t))))
3571
3572 (defun message-rename-buffer (&optional enter-string)
3573   "Rename the *message* buffer to \"*message* RECIPIENT\".
3574 If the function is run with a prefix, it will ask for a new buffer
3575 name, rather than giving an automatic name."
3576   (interactive "Pbuffer name: ")
3577   (save-excursion
3578     (save-restriction
3579       (goto-char (point-min))
3580       (narrow-to-region (point)
3581                         (search-forward mail-header-separator nil 'end))
3582       (let* ((mail-to (or
3583                        (if (message-news-p) (message-fetch-field "Newsgroups")
3584                          (message-fetch-field "To"))
3585                        ""))
3586              (mail-trimmed-to
3587               (if (string-match "," mail-to)
3588                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3589                 mail-to))
3590              (name-default (concat "*message* " mail-trimmed-to))
3591              (name (if enter-string
3592                        (read-string "New buffer name: " name-default)
3593                      name-default)))
3594         (rename-buffer name t)))))
3595
3596 (defun message-fill-yanked-message (&optional justifyp)
3597   "Fill the paragraphs of a message yanked into this one.
3598 Numeric argument means justify as well."
3599   (interactive "P")
3600   (save-excursion
3601     (goto-char (point-min))
3602     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3603     (let ((fill-prefix message-yank-prefix))
3604       (fill-individual-paragraphs (point) (point-max) justifyp))))
3605
3606 (defun message-indent-citation (&optional start end yank-only)
3607   "Modify text just inserted from a message to be cited.
3608 The inserted text should be the region.
3609 When this function returns, the region is again around the modified text.
3610
3611 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3612 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3613   (unless start (setq start (point)))
3614   (unless yank-only
3615     ;; Remove unwanted headers.
3616     (when message-ignored-cited-headers
3617       (let (all-removed)
3618         (save-restriction
3619           (narrow-to-region
3620            (goto-char start)
3621            (if (search-forward "\n\n" nil t)
3622                (1- (point))
3623              (point)))
3624           (message-remove-header message-ignored-cited-headers t)
3625           (when (= (point-min) (point-max))
3626             (setq all-removed t))
3627           (goto-char (point-max)))
3628         (if all-removed
3629             (goto-char start)
3630           (forward-line 1))))
3631     ;; Delete blank lines at the start of the buffer.
3632     (while (and (point-min)
3633                 (eolp)
3634                 (not (eobp)))
3635       (message-delete-line))
3636     ;; Delete blank lines at the end of the buffer.
3637     (goto-char (point-max))
3638     (unless (eolp)
3639       (insert "\n"))
3640     (while (and (zerop (forward-line -1))
3641                 (looking-at "$"))
3642       (message-delete-line)))
3643   ;; Do the indentation.
3644   (if (null message-yank-prefix)
3645       (indent-rigidly start (or end (mark t)) message-indentation-spaces)
3646     (save-excursion
3647       (goto-char start)
3648       (while (< (point) (or end (mark t)))
3649         (cond ((looking-at ">")
3650                (insert message-yank-cited-prefix))
3651               ((looking-at "^$")
3652                (insert message-yank-empty-prefix))
3653               (t
3654                (insert message-yank-prefix)))
3655         (forward-line 1))))
3656   (goto-char start))
3657
3658 (defun message-remove-blank-cited-lines (&optional remove)
3659   "Remove cited lines containing only blanks.
3660 If REMOVE is non-nil, remove newlines, too.
3661
3662 To use this automatically, you may add this function to
3663 `gnus-message-setup-hook'."
3664   (interactive "P")
3665   (let ((citexp
3666          (concat
3667           "^\\("
3668           (when (boundp 'message-yank-cited-prefix)
3669             (concat message-yank-cited-prefix "\\|"))
3670           message-yank-prefix
3671           "\\)+ *\n"
3672           )))
3673     (gnus-message 8 "removing `%s'" citexp)
3674     (save-excursion
3675       (message-goto-body)
3676       (while (re-search-forward citexp nil t)
3677         (replace-match (if remove "" "\n"))))))
3678
3679 (defvar message-cite-reply-above nil
3680   "If non-nil, start own text above the quote.
3681
3682 Note: Top posting is bad netiquette.  Don't use it unless you
3683 really must.  You probably want to set variable only for specific
3684 groups, e.g. using `gnus-posting-styles':
3685
3686   (eval (set (make-local-variable 'message-cite-reply-above) t))
3687
3688 This variable has no effect in news postings.")
3689
3690 (defun message-yank-original (&optional arg)
3691   "Insert the message being replied to, if any.
3692 Puts point before the text and mark after.
3693 Normally indents each nonblank line ARG spaces (default 3).  However,
3694 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3695
3696 This function uses `message-cite-function' to do the actual citing.
3697
3698 Just \\[universal-argument] as argument means don't indent, insert no
3699 prefix, and don't delete any headers."
3700   (interactive "P")
3701   (let ((modified (buffer-modified-p))
3702         body-text)
3703     (when (and message-reply-buffer
3704                message-cite-function)
3705       (when message-cite-reply-above
3706         (if (and (not (message-news-p))
3707                  (or (eq message-cite-reply-above 'is-evil)
3708                      (y-or-n-p "\
3709 Top posting is bad netiquette.  Please don't top post unless you really must.
3710 Really top post? ")))
3711             (save-excursion
3712               (setq body-text
3713                     (buffer-substring (message-goto-body)
3714                                       (point-max)))
3715               (delete-region (message-goto-body) (point-max)))
3716           (set (make-local-variable 'message-cite-reply-above) nil)))
3717       (if (bufferp message-reply-buffer)
3718           (delete-windows-on message-reply-buffer t))
3719       (push-mark (save-excursion
3720                    (cond
3721                     ((bufferp message-reply-buffer)
3722                      (insert-buffer-substring message-reply-buffer))
3723                     ((and (consp message-reply-buffer)
3724                           (functionp (car message-reply-buffer)))
3725                      (apply (car message-reply-buffer)
3726                             (cdr message-reply-buffer))))
3727                    (unless (bolp)
3728                      (insert ?\n))
3729                    (point)))
3730       (unless arg
3731         (funcall message-cite-function)
3732         (unless (eq (char-before (mark t)) ?\n)
3733           (let ((pt (point)))
3734             (goto-char (mark t))
3735             (insert-before-markers ?\n)
3736             (goto-char pt))))
3737       (when message-cite-reply-above
3738         (message-goto-body)
3739         (insert body-text)
3740         (insert (if (bolp) "\n" "\n\n"))
3741         (message-goto-body))
3742       ;; Add a `message-setup-very-last-hook' here?
3743       ;; Add `gnus-article-highlight-citation' here?
3744       (unless modified
3745         (setq message-checksum (message-checksum))))))
3746
3747 (defun message-yank-buffer (buffer)
3748   "Insert BUFFER into the current buffer and quote it."
3749   (interactive "bYank buffer: ")
3750   (let ((message-reply-buffer (get-buffer buffer)))
3751     (save-window-excursion
3752       (message-yank-original))))
3753
3754 (defun message-buffers ()
3755   "Return a list of active message buffers."
3756   (let (buffers)
3757     (save-current-buffer
3758       (dolist (buffer (buffer-list t))
3759         (set-buffer buffer)
3760         (when (and (eq major-mode 'message-mode)
3761                    (null message-sent-message-via))
3762           (push (buffer-name buffer) buffers))))
3763     (nreverse buffers)))
3764
3765 (defun message-cite-original-1 (strip-signature)
3766   "Cite an original message.
3767 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3768 original message.
3769
3770 This function uses `mail-citation-hook' if that is non-nil."
3771   (if (and (boundp 'mail-citation-hook)
3772            mail-citation-hook)
3773       (run-hooks 'mail-citation-hook)
3774     (let* ((start (point))
3775            (end (mark t))
3776            (x-no-archive nil)
3777            (functions
3778             (when message-indent-citation-function
3779               (if (listp message-indent-citation-function)
3780                   message-indent-citation-function
3781                 (list message-indent-citation-function))))
3782            ;; This function may be called by `gnus-summary-yank-message' and
3783            ;; may insert a different article from the original.  So, we will
3784            ;; modify the value of `message-reply-headers' with that article.
3785            (message-reply-headers
3786             (save-restriction
3787               (narrow-to-region start end)
3788               (message-narrow-to-head-1)
3789               (setq x-no-archive (message-fetch-field "x-no-archive"))
3790               (vector 0
3791                       (or (message-fetch-field "subject") "none")
3792                       (or (message-fetch-field "from") "nobody")
3793                       (message-fetch-field "date")
3794                       (message-fetch-field "message-id" t)
3795                       (message-fetch-field "references")
3796                       0 0 ""))))
3797       (mml-quote-region start end)
3798       (when strip-signature
3799         ;; Allow undoing.
3800         (undo-boundary)
3801         (goto-char end)
3802         (when (re-search-backward message-signature-separator start t)
3803           ;; Also peel off any blank lines before the signature.
3804           (forward-line -1)
3805           (while (looking-at "^[ \t]*$")
3806             (forward-line -1))
3807           (forward-line 1)
3808           (delete-region (point) end)
3809           (unless (search-backward "\n\n" start t)
3810             ;; Insert a blank line if it is peeled off.
3811             (insert "\n"))))
3812       (goto-char start)
3813       (mapc 'funcall functions)
3814       (when message-citation-line-function
3815         (unless (bolp)
3816           (insert "\n"))
3817         (funcall message-citation-line-function))
3818       (when (and x-no-archive
3819                  (not message-cite-articles-with-x-no-archive)
3820                  (string-match "yes" x-no-archive))
3821         (undo-boundary)
3822         (delete-region (point) (mark t))
3823         (insert "> [Quoted text removed due to X-No-Archive]\n")
3824         (push-mark)
3825         (forward-line -1)))))
3826
3827 (defun message-cite-original ()
3828   "Cite function in the standard Message manner."
3829   (message-cite-original-1 nil))
3830
3831 (defvar gnus-extract-address-components)
3832
3833 (autoload 'format-spec "format-spec")
3834
3835 (defun message-insert-formatted-citation-line (&optional from date)
3836   "Function that inserts a formatted citation line.
3837
3838 See `message-citation-line-format'."
3839   ;; The optional args are for testing/debugging.  They will disappear later.
3840   ;; Example:
3841   ;; (with-temp-buffer
3842   ;;   (message-insert-formatted-citation-line
3843   ;;    "John Doe <john.doe@example.invalid>"
3844   ;;    (current-time))
3845   ;;   (buffer-string))
3846   (when (or message-reply-headers (and from date))
3847     (unless from
3848       (setq from (mail-header-from message-reply-headers)))
3849     (let* ((data (condition-case ()
3850                      (funcall (if (boundp gnus-extract-address-components)
3851                                   gnus-extract-address-components
3852                                 'mail-extract-address-components)
3853                               from)
3854                    (error nil)))
3855            (name (car data))
3856            (fname name)
3857            (lname name)
3858            (net (car (cdr data)))
3859            (name-or-net (or (car data)
3860                             (car (cdr data)) from))
3861            (replydate
3862             (or
3863              date
3864              ;; We need Gnus functionality if the user wants date or time from
3865              ;; the original article:
3866              (when (string-match "%[^fnNFL]" message-citation-line-format)
3867                (autoload 'gnus-date-get-time "gnus-util")
3868                (gnus-date-get-time (mail-header-date message-reply-headers)))))
3869            (flist
3870             (let ((i ?A) lst)
3871               (when (stringp name)
3872                 ;; Guess first name and last name:
3873                 (cond ((string-match
3874                         "\\`\\(\\w\\|[-.]\\)+ \\(\\w\\|[-.]\\)+\\'" name)
3875                        (setq fname (nth 0 (split-string name "[ \t]+"))
3876                              lname (nth 1 (split-string name "[ \t]+"))))
3877                       ((string-match
3878                         "\\`\\(\\w\\|[-.]\\)+, \\(\\w\\|[-.]\\)+\\'" name)
3879                        (setq fname (nth 1 (split-string name "[ \t,]+"))
3880                              lname (nth 0 (split-string name "[ \t,]+"))))
3881                       ((string-match
3882                         "\\`\\(\\w\\|[-.]\\)+\\'" name)
3883                        (setq fname name
3884                              lname ""))))
3885               ;; The following letters are not used in `format-time-string':
3886               (push ?E lst) (push "<E>" lst)
3887               (push ?F lst) (push fname lst)
3888               ;; We might want to use "" instead of "<X>" later.
3889               (push ?J lst) (push "<J>" lst)
3890               (push ?K lst) (push "<K>" lst)
3891               (push ?L lst) (push lname lst)
3892               (push ?N lst) (push name-or-net lst)
3893               (push ?O lst) (push "<O>" lst)
3894               (push ?P lst) (push "<P>" lst)
3895               (push ?Q lst) (push "<Q>" lst)
3896               (push ?f lst) (push from lst)
3897               (push ?i lst) (push "<i>" lst)
3898               (push ?n lst) (push net lst)
3899               (push ?o lst) (push "<o>" lst)
3900               (push ?q lst) (push "<q>" lst)
3901               (push ?t lst) (push "<t>" lst)
3902               (push ?v lst) (push "<v>" lst)
3903               ;; Delegate the rest to `format-time-string':
3904               (while (<= i ?z)
3905                 (when (and (not (memq i lst))
3906                            ;; Skip (Z,a)
3907                            (or (<= i ?Z)
3908                                (>= i ?a)))
3909                   (push i lst)
3910                   (push (condition-case nil
3911                             (format-time-string (format "%%%c" i) replydate)
3912                           (error (format ">%c<" i)))
3913                         lst))
3914                 (setq i (1+ i)))
3915               (reverse lst)))
3916            (spec (apply 'format-spec-make flist)))
3917       (insert (format-spec message-citation-line-format spec)))
3918     (newline)))
3919
3920 (defun message-cite-original-without-signature ()
3921   "Cite function in the standard Message manner.
3922 This function strips off the signature from the original message."
3923   (message-cite-original-1 t))
3924
3925 (defun message-insert-citation-line ()
3926   "Insert a simple citation line."
3927   (when message-reply-headers
3928     (insert (mail-header-from message-reply-headers) " writes:")
3929     (newline)
3930     (newline)))
3931
3932 (defun message-position-on-field (header &rest afters)
3933   (let ((case-fold-search t))
3934     (save-restriction
3935       (narrow-to-region
3936        (goto-char (point-min))
3937        (progn
3938          (re-search-forward
3939           (concat "^" (regexp-quote mail-header-separator) "$"))
3940          (match-beginning 0)))
3941       (goto-char (point-min))
3942       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
3943           (progn
3944             (re-search-forward "^[^ \t]" nil 'move)
3945             (beginning-of-line)
3946             (skip-chars-backward "\n")
3947             t)
3948         (while (and afters
3949                     (not (re-search-forward
3950                           (concat "^" (regexp-quote (car afters)) ":")
3951                           nil t)))
3952           (pop afters))
3953         (when afters
3954           (re-search-forward "^[^ \t]" nil 'move)
3955           (beginning-of-line))
3956         (insert header ": \n")
3957         (forward-char -1)
3958         nil))))
3959
3960 (defun message-remove-signature ()
3961   "Remove the signature from the text between point and mark.
3962 The text will also be indented the normal way."
3963   (save-excursion
3964     (let ((start (point))
3965           mark)
3966       (if (not (re-search-forward message-signature-separator (mark t) t))
3967           ;; No signature here, so we just indent the cited text.
3968           (message-indent-citation)
3969         ;; Find the last non-empty line.
3970         (forward-line -1)
3971         (while (looking-at "[ \t]*$")
3972           (forward-line -1))
3973         (forward-line 1)
3974         (setq mark (set-marker (make-marker) (point)))
3975         (goto-char start)
3976         (message-indent-citation)
3977         ;; Enable undoing the deletion.
3978         (undo-boundary)
3979         (delete-region mark (mark t))
3980         (set-marker mark nil)))))
3981
3982 \f
3983
3984 ;;;
3985 ;;; Sending messages
3986 ;;;
3987
3988 (defun message-send-and-exit (&optional arg)
3989   "Send message like `message-send', then, if no errors, exit from mail buffer."
3990   (interactive "P")
3991   (let ((buf (current-buffer))
3992         (actions message-exit-actions))
3993     (when (and (message-send arg)
3994                (buffer-name buf))
3995       (if message-kill-buffer-on-exit
3996           (kill-buffer buf)
3997         (bury-buffer buf)
3998         (when (eq buf (current-buffer))
3999           (message-bury buf)))
4000       (message-do-actions actions)
4001       t)))
4002
4003 (defun message-dont-send ()
4004   "Don't send the message you have been editing.
4005 Instead, just auto-save the buffer and then bury it."
4006   (interactive)
4007   (set-buffer-modified-p t)
4008   (save-buffer)
4009   (let ((actions message-postpone-actions))
4010     (message-bury (current-buffer))
4011     (message-do-actions actions)))
4012
4013 (defun message-kill-buffer ()
4014   "Kill the current buffer."
4015   (interactive)
4016   (when (or (not (buffer-modified-p))
4017             (not message-kill-buffer-query)
4018             (yes-or-no-p "Message modified; kill anyway? "))
4019     (let ((actions message-kill-actions)
4020           (draft-article message-draft-article)
4021           (auto-save-file-name buffer-auto-save-file-name)
4022           (file-name buffer-file-name)
4023           (modified (buffer-modified-p)))
4024       (setq buffer-file-name nil)
4025       (kill-buffer (current-buffer))
4026       (when (and (or (and auto-save-file-name
4027                           (file-exists-p auto-save-file-name))
4028                      (and file-name
4029                           (file-exists-p file-name)))
4030                  (progn
4031                    ;; If the message buffer has lived in a dedicated window,
4032                    ;; `kill-buffer' has killed the frame.  Thus the
4033                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
4034                    ;; that the user can see the question by raising the
4035                    ;; current frame:
4036                    (raise-frame)
4037                    (yes-or-no-p (format "Remove the backup file%s? "
4038                                         (if modified " too" "")))))
4039         (ignore-errors
4040           (delete-file auto-save-file-name))
4041         (let ((message-draft-article draft-article))
4042           (message-disassociate-draft)))
4043       (message-do-actions actions))))
4044
4045 (defun message-bury (buffer)
4046   "Bury this mail BUFFER."
4047   (let ((newbuf (other-buffer buffer)))
4048     (bury-buffer buffer)
4049     (if (and (window-dedicated-p (selected-window))
4050              (not (null (delq (selected-frame) (visible-frame-list)))))
4051         (delete-frame (selected-frame))
4052       (switch-to-buffer newbuf))))
4053
4054 (defun message-send (&optional arg)
4055   "Send the message in the current buffer.
4056 If `message-interactive' is non-nil, wait for success indication or
4057 error messages, and inform user.
4058 Otherwise any failure is reported in a message back to the user from
4059 the mailer.
4060 The usage of ARG is defined by the instance that called Message.
4061 It should typically alter the sending method in some way or other."
4062   (interactive "P")
4063   ;; Make it possible to undo the coming changes.
4064   (undo-boundary)
4065   (let ((inhibit-read-only t))
4066     (put-text-property (point-min) (point-max) 'read-only nil))
4067   (message-fix-before-sending)
4068   (run-hooks 'message-send-hook)
4069   (when message-confirm-send
4070     (or (y-or-n-p "Send message? ")
4071         (keyboard-quit)))
4072   (message message-sending-message)
4073   (let ((alist message-send-method-alist)
4074         (success t)
4075         elem sent dont-barf-on-no-method
4076         (message-options message-options))
4077     (message-options-set-recipient)
4078     (while (and success
4079                 (setq elem (pop alist)))
4080       (when (funcall (cadr elem))
4081         (when (and (or (not (memq (car elem)
4082                                   message-sent-message-via))
4083                        (message-fetch-field "supersedes")
4084                        (if (or (message-gnksa-enable-p 'multiple-copies)
4085                                (not (eq (car elem) 'news)))
4086                            (y-or-n-p
4087                             (format
4088                              "Already sent message via %s; resend? "
4089                              (car elem)))
4090                          (error "Denied posting -- multiple copies")))
4091                    (setq success (funcall (caddr elem) arg)))
4092           (setq sent t))))
4093     (unless (or sent
4094                 (not success)
4095                 (let ((fcc (message-fetch-field "Fcc"))
4096                       (gcc (message-fetch-field "Gcc")))
4097                   (when (or fcc gcc)
4098                     (or (eq message-allow-no-recipients 'always)
4099                         (and (not (eq message-allow-no-recipients 'never))
4100                              (setq dont-barf-on-no-method
4101                                    (gnus-y-or-n-p
4102                                     (format "No receiver, perform %s anyway? "
4103                                             (cond ((and fcc gcc) "Fcc and Gcc")
4104                                                   (fcc "Fcc")
4105                                                   (t "Gcc"))))))))))
4106       (error "No methods specified to send by"))
4107     (when (or dont-barf-on-no-method
4108               (and success sent))
4109       (message-do-fcc)
4110       (save-excursion
4111         (run-hooks 'message-sent-hook))
4112       (message "Sending...done")
4113       ;; Do ecomplete address snarfing.
4114       (when (and (message-mail-alias-type-p 'ecomplete)
4115                  (not message-inhibit-ecomplete))
4116         (message-put-addresses-in-ecomplete))
4117       ;; Mark the buffer as unmodified and delete auto-save.
4118       (set-buffer-modified-p nil)
4119       (delete-auto-save-file-if-necessary t)
4120       (message-disassociate-draft)
4121       ;; Delete other mail buffers and stuff.
4122       (message-do-send-housekeeping)
4123       (message-do-actions message-send-actions)
4124       ;; Return success.
4125       t)))
4126
4127 (defun message-send-via-mail (arg)
4128   "Send the current message via mail."
4129   (message-send-mail arg))
4130
4131 (defun message-send-via-news (arg)
4132   "Send the current message via news."
4133   (funcall message-send-news-function arg))
4134
4135 (defmacro message-check (type &rest forms)
4136   "Eval FORMS if TYPE is to be checked."
4137   `(or (message-check-element ,type)
4138        (save-excursion
4139          ,@forms)))
4140
4141 (put 'message-check 'lisp-indent-function 1)
4142 (put 'message-check 'edebug-form-spec '(form body))
4143
4144 (defun message-text-with-property (prop &optional start end reverse)
4145   "Return a list of start and end positions where the text has PROP.
4146 START and END bound the search, they default to `point-min' and
4147 `point-max' respectively.  If REVERSE is non-nil, find text which does
4148 not have PROP."
4149   (unless start
4150     (setq start (point-min)))
4151   (unless end
4152     (setq end (point-max)))
4153   (let (next regions)
4154     (if reverse
4155         (while (and start
4156                     (setq start (text-property-any start end prop nil)))
4157           (setq next (next-single-property-change start prop nil end))
4158           (push (cons start (or next end)) regions)
4159           (setq start next))
4160       (while (and start
4161                   (or (get-text-property start prop)
4162                       (and (setq start (next-single-property-change
4163                                         start prop nil end))
4164                            (get-text-property start prop))))
4165         (setq next (text-property-any start end prop nil))
4166         (push (cons start (or next end)) regions)
4167         (setq start next)))
4168     (nreverse regions)))
4169
4170 (defcustom message-bogus-addresses
4171   ;; '("noreply" "nospam" "invalid")
4172   '("noreply" "nospam" "invalid" "@@" "[^[:ascii:]].*@" "[ \t]")
4173   "List of regexps of potentially bogus mail addresses.
4174 See `message-check-recipients' how to setup checking.
4175
4176 This list should make it possible to catch typos or warn about
4177 spam-trap addresses.  It doesn't aim to verify strict RFC
4178 conformance."
4179   :version "23.1" ;; No Gnus
4180   :group 'message-headers
4181   :type '(choice
4182           (const :tag "None" nil)
4183           (list
4184            (set :inline t
4185                 (const "noreply")
4186                 (const "nospam")
4187                 (const "invalid")
4188                 (const :tag "duplicate @" "@@")
4189                 (const :tag "non-ascii local part" "[^[:ascii:]].*@")
4190                 ;; Already caught by `message-valid-fqdn-regexp'
4191                 ;; (const :tag "`_' in domain part" "@.*_")
4192                 (const :tag "whitespace" "[ \t]"))
4193            (repeat :inline t
4194                    :tag "Other"
4195                    (regexp)))))
4196
4197 (defun message-fix-before-sending ()
4198   "Do various things to make the message nice before sending it."
4199   ;; Make sure there's a newline at the end of the message.
4200   (goto-char (point-max))
4201   (unless (bolp)
4202     (insert "\n"))
4203   ;; Make the hidden headers visible.
4204   (widen)
4205   ;; Sort headers before sending the message.
4206   (message-sort-headers)
4207   ;; Make invisible text visible.
4208   ;; It doesn't seem as if this is useful, since the invisible property
4209   ;; is clobbered by an after-change hook anyhow.
4210   (message-check 'invisible-text
4211     (let ((regions (message-text-with-property 'invisible))
4212           from to)
4213       (when regions
4214         (while regions
4215           (setq from (caar regions)
4216                 to (cdar regions)
4217                 regions (cdr regions))
4218           (put-text-property from to 'invisible nil)
4219           (message-overlay-put (message-make-overlay from to)
4220                                'face 'highlight))
4221         (unless (yes-or-no-p
4222                  "Invisible text found and made visible; continue sending? ")
4223           (error "Invisible text found and made visible")))))
4224   (message-check 'illegible-text
4225     (let (char found choice)
4226       (message-goto-body)
4227       (while (progn
4228                (skip-chars-forward mm-7bit-chars)
4229                (when (get-text-property (point) 'no-illegible-text)
4230                  ;; There is a signed or encrypted raw message part
4231                  ;; that is considered to be safe.
4232                  (goto-char (or (next-single-property-change
4233                                  (point) 'no-illegible-text)
4234                                 (point-max))))
4235                (setq char (char-after)))
4236         (when (or (< (mm-char-int char) 128)
4237                   (and (mm-multibyte-p)
4238                        (memq (char-charset char)
4239                              '(eight-bit-control eight-bit-graphic
4240                                                  ;; Emacs 23, Bug#1770:
4241                                                  eight-bit
4242                                                  control-1))
4243                        (not (get-text-property
4244                              (point) 'untranslated-utf-8))))
4245           (message-overlay-put (message-make-overlay (point) (1+ (point)))
4246                                'face 'highlight)
4247           (setq found t))
4248         (forward-char))
4249       (when found
4250         (setq choice
4251               (gnus-multiple-choice
4252                "Non-printable characters found.  Continue sending?"
4253                `((?d "Remove non-printable characters and send")
4254                  (?r ,(format
4255                        "Replace non-printable characters with \"%s\" and send"
4256                        message-replacement-char))
4257                  (?s "Send as is without removing anything")
4258                  (?e "Continue editing"))))
4259         (if (eq choice ?e)
4260           (error "Non-printable characters"))
4261         (message-goto-body)
4262         (skip-chars-forward mm-7bit-chars)
4263         (while (not (eobp))
4264           (when (let ((char (char-after)))
4265                   (or (< (mm-char-int char) 128)
4266                       (and (mm-multibyte-p)
4267                            ;; FIXME: Wrong for Emacs 23 (unicode) and for
4268                            ;; things like undecodable utf-8 (in Emacs 21?).
4269                            ;; Should at least use find-coding-systems-region.
4270                            ;; -- fx
4271                            (memq (char-charset char)
4272                                  '(eight-bit-control eight-bit-graphic
4273                                                      ;; Emacs 23, Bug#1770:
4274                                                      eight-bit
4275                                                      control-1))
4276                            (not (get-text-property
4277                                  (point) 'untranslated-utf-8)))))
4278             (if (eq choice ?i)
4279                 (message-kill-all-overlays)
4280               (delete-char 1)
4281               (when (eq choice ?r)
4282                 (insert message-replacement-char))))
4283           (forward-char)
4284           (skip-chars-forward mm-7bit-chars)))))
4285   (message-check 'bogus-recipient
4286     ;; Warn before sending a mail to an invalid address.
4287     (message-check-recipients)))
4288
4289 (defun message-bogus-recipient-p (recipients)
4290   "Check if a mail address in RECIPIENTS looks bogus.
4291
4292 RECIPIENTS is a mail header.  Return a list of potentially bogus
4293 addresses.  If none is found, return nil.
4294
4295 An address might be bogus if the domain part is not fully
4296 qualified, see `message-valid-fqdn-regexp', or if there's a
4297 matching entry in `message-bogus-addresses'."
4298   ;; FIXME: How about "foo@subdomain", when the MTA adds ".domain.tld"?
4299   (let (found)
4300     (mapc (lambda (address)
4301             (setq address (cadr address))
4302             (when
4303                 (or (not
4304                      (or
4305                       (not (string-match "@" address))
4306                       (string-match
4307                        (concat ".@.*\\("
4308                                message-valid-fqdn-regexp "\\)\\'") address)))
4309                     (and message-bogus-addresses
4310                          (let ((re
4311                                 (if (listp message-bogus-addresses)
4312                                     (mapconcat 'identity
4313                                                message-bogus-addresses
4314                                                "\\|")
4315                                   message-bogus-addresses)))
4316                            (string-match re address))))
4317                          (push address found)))
4318           ;;
4319           (mail-extract-address-components recipients t))
4320     found))
4321
4322 (defun message-check-recipients ()
4323   "Warn before composing or sending a mail to an invalid address.
4324
4325 This function could be useful in `message-setup-hook'."
4326   (interactive)
4327   (save-restriction
4328     (message-narrow-to-headers)
4329     (dolist (hdr '("To" "Cc" "Bcc"))
4330       (let ((addr (message-fetch-field hdr)))
4331         (when (stringp addr)
4332           (dolist (bog (message-bogus-recipient-p addr))
4333             (and bog
4334                  (not (y-or-n-p
4335                        (format
4336                         "Address `%s' might be bogus.  Continue? " bog)))
4337                  (error "Bogus address"))))))))
4338
4339 (custom-add-option 'message-setup-hook 'message-check-recipients)
4340
4341 (defun message-add-action (action &rest types)
4342   "Add ACTION to be performed when doing an exit of type TYPES."
4343   (while types
4344     (add-to-list (intern (format "message-%s-actions" (pop types)))
4345                  action)))
4346
4347 (defun message-delete-action (action &rest types)
4348   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4349   (let (var)
4350     (while types
4351       (set (setq var (intern (format "message-%s-actions" (pop types))))
4352            (delq action (symbol-value var))))))
4353
4354 (defun message-do-actions (actions)
4355   "Perform all actions in ACTIONS."
4356   ;; Now perform actions on successful sending.
4357   (dolist (action actions)
4358     (ignore-errors
4359       (cond
4360        ;; A simple function.
4361        ((functionp action)
4362         (funcall action))
4363        ;; Something to be evaled.
4364        (t
4365         (eval action))))))
4366
4367 (defun message-send-mail-partially ()
4368   "Send mail as message/partial."
4369   ;; replace the header delimiter with a blank line
4370   (goto-char (point-min))
4371   (re-search-forward
4372    (concat "^" (regexp-quote mail-header-separator) "\n"))
4373   (replace-match "\n")
4374   (run-hooks 'message-send-mail-hook)
4375   (let ((p (goto-char (point-min)))
4376         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4377         (curbuf (current-buffer))
4378         (id (message-make-message-id)) (n 1)
4379         plist total  header required-mail-headers)
4380     (while (not (eobp))
4381       (if (< (point-max) (+ p message-send-mail-partially-limit))
4382           (goto-char (point-max))
4383         (goto-char (+ p message-send-mail-partially-limit))
4384         (beginning-of-line)
4385         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4386       (push p plist)
4387       (setq p (point)))
4388     (setq total (length plist))
4389     (push (point-max) plist)
4390     (setq plist (nreverse plist))
4391     (unwind-protect
4392         (save-excursion
4393           (setq p (pop plist))
4394           (while plist
4395             (set-buffer curbuf)
4396             (copy-to-buffer tembuf p (car plist))
4397             (set-buffer tembuf)
4398             (goto-char (point-min))
4399             (if header
4400                 (progn
4401                   (goto-char (point-min))
4402                   (narrow-to-region (point) (point))
4403                   (insert header))
4404               (message-goto-eoh)
4405               (setq header (buffer-substring (point-min) (point)))
4406               (goto-char (point-min))
4407               (narrow-to-region (point) (point))
4408               (insert header)
4409               (message-remove-header "Mime-Version")
4410               (message-remove-header "Content-Type")
4411               (message-remove-header "Content-Transfer-Encoding")
4412               (message-remove-header "Message-ID")
4413               (message-remove-header "Lines")
4414               (goto-char (point-max))
4415               (insert "Mime-Version: 1.0\n")
4416               (setq header (buffer-string)))
4417             (goto-char (point-max))
4418             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4419                             id n total))
4420             (forward-char -1)
4421             (let ((mail-header-separator ""))
4422               (when (memq 'Message-ID message-required-mail-headers)
4423                 (insert "Message-ID: " (message-make-message-id) "\n"))
4424               (when (memq 'Lines message-required-mail-headers)
4425                 (insert "Lines: " (message-make-lines) "\n"))
4426               (message-goto-subject)
4427               (end-of-line)
4428               (insert (format " (%d/%d)" n total))
4429               (widen)
4430               (funcall (or message-send-mail-real-function
4431                            message-send-mail-function)))
4432             (setq n (+ n 1))
4433             (setq p (pop plist))
4434             (erase-buffer)))
4435       (kill-buffer tembuf))))
4436
4437 (declare-function hashcash-wait-async "hashcash" (&optional buffer))
4438
4439 (defun message-send-mail (&optional arg)
4440   (require 'mail-utils)
4441   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4442          (case-fold-search nil)
4443          (news (message-news-p))
4444          (mailbuf (current-buffer))
4445          (message-this-is-mail t)
4446          ;; gnus-setup-posting-charset is autoloaded in mml.el (FIXME
4447          ;; maybe it should not be), which this file requires.  Hence
4448          ;; the fboundp test is always true.  Loading it from gnus-msg
4449          ;; loads many Gnus files (Bug#5642).  If
4450          ;; gnus-group-posting-charset-alist hasn't been customized,
4451          ;; this is just going to return nil anyway.  FIXME it would
4452          ;; be good to improve this further, because even if g-g-p-c-a
4453          ;; has been customized, that is likely to just be for news.
4454          ;; Eg either move the definition from gnus-msg, or separate out
4455          ;; the mail and news parts.
4456          (message-posting-charset
4457           (if (and (fboundp 'gnus-setup-posting-charset)
4458                    (boundp 'gnus-group-posting-charset-alist))
4459               (gnus-setup-posting-charset nil)
4460             message-posting-charset))
4461          (headers message-required-mail-headers))
4462     (when (and message-generate-hashcash
4463                (not (eq message-generate-hashcash 'opportunistic)))
4464       (message "Generating hashcash...")
4465       (require 'hashcash)
4466       ;; Wait for calculations already started to finish...
4467       (hashcash-wait-async)
4468       ;; ...and do calculations not already done.  mail-add-payment
4469       ;; will leave existing X-Hashcash headers alone.
4470       (mail-add-payment)
4471       (message "Generating hashcash...done"))
4472     (save-restriction
4473       (message-narrow-to-headers)
4474       ;; Generate the Mail-Followup-To header if the header is not there...
4475       (if (and (message-subscribed-p)
4476                (not (mail-fetch-field "mail-followup-to")))
4477           (setq headers
4478                 (cons
4479                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4480                  message-required-mail-headers))
4481         ;; otherwise, delete the MFT header if the field is empty
4482         (when (equal "" (mail-fetch-field "mail-followup-to"))
4483           (message-remove-header "^Mail-Followup-To:")))
4484       ;; Insert some headers.
4485       (let ((message-deletable-headers
4486              (if news nil message-deletable-headers)))
4487         (message-generate-headers headers))
4488       ;; Check continuation headers.
4489       (message-check 'continuation-headers
4490         (goto-char (point-min))
4491         (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
4492           (goto-char (match-beginning 0))
4493           (if (y-or-n-p "Fix continuation lines? ")
4494               (insert " ")
4495             (forward-line 1)
4496             (unless (y-or-n-p "Send anyway? ")
4497               (error "Failed to send the message")))))
4498       ;; Let the user do all of the above.
4499       (run-hooks 'message-header-hook))
4500     (unwind-protect
4501         (with-current-buffer tembuf
4502           (erase-buffer)
4503           ;; Avoid copying text props (except hard newlines).
4504           (insert (with-current-buffer mailbuf
4505                     (mml-buffer-substring-no-properties-except-hard-newlines
4506                      (point-min) (point-max))))
4507           ;; Remove some headers.
4508           (message-encode-message-body)
4509           (save-restriction
4510             (message-narrow-to-headers)
4511             ;; We (re)generate the Lines header.
4512             (when (memq 'Lines message-required-mail-headers)
4513               (message-generate-headers '(Lines)))
4514             ;; Remove some headers.
4515             (message-remove-header message-ignored-mail-headers t)
4516             (let ((mail-parse-charset message-default-charset))
4517               (mail-encode-encoded-word-buffer)))
4518           (goto-char (point-max))
4519           ;; require one newline at the end.
4520           (or (= (preceding-char) ?\n)
4521               (insert ?\n))
4522           (message-cleanup-headers)
4523           ;; FIXME: we're inserting the courtesy copy after encoding.
4524           ;; This is wrong if the courtesy copy string contains
4525           ;; non-ASCII characters. -- jh
4526           (when
4527               (save-restriction
4528                 (message-narrow-to-headers)
4529                 (and news
4530                      (not (message-fetch-field "List-Post"))
4531                      (not (message-fetch-field "List-ID"))
4532                      (or (message-fetch-field "cc")
4533                          (message-fetch-field "bcc")
4534                          (message-fetch-field "to"))
4535                      (let ((content-type (message-fetch-field
4536                                           "content-type")))
4537                        (and
4538                         (or
4539                          (not content-type)
4540                          (string= "text/plain"
4541                                   (car
4542                                    (mail-header-parse-content-type
4543                                     content-type))))
4544                         (not
4545                          (string= "base64"
4546                                   (message-fetch-field
4547                                    "content-transfer-encoding")))))))
4548             (message-insert-courtesy-copy
4549              (with-current-buffer mailbuf
4550                message-courtesy-message)))
4551           ;; Let's make sure we encoded all the body.
4552           (assert (save-excursion
4553                     (goto-char (point-min))
4554                     (not (re-search-forward "[^\000-\377]" nil t))))
4555           (mm-disable-multibyte)
4556           (if (or (not message-send-mail-partially-limit)
4557                   (< (buffer-size) message-send-mail-partially-limit)
4558                   (not (message-y-or-n-p
4559                         "The message size is too large, split? "
4560                         t
4561                         "\
4562 The message size, "
4563                         (/ (buffer-size) 1000) "KB, is too large.
4564
4565 Some mail gateways (MTA's) bounce large messages.  To avoid the
4566 problem, answer `y', and the message will be split into several
4567 smaller pieces, the size of each is about "
4568                         (/ message-send-mail-partially-limit 1000)
4569                         "KB except the last
4570 one.
4571
4572 However, some mail readers (MUA's) can't read split messages, i.e.,
4573 mails in message/partially format. Answer `n', and the message will be
4574 sent in one piece.
4575
4576 The size limit is controlled by `message-send-mail-partially-limit'.
4577 If you always want Gnus to send messages in one piece, set
4578 `message-send-mail-partially-limit' to nil.
4579 ")))
4580               (progn
4581                 (message "Sending via mail...")
4582                 (funcall (or message-send-mail-real-function
4583                              message-send-mail-function)))
4584             (message-send-mail-partially)))
4585       (kill-buffer tembuf))
4586     (set-buffer mailbuf)
4587     (push 'mail message-sent-message-via)))
4588
4589 (defun message-send-mail-with-sendmail ()
4590   "Send off the prepared buffer with sendmail."
4591   (require 'sendmail)
4592   (let ((errbuf (if message-interactive
4593                     (message-generate-new-buffer-clone-locals
4594                      " sendmail errors")
4595                   0))
4596         resend-to-addresses delimline)
4597     (unwind-protect
4598         (progn
4599           (let ((case-fold-search t))
4600             (save-restriction
4601               (message-narrow-to-headers)
4602               (setq resend-to-addresses (message-fetch-field "resent-to")))
4603             ;; Change header-delimiter to be what sendmail expects.
4604             (goto-char (point-min))
4605             (re-search-forward
4606              (concat "^" (regexp-quote mail-header-separator) "\n"))
4607             (replace-match "\n")
4608             (backward-char 1)
4609             (setq delimline (point-marker))
4610             (run-hooks 'message-send-mail-hook)
4611             ;; Insert an extra newline if we need it to work around
4612             ;; Sun's bug that swallows newlines.
4613             (goto-char (1+ delimline))
4614             (when (eval message-mailer-swallows-blank-line)
4615               (newline))
4616             (when message-interactive
4617               (with-current-buffer errbuf
4618                 (erase-buffer))))
4619           (let* ((default-directory "/")
4620                  (coding-system-for-write message-send-coding-system)
4621                  (cpr (apply
4622                        'call-process-region
4623                        (append
4624                         (list (point-min) (point-max)
4625                               (cond ((boundp 'sendmail-program)
4626                                      sendmail-program)
4627                                     ((file-exists-p "/usr/sbin/sendmail")
4628                                      "/usr/sbin/sendmail")
4629                                     ((file-exists-p "/usr/lib/sendmail")
4630                                      "/usr/lib/sendmail")
4631                                     ((file-exists-p "/usr/ucblib/sendmail")
4632                                      "/usr/ucblib/sendmail")
4633                                     (t "fakemail"))
4634                               nil errbuf nil "-oi")
4635                         message-sendmail-extra-arguments
4636                         ;; Always specify who from,
4637                         ;; since some systems have broken sendmails.
4638                         ;; But some systems are more broken with -f, so
4639                         ;; we'll let users override this.
4640                         (and (null message-sendmail-f-is-evil)
4641                              (list "-f" (message-sendmail-envelope-from)))
4642                         ;; These mean "report errors by mail"
4643                         ;; and "deliver in background".
4644                         (if (null message-interactive) '("-oem" "-odb"))
4645                         ;; Get the addresses from the message
4646                         ;; unless this is a resend.
4647                         ;; We must not do that for a resend
4648                         ;; because we would find the original addresses.
4649                         ;; For a resend, include the specific addresses.
4650                         (if resend-to-addresses
4651                             (list resend-to-addresses)
4652                           '("-t"))))))
4653             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4654               (if errbuf (pop-to-buffer errbuf))
4655               (error "Sending...failed with exit value %d" cpr)))
4656           (when message-interactive
4657             (with-current-buffer errbuf
4658               (goto-char (point-min))
4659               (while (re-search-forward "\n+ *" nil t)
4660                 (replace-match "; "))
4661               (if (not (zerop (buffer-size)))
4662                   (error "Sending...failed to %s"
4663                          (buffer-string))))))
4664       (when (bufferp errbuf)
4665         (kill-buffer errbuf)))))
4666
4667 (defun message-send-mail-with-qmail ()
4668   "Pass the prepared message buffer to qmail-inject.
4669 Refer to the documentation for the variable `message-send-mail-function'
4670 to find out how to use this."
4671   ;; replace the header delimiter with a blank line
4672   (goto-char (point-min))
4673   (re-search-forward
4674    (concat "^" (regexp-quote mail-header-separator) "\n"))
4675   (replace-match "\n")
4676   (run-hooks 'message-send-mail-hook)
4677   ;; send the message
4678   (case
4679       (let ((coding-system-for-write message-send-coding-system))
4680         (apply
4681          'call-process-region (point-min) (point-max)
4682          message-qmail-inject-program nil nil nil
4683          ;; qmail-inject's default behavior is to look for addresses on the
4684          ;; command line; if there're none, it scans the headers.
4685          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4686          ;;
4687          ;; in general, ALL of qmail-inject's defaults are perfect for simply
4688          ;; reading a formatted (i. e., at least a To: or Resent-To header)
4689          ;; message from stdin.
4690          ;;
4691          ;; qmail also has the advantage of not having been raped by
4692          ;; various vendors, so we don't have to allow for that, either --
4693          ;; compare this with message-send-mail-with-sendmail and weep
4694          ;; for sendmail's lost innocence.
4695          ;;
4696          ;; all this is way cool coz it lets us keep the arguments entirely
4697          ;; free for -inject-arguments -- a big win for the user and for us
4698          ;; since we don't have to play that double-guessing game and the user
4699          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4700          (if (functionp message-qmail-inject-args)
4701              (funcall message-qmail-inject-args)
4702            message-qmail-inject-args)))
4703     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4704     ;; we have to look at the retval instead
4705     (0 nil)
4706     (100 (error "qmail-inject reported permanent failure"))
4707     (111 (error "qmail-inject reported transient failure"))
4708     ;; should never happen
4709     (t   (error "qmail-inject reported unknown failure"))))
4710
4711 (defun message-send-mail-with-mh ()
4712   "Send the prepared message buffer with mh."
4713   (let ((mh-previous-window-config nil)
4714         (name (mh-new-draft-name)))
4715     (setq buffer-file-name name)
4716     ;; MH wants to generate these headers itself.
4717     (when message-mh-deletable-headers
4718       (let ((headers message-mh-deletable-headers))
4719         (while headers
4720           (goto-char (point-min))
4721           (and (re-search-forward
4722                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4723                (message-delete-line))
4724           (pop headers))))
4725     (run-hooks 'message-send-mail-hook)
4726     ;; Pass it on to mh.
4727     (mh-send-letter)))
4728
4729 (defun message-smtpmail-send-it ()
4730   "Send the prepared message buffer with `smtpmail-send-it'.
4731 The only difference from `smtpmail-send-it' is that this command
4732 evaluates `message-send-mail-hook' just before sending a message.
4733 It is useful if your ISP requires the POP-before-SMTP
4734 authentication.  See the Gnus manual for details."
4735   (run-hooks 'message-send-mail-hook)
4736   (smtpmail-send-it))
4737
4738 (defun message-send-mail-with-mailclient ()
4739   "Send the prepared message buffer with `mailclient-send-it'.
4740 The only difference from `mailclient-send-it' is that this
4741 command evaluates `message-send-mail-hook' just before sending a message."
4742   (run-hooks 'message-send-mail-hook)
4743   (mailclient-send-it))
4744
4745 (defun message-canlock-generate ()
4746   "Return a string that is non-trivial to guess.
4747 Do not use this for anything important, it is cryptographically weak."
4748   (require 'sha1)
4749   (let (sha1-maximum-internal-length)
4750     (sha1 (concat (message-unique-id)
4751                   (format "%x%x%x" (random) (random t) (random))
4752                   (prin1-to-string (recent-keys))
4753                   (prin1-to-string (garbage-collect))))))
4754
4755 (defvar canlock-password)
4756 (defvar canlock-password-for-verify)
4757
4758 (defun message-canlock-password ()
4759   "The password used by message for cancel locks.
4760 This is the value of `canlock-password', if that option is non-nil.
4761 Otherwise, generate and save a value for `canlock-password' first."
4762   (require 'canlock)
4763   (unless canlock-password
4764     (customize-save-variable 'canlock-password (message-canlock-generate))
4765     (setq canlock-password-for-verify canlock-password))
4766   canlock-password)
4767
4768 (defun message-insert-canlock ()
4769   (when message-insert-canlock
4770     (message-canlock-password)
4771     (canlock-insert-header)))
4772
4773 (autoload 'nnheader-get-report "nnheader")
4774
4775 (declare-function gnus-setup-posting-charset "gnus-msg" (group))
4776
4777 (defun message-send-news (&optional arg)
4778   (require 'gnus-msg)
4779   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4780          (case-fold-search nil)
4781          (method (if (functionp message-post-method)
4782                      (funcall message-post-method arg)
4783                    message-post-method))
4784          (newsgroups-field (save-restriction
4785                             (message-narrow-to-headers-or-head)
4786                             (message-fetch-field "Newsgroups")))
4787          (followup-field (save-restriction
4788                            (message-narrow-to-headers-or-head)
4789                            (message-fetch-field "Followup-To")))
4790          ;; BUG: We really need to get the charset for each name in the
4791          ;; Newsgroups and Followup-To lines to allow crossposting
4792          ;; between group namess with incompatible character sets.
4793          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4794          (group-field-charset
4795           (gnus-group-name-charset method newsgroups-field))
4796          (followup-field-charset
4797           (gnus-group-name-charset method (or followup-field "")))
4798          (rfc2047-header-encoding-alist
4799           (append (when group-field-charset
4800                     (list (cons "Newsgroups" group-field-charset)))
4801                   (when followup-field-charset
4802                     (list (cons "Followup-To" followup-field-charset)))
4803                   rfc2047-header-encoding-alist))
4804          (messbuf (current-buffer))
4805          (message-syntax-checks
4806           (if (and arg
4807                    (listp message-syntax-checks))
4808               (cons '(existing-newsgroups . disabled)
4809                     message-syntax-checks)
4810             message-syntax-checks))
4811          (message-this-is-news t)
4812          (message-posting-charset
4813           (gnus-setup-posting-charset newsgroups-field))
4814          result)
4815     (if (not (message-check-news-body-syntax))
4816         nil
4817       (save-restriction
4818         (message-narrow-to-headers)
4819         ;; Insert some headers.
4820         (message-generate-headers message-required-news-headers)
4821         (message-insert-canlock)
4822         ;; Let the user do all of the above.
4823         (run-hooks 'message-header-hook))
4824       ;; Note: This check will be disabled by the ".*" default value for
4825       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4826       (when (and group-field-charset
4827                  (listp message-syntax-checks))
4828         (setq message-syntax-checks
4829               (cons '(valid-newsgroups . disabled)
4830                     message-syntax-checks)))
4831       (message-cleanup-headers)
4832       (if (not (let ((message-post-method method))
4833                  (message-check-news-syntax)))
4834           nil
4835         (unwind-protect
4836             (with-current-buffer tembuf
4837               (buffer-disable-undo)
4838               (erase-buffer)
4839               ;; Avoid copying text props (except hard newlines).
4840               (insert
4841                (with-current-buffer messbuf
4842                  (mml-buffer-substring-no-properties-except-hard-newlines
4843                   (point-min) (point-max))))
4844               (message-encode-message-body)
4845               ;; Remove some headers.
4846               (save-restriction
4847                 (message-narrow-to-headers)
4848                 ;; We (re)generate the Lines header.
4849                 (when (memq 'Lines message-required-mail-headers)
4850                   (message-generate-headers '(Lines)))
4851                 ;; Remove some headers.
4852                 (message-remove-header message-ignored-news-headers t)
4853                 (let ((mail-parse-charset message-default-charset))
4854                   (mail-encode-encoded-word-buffer)))
4855               (goto-char (point-max))
4856               ;; require one newline at the end.
4857               (or (= (preceding-char) ?\n)
4858                   (insert ?\n))
4859               (let ((case-fold-search t))
4860                 ;; Remove the delimiter.
4861                 (goto-char (point-min))
4862                 (re-search-forward
4863                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4864                 (replace-match "\n")
4865                 (backward-char 1))
4866               (run-hooks 'message-send-news-hook)
4867               (gnus-open-server method)
4868               (message "Sending news via %s..." (gnus-server-string method))
4869               (setq result (let ((mail-header-separator ""))
4870                              (gnus-request-post method))))
4871           (kill-buffer tembuf))
4872         (set-buffer messbuf)
4873         (if result
4874             (push 'news message-sent-message-via)
4875           (message "Couldn't send message via news: %s"
4876                    (nnheader-get-report (car method)))
4877           nil)))))
4878
4879 ;;;
4880 ;;; Header generation & syntax checking.
4881 ;;;
4882
4883 (defun message-check-element (type)
4884   "Return non-nil if this TYPE is not to be checked."
4885   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4886       t
4887     (let ((able (assq type message-syntax-checks)))
4888       (and (consp able)
4889            (eq (cdr able) 'disabled)))))
4890
4891 (defun message-check-news-syntax ()
4892   "Check the syntax of the message."
4893   (save-excursion
4894     (save-restriction
4895       (widen)
4896       ;; We narrow to the headers and check them first.
4897       (save-excursion
4898         (save-restriction
4899           (message-narrow-to-headers)
4900           (message-check-news-header-syntax))))))
4901
4902 (defun message-check-news-header-syntax ()
4903   (and
4904    ;; Check Newsgroups header.
4905    (message-check 'newsgroups
4906      (let ((group (message-fetch-field "newsgroups")))
4907        (or
4908         (and group
4909              (not (string-match "\\`[ \t]*\\'" group)))
4910         (ignore
4911          (message
4912           "The newsgroups field is empty or missing.  Posting is denied.")))))
4913    ;; Check the Subject header.
4914    (message-check 'subject
4915      (let* ((case-fold-search t)
4916             (subject (message-fetch-field "subject")))
4917        (or
4918         (and subject
4919              (not (string-match "\\`[ \t]*\\'" subject)))
4920         (ignore
4921          (message
4922           "The subject field is empty or missing.  Posting is denied.")))))
4923    ;; Check for commands in Subject.
4924    (message-check 'subject-cmsg
4925      (if (string-match "^cmsg " (message-fetch-field "subject"))
4926          (y-or-n-p
4927           "The control code \"cmsg\" is in the subject.  Really post? ")
4928        t))
4929    ;; Check long header lines.
4930    (message-check 'long-header-lines
4931      (let ((start (point))
4932            (header nil)
4933            (length 0)
4934            found)
4935        (while (and (not found)
4936                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4937          (if (> (- (point) (match-beginning 0)) 998)
4938              (setq found t
4939                    length (- (point) (match-beginning 0)))
4940            (setq header (match-string-no-properties 1)))
4941          (setq start (match-beginning 0))
4942          (forward-line 1))
4943        (if found
4944            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4945                              header length))
4946          t)))
4947    ;; Check for multiple identical headers.
4948    (message-check 'multiple-headers
4949      (let (found)
4950        (while (and (not found)
4951                    (re-search-forward "^[^ \t:]+: " nil t))
4952          (save-excursion
4953            (or (re-search-forward
4954                 (concat "^"
4955                         (regexp-quote
4956                          (setq found
4957                                (buffer-substring
4958                                 (match-beginning 0) (- (match-end 0) 2))))
4959                         ":")
4960                 nil t)
4961                (setq found nil))))
4962        (if found
4963            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4964          t)))
4965    ;; Check for Version and Sendsys.
4966    (message-check 'sendsys
4967      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4968          (y-or-n-p
4969           (format "The article contains a %s command.  Really post? "
4970                   (buffer-substring (match-beginning 0)
4971                                     (1- (match-end 0)))))
4972        t))
4973    ;; See whether we can shorten Followup-To.
4974    (message-check 'shorten-followup-to
4975      (let ((newsgroups (message-fetch-field "newsgroups"))
4976            (followup-to (message-fetch-field "followup-to"))
4977            to)
4978        (when (and newsgroups
4979                   (string-match "," newsgroups)
4980                   (not followup-to)
4981                   (not
4982                    (zerop
4983                     (length
4984                      (setq to (completing-read
4985                                "Followups to (default no Followup-To header): "
4986                                (mapcar #'list
4987                                        (cons "poster"
4988                                              (message-tokenize-header
4989                                               newsgroups)))))))))
4990          (goto-char (point-min))
4991          (insert "Followup-To: " to "\n"))
4992        t))
4993    ;; Check "Shoot me".
4994    (message-check 'shoot
4995      (if (re-search-forward
4996           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4997          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4998        t))
4999    ;; Check for Approved.
5000    (message-check 'approved
5001      (if (re-search-forward "^Approved:" nil t)
5002          (y-or-n-p "The article contains an Approved header.  Really post? ")
5003        t))
5004    ;; Check the Message-ID header.
5005    (message-check 'message-id
5006      (let* ((case-fold-search t)
5007             (message-id (message-fetch-field "message-id" t)))
5008        (or (not message-id)
5009            ;; Is there an @ in the ID?
5010            (and (string-match "@" message-id)
5011                 ;; Is there a dot in the ID?
5012                 (string-match "@[^.]*\\." message-id)
5013                 ;; Does the ID end with a dot?
5014                 (not (string-match "\\.>" message-id)))
5015            (y-or-n-p
5016             (format "The Message-ID looks strange: \"%s\".  Really post? "
5017                     message-id)))))
5018    ;; Check the Newsgroups & Followup-To headers.
5019    (message-check 'existing-newsgroups
5020      (let* ((case-fold-search t)
5021             (newsgroups (message-fetch-field "newsgroups"))
5022             (followup-to (message-fetch-field "followup-to"))
5023             (groups (message-tokenize-header
5024                      (if followup-to
5025                          (concat newsgroups "," followup-to)
5026                        newsgroups)))
5027             (post-method (if (functionp message-post-method)
5028                              (funcall message-post-method)
5029                            message-post-method))
5030             ;; KLUDGE to handle nnvirtual groups.  Doing this right
5031             ;; would probably involve a new nnoo function.
5032             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
5033             (method (if (and (consp post-method)
5034                              (eq (car post-method) 'nnvirtual)
5035                              gnus-message-group-art)
5036                         (let ((group (car (nnvirtual-find-group-art
5037                                            (car gnus-message-group-art)
5038                                            (cdr gnus-message-group-art)))))
5039                           (gnus-find-method-for-group group))
5040                       post-method))
5041             (known-groups
5042              (mapcar (lambda (n)
5043                        (gnus-group-name-decode
5044                         (gnus-group-real-name n)
5045                         (gnus-group-name-charset method n)))
5046                      (gnus-groups-from-server method)))
5047             errors)
5048        (while groups
5049          (when (and (not (equal (car groups) "poster"))
5050                     (not (member (car groups) known-groups))
5051                     (not (member (car groups) errors)))
5052            (push (car groups) errors))
5053          (pop groups))
5054        (cond
5055         ;; Gnus is not running.
5056         ((or (not (and (boundp 'gnus-active-hashtb)
5057                        gnus-active-hashtb))
5058              (not (boundp 'gnus-read-active-file)))
5059          t)
5060         ;; We don't have all the group names.
5061         ((and (or (not gnus-read-active-file)
5062                   (eq gnus-read-active-file 'some))
5063               errors)
5064          (y-or-n-p
5065           (format
5066            "Really use %s possibly unknown group%s: %s? "
5067            (if (= (length errors) 1) "this" "these")
5068            (if (= (length errors) 1) "" "s")
5069            (mapconcat 'identity errors ", "))))
5070         ;; There were no errors.
5071         ((not errors)
5072          t)
5073         ;; There are unknown groups.
5074         (t
5075          (y-or-n-p
5076           (format
5077            "Really post to %s unknown group%s: %s? "
5078            (if (= (length errors) 1) "this" "these")
5079            (if (= (length errors) 1) "" "s")
5080            (mapconcat 'identity errors ", ")))))))
5081    ;; Check continuation headers.
5082    (message-check 'continuation-headers
5083      (goto-char (point-min))
5084      (let ((do-posting t))
5085        (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
5086          (goto-char (match-beginning 0))
5087          (if (y-or-n-p "Fix continuation lines? ")
5088              (insert " ")
5089            (forward-line 1)
5090            (unless (y-or-n-p "Send anyway? ")
5091              (setq do-posting nil))))
5092        do-posting))
5093    ;; Check the Newsgroups & Followup-To headers for syntax errors.
5094    (message-check 'valid-newsgroups
5095      (let ((case-fold-search t)
5096            (headers '("Newsgroups" "Followup-To"))
5097            header error)
5098        (while (and headers (not error))
5099          (when (setq header (mail-fetch-field (car headers)))
5100            (if (or
5101                 (not
5102                  (string-match
5103                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
5104                   header))
5105                 (memq
5106                  nil (mapcar
5107                       (lambda (g)
5108                         (not (string-match "\\.\\'\\|\\.\\." g)))
5109                       (message-tokenize-header header ","))))
5110                (setq error t)))
5111          (unless error
5112            (pop headers)))
5113        (if (not error)
5114            t
5115          (y-or-n-p
5116           (format "The %s header looks odd: \"%s\".  Really post? "
5117                   (car headers) header)))))
5118    (message-check 'repeated-newsgroups
5119      (let ((case-fold-search t)
5120            (headers '("Newsgroups" "Followup-To"))
5121            header error groups group)
5122        (while (and headers
5123                    (not error))
5124          (when (setq header (mail-fetch-field (pop headers)))
5125            (setq groups (message-tokenize-header header ","))
5126            (while (setq group (pop groups))
5127              (when (member group groups)
5128                (setq error group
5129                      groups nil)))))
5130        (if (not error)
5131            t
5132          (y-or-n-p
5133           (format "Group %s is repeated in headers.  Really post? " error)))))
5134    ;; Check the From header.
5135    (message-check 'from
5136      (let* ((case-fold-search t)
5137             (from (message-fetch-field "from"))
5138             ad)
5139        (cond
5140         ((not from)
5141          (message "There is no From line.  Posting is denied.")
5142          nil)
5143         ((or (not (string-match
5144                    "@[^\\.]*\\."
5145                    (setq ad (nth 1 (mail-extract-address-components
5146                                     from))))) ;larsi@ifi
5147              (string-match "\\.\\." ad) ;larsi@ifi..uio
5148              (string-match "@\\." ad)   ;larsi@.ifi.uio
5149              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5150              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5151              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
5152          (message
5153           "Denied posting -- the From looks strange: \"%s\"." from)
5154          nil)
5155         ((let ((addresses (rfc822-addresses from)))
5156            ;; `rfc822-addresses' returns a string if parsing fails.
5157            (while (and (consp addresses)
5158                        (not (eq (string-to-char (car addresses)) ?\()))
5159              (setq addresses (cdr addresses)))
5160            addresses)
5161          (message
5162           "Denied posting -- bad From address: \"%s\"." from)
5163          nil)
5164         (t t))))
5165    ;; Check the Reply-To header.
5166    (message-check 'reply-to
5167      (let* ((case-fold-search t)
5168             (reply-to (message-fetch-field "reply-to"))
5169             ad)
5170        (cond
5171         ((not reply-to)
5172          t)
5173         ((string-match "," reply-to)
5174          (y-or-n-p
5175           (format "Multiple Reply-To addresses: \"%s\". Really post? "
5176                   reply-to)))
5177         ((or (not (string-match
5178                    "@[^\\.]*\\."
5179                    (setq ad (nth 1 (mail-extract-address-components
5180                                     reply-to))))) ;larsi@ifi
5181              (string-match "\\.\\." ad) ;larsi@ifi..uio
5182              (string-match "@\\." ad)   ;larsi@.ifi.uio
5183              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5184              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5185              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5186          (y-or-n-p
5187           (format
5188            "The Reply-To looks strange: \"%s\". Really post? "
5189            reply-to)))
5190         (t t))))))
5191
5192 (defun message-check-news-body-syntax ()
5193   (and
5194    ;; Check for long lines.
5195    (message-check 'long-lines
5196      (goto-char (point-min))
5197      (re-search-forward
5198       (concat "^" (regexp-quote mail-header-separator) "$"))
5199      (forward-line 1)
5200      (while (and
5201              (or (looking-at
5202                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
5203                  (let ((p (point)))
5204                    (end-of-line)
5205                    (< (- (point) p) 80)))
5206              (zerop (forward-line 1))))
5207      (or (bolp)
5208          (eobp)
5209          (y-or-n-p
5210           "You have lines longer than 79 characters.  Really post? ")))
5211    ;; Check whether the article is empty.
5212    (message-check 'empty
5213      (goto-char (point-min))
5214      (re-search-forward
5215       (concat "^" (regexp-quote mail-header-separator) "$"))
5216      (forward-line 1)
5217      (let ((b (point)))
5218        (goto-char (point-max))
5219        (re-search-backward message-signature-separator nil t)
5220        (beginning-of-line)
5221        (or (re-search-backward "[^ \n\t]" b t)
5222            (if (message-gnksa-enable-p 'empty-article)
5223                (y-or-n-p "Empty article.  Really post? ")
5224              (message "Denied posting -- Empty article.")
5225              nil))))
5226    ;; Check for control characters.
5227    (message-check 'control-chars
5228      (if (re-search-forward
5229           (mm-string-to-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5230           nil t)
5231          (y-or-n-p
5232           "The article contains control characters.  Really post? ")
5233        t))
5234    ;; Check excessive size.
5235    (message-check 'size
5236      (if (> (buffer-size) 60000)
5237          (y-or-n-p
5238           (format "The article is %d octets long.  Really post? "
5239                   (buffer-size)))
5240        t))
5241    ;; Check whether any new text has been added.
5242    (message-check 'new-text
5243      (or
5244       (not message-checksum)
5245       (not (eq (message-checksum) message-checksum))
5246       (if (message-gnksa-enable-p 'quoted-text-only)
5247           (y-or-n-p
5248            "It looks like no new text has been added.  Really post? ")
5249         (message "Denied posting -- no new text has been added.")
5250         nil)))
5251    ;; Check the length of the signature.
5252    (message-check 'signature
5253      (let (sig-start sig-end)
5254        (goto-char (point-max))
5255        (if (not (re-search-backward message-signature-separator nil t))
5256            t
5257          (setq sig-start (1+ (point-at-eol)))
5258          (setq sig-end
5259                (if (re-search-forward
5260                     "<#/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
5261                    (- (point-at-bol) 1)
5262                  (point-max)))
5263          (if (>= (count-lines sig-start sig-end) 5)
5264              (if (message-gnksa-enable-p 'signature)
5265                  (y-or-n-p
5266                   (format "Signature is excessively long (%d lines).  Really post? "
5267                           (count-lines sig-start sig-end)))
5268                (message "Denied posting -- Excessive signature.")
5269                nil)
5270            t))))
5271    ;; Ensure that text follows last quoted portion.
5272    (message-check 'quoting-style
5273      (goto-char (point-max))
5274      (let ((no-problem t))
5275        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5276          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5277        (if no-problem
5278            t
5279          (if (message-gnksa-enable-p 'quoted-text-only)
5280              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5281            ;; Ensure that
5282            (goto-char (point-min))
5283            (re-search-forward
5284             (concat "^" (regexp-quote mail-header-separator) "$"))
5285            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5286                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5287              (message "Denied posting -- only quoted text.")
5288              nil)))))))
5289
5290 (defun message-checksum ()
5291   "Return a \"checksum\" for the current buffer."
5292   (let ((sum 0))
5293     (save-excursion
5294       (goto-char (point-min))
5295       (re-search-forward
5296        (concat "^" (regexp-quote mail-header-separator) "$"))
5297       (while (not (eobp))
5298         (when (not (looking-at "[ \t\n]"))
5299           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5300                             (char-after))))
5301         (forward-char 1)))
5302     sum))
5303
5304 (defun message-do-fcc ()
5305   "Process Fcc headers in the current buffer."
5306   (let ((case-fold-search t)
5307         (buf (current-buffer))
5308         list file
5309         (mml-externalize-attachments message-fcc-externalize-attachments))
5310     (save-excursion
5311       (save-restriction
5312         (message-narrow-to-headers)
5313         (setq file (message-fetch-field "fcc" t)))
5314       (when file
5315         (set-buffer (get-buffer-create " *message temp*"))
5316         (erase-buffer)
5317         (insert-buffer-substring buf)
5318         (message-encode-message-body)
5319         (save-restriction
5320           (message-narrow-to-headers)
5321           (while (setq file (message-fetch-field "fcc" t))
5322             (push file list)
5323             (message-remove-header "fcc" nil t))
5324           (let ((mail-parse-charset message-default-charset)
5325                 (rfc2047-header-encoding-alist
5326                  (cons '("Newsgroups" . default)
5327                        rfc2047-header-encoding-alist)))
5328             (mail-encode-encoded-word-buffer)))
5329         (goto-char (point-min))
5330         (when (re-search-forward
5331                (concat "^" (regexp-quote mail-header-separator) "$")
5332                nil t)
5333           (replace-match "" t t ))
5334         ;; Process FCC operations.
5335         (while list
5336           (setq file (pop list))
5337           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5338               ;; Pipe the article to the program in question.
5339               (call-process-region (point-min) (point-max) shell-file-name
5340                                    nil nil nil shell-command-switch
5341                                    (match-string 1 file))
5342             ;; Save the article.
5343             (setq file (expand-file-name file))
5344             (unless (file-exists-p (file-name-directory file))
5345               (make-directory (file-name-directory file) t))
5346             (if (and message-fcc-handler-function
5347                      (not (eq message-fcc-handler-function 'rmail-output)))
5348                 (funcall message-fcc-handler-function file)
5349               ;; FIXME this option, rmail-output (also used if
5350               ;; message-fcc-handler-function is nil) is not
5351               ;; documented anywhere AFAICS.  It should work in Emacs
5352               ;; 23; I suspect it does not work in Emacs 22.
5353               ;; FIXME I don't see the need for the two different cases here.
5354               ;; mail-use-rfc822 makes no difference (in Emacs 23),and
5355               ;; the third argument just controls \"Wrote file\" message.
5356               (if (and (file-readable-p file) (mail-file-babyl-p file))
5357                   (rmail-output file 1 nil t)
5358                 (let ((mail-use-rfc822 t))
5359                   (rmail-output file 1 t t))))))
5360         (kill-buffer (current-buffer))))))
5361
5362 (defun message-output (filename)
5363   "Append this article to Unix/babyl mail file FILENAME."
5364   (if (or (and (file-readable-p filename)
5365                (mail-file-babyl-p filename))
5366           ;; gnus-output-to-mail does the wrong thing with live, mbox
5367           ;; Rmail buffers in Emacs 23.
5368           ;; http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=597255
5369           (let ((buff (find-buffer-visiting filename)))
5370             (and buff (with-current-buffer buff
5371                         (eq major-mode 'rmail-mode)))))
5372       (gnus-output-to-rmail filename t)
5373     (gnus-output-to-mail filename t)))
5374
5375 (defun message-cleanup-headers ()
5376   "Do various automatic cleanups of the headers."
5377   ;; Remove empty lines in the header.
5378   (save-restriction
5379     (message-narrow-to-headers)
5380     ;; Remove blank lines.
5381     (while (re-search-forward "^[ \t]*\n" nil t)
5382       (replace-match "" t t))
5383
5384     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5385     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5386     ;; embedded line breaks.
5387     (goto-char (point-min))
5388     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5389       (save-restriction
5390         (narrow-to-region
5391          (point)
5392          (if (re-search-forward "^[^ \t]" nil t)
5393              (match-beginning 0)
5394            (forward-line 1)
5395            (point)))
5396         (goto-char (point-min))
5397         (while (re-search-forward "\n[ \t]+" nil t)
5398           (replace-match " " t t))     ;No line breaks (too confusing)
5399         (goto-char (point-min))
5400         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5401           (replace-match "," t t))
5402         (goto-char (point-min))
5403         ;; Remove trailing commas.
5404         (when (re-search-forward ",+$" nil t)
5405           (replace-match "" t t))))))
5406
5407 (defun message-make-date (&optional now)
5408   "Make a valid data header.
5409 If NOW, use that time instead."
5410   (let ((system-time-locale "C"))
5411     (format-time-string "%a, %d %b %Y %T %z" now)))
5412
5413 (defun message-insert-expires (days)
5414   "Insert the Expires header.  Expiry in DAYS days."
5415   (interactive "NExpire article in how many days? ")
5416   (save-excursion
5417     (message-position-on-field "Expires" "X-Draft-From")
5418     (insert (message-make-expires-date days))))
5419
5420 (defun message-make-expires-date (days)
5421   "Make date string for the Expires header.  Expiry in DAYS days.
5422
5423 In posting styles use `(\"Expires\" (make-expires-date 30))'."
5424   (let* ((cur (decode-time (current-time)))
5425          (nday (+ days (nth 3 cur))))
5426     (setf (nth 3 cur) nday)
5427     (message-make-date (apply 'encode-time cur))))
5428
5429 (defun message-make-message-id ()
5430   "Make a unique Message-ID."
5431   (concat "<" (message-unique-id)
5432           (let ((psubject (save-excursion (message-fetch-field "subject")))
5433                 (psupersedes
5434                  (save-excursion (message-fetch-field "supersedes"))))
5435             (if (or
5436                  (and message-reply-headers
5437                       (mail-header-references message-reply-headers)
5438                       (mail-header-subject message-reply-headers)
5439                       psubject
5440                       (not (string=
5441                             (message-strip-subject-re
5442                              (mail-header-subject message-reply-headers))
5443                             (message-strip-subject-re psubject))))
5444                  (and psupersedes
5445                       (string-match "_-_@" psupersedes)))
5446                 "_-_" ""))
5447           "@" (message-make-fqdn) ">"))
5448
5449 (defvar message-unique-id-char nil)
5450
5451 ;; If you ever change this function, make sure the new version
5452 ;; cannot generate IDs that the old version could.
5453 ;; You might for example insert a "." somewhere (not next to another dot
5454 ;; or string boundary), or modify the "fsf" string.
5455 (defun message-unique-id ()
5456   ;; Don't use microseconds from (current-time), they may be unsupported.
5457   ;; Instead we use this randomly inited counter.
5458   (setq message-unique-id-char
5459         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5460            ;; (current-time) returns 16-bit ints,
5461            ;; and 2^16*25 just fits into 4 digits i base 36.
5462            (* 25 25)))
5463   (let ((tm (current-time)))
5464     (concat
5465      (if (or (eq system-type 'ms-dos)
5466              ;; message-number-base36 doesn't handle bigints.
5467              (floatp (user-uid)))
5468          (let ((user (downcase (user-login-name))))
5469            (while (string-match "[^a-z0-9_]" user)
5470              (aset user (match-beginning 0) ?_))
5471            user)
5472        (message-number-base36 (user-uid) -1))
5473      (message-number-base36 (+ (car tm)
5474                                (lsh (% message-unique-id-char 25) 16)) 4)
5475      (message-number-base36 (+ (nth 1 tm)
5476                                (lsh (/ message-unique-id-char 25) 16)) 4)
5477      ;; Append a given name, because while the generated ID is unique
5478      ;; to this newsreader, other newsreaders might otherwise generate
5479      ;; the same ID via another algorithm.
5480      ".fsf")))
5481
5482 (defun message-number-base36 (num len)
5483   (if (if (< len 0)
5484           (<= num 0)
5485         (= len 0))
5486       ""
5487     (concat (message-number-base36 (/ num 36) (1- len))
5488             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5489                                   (% num 36))))))
5490
5491 (defun message-make-organization ()
5492   "Make an Organization header."
5493   (let* ((organization
5494           (when message-user-organization
5495             (if (functionp message-user-organization)
5496                 (funcall message-user-organization)
5497               message-user-organization))))
5498     (with-temp-buffer
5499       (mm-enable-multibyte)
5500       (cond ((stringp organization)
5501              (insert organization))
5502             ((and (eq t organization)
5503                   message-user-organization-file
5504                   (file-exists-p message-user-organization-file))
5505              (insert-file-contents message-user-organization-file)))
5506       (goto-char (point-min))
5507       (while (re-search-forward "[\t\n]+" nil t)
5508         (replace-match "" t t))
5509       (unless (zerop (buffer-size))
5510         (buffer-string)))))
5511
5512 (defun message-make-lines ()
5513   "Count the number of lines and return numeric string."
5514   (save-excursion
5515     (save-restriction
5516       (widen)
5517       (message-goto-body)
5518       (int-to-string (count-lines (point) (point-max))))))
5519
5520 (defun message-make-references ()
5521   "Return the References header for this message."
5522   (when message-reply-headers
5523     (let ((message-id (mail-header-id message-reply-headers))
5524           (references (mail-header-references message-reply-headers)))
5525       (if (or references message-id)
5526           (concat (or references "") (and references " ")
5527                   (or message-id ""))
5528         nil))))
5529
5530 (defun message-make-in-reply-to ()
5531   "Return the In-Reply-To header for this message."
5532   (when message-reply-headers
5533     (let ((from (mail-header-from message-reply-headers))
5534           (date (mail-header-date message-reply-headers))
5535           (msg-id (mail-header-id message-reply-headers)))
5536       (when from
5537         (let ((name (mail-extract-address-components from)))
5538           (concat
5539            msg-id (if msg-id " (")
5540            (if (car name)
5541                (if (string-match "[^\000-\177]" (car name))
5542                    ;; Quote a string containing non-ASCII characters.
5543                    ;; It will make the RFC2047 encoder cause an error
5544                    ;; if there are special characters.
5545                    (mm-with-multibyte-buffer
5546                      (insert (car name))
5547                      (goto-char (point-min))
5548                      (while (search-forward "\"" nil t)
5549                        (when (prog2
5550                                  (backward-char)
5551                                  (zerop (% (skip-chars-backward "\\\\") 2))
5552                                (goto-char (match-beginning 0)))
5553                          (insert "\\"))
5554                        (forward-char))
5555                      ;; Those quotes will be removed by the RFC2047 encoder.
5556                      (concat "\"" (buffer-string) "\""))
5557                  (car name))
5558              (nth 1 name))
5559            "'s message of \""
5560            (if (or (not date) (string= date ""))
5561                "(unknown date)" date)
5562            "\"" (if msg-id ")")))))))
5563
5564 (defun message-make-distribution ()
5565   "Make a Distribution header."
5566   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5567     (cond ((functionp message-distribution-function)
5568            (funcall message-distribution-function))
5569           (t orig-distribution))))
5570
5571 (defun message-make-expires ()
5572   "Return an Expires header based on `message-expires'."
5573   (let ((current (current-time))
5574         (future (* 1.0 message-expires 60 60 24)))
5575     ;; Add the future to current.
5576     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5577     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5578     (message-make-date current)))
5579
5580 (defun message-make-path ()
5581   "Return uucp path."
5582   (let ((login-name (user-login-name)))
5583     (cond ((null message-user-path)
5584            (concat (system-name) "!" login-name))
5585           ((stringp message-user-path)
5586            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5587            (concat message-user-path "!" login-name))
5588           (t login-name))))
5589
5590 (defun message-make-from (&optional name address)
5591   "Make a From header."
5592   (let* ((style message-from-style)
5593          (login (or address (message-make-address)))
5594          (fullname (or name
5595                        (and (boundp 'user-full-name)
5596                             user-full-name)
5597                        (user-full-name))))
5598     (when (string= fullname "&")
5599       (setq fullname (user-login-name)))
5600     (with-temp-buffer
5601       (mm-enable-multibyte)
5602       (cond
5603        ((or (null style)
5604             (equal fullname ""))
5605         (insert login))
5606        ((or (eq style 'angles)
5607             (and (not (eq style 'parens))
5608                  ;; Use angles if no quoting is needed, or if parens would
5609                  ;; need quoting too.
5610                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5611                      (let ((tmp (concat fullname nil)))
5612                        (while (string-match "([^()]*)" tmp)
5613                          (aset tmp (match-beginning 0) ?-)
5614                          (aset tmp (1- (match-end 0)) ?-))
5615                        (string-match "[\\()]" tmp)))))
5616         (insert fullname)
5617         (goto-char (point-min))
5618         ;; Look for a character that cannot appear unquoted
5619         ;; according to RFC 822.
5620         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5621           ;; Quote fullname, escaping specials.
5622           (goto-char (point-min))
5623           (insert "\"")
5624           (while (re-search-forward "[\"\\]" nil 1)
5625             (replace-match "\\\\\\&" t))
5626           (insert "\""))
5627         (insert " <" login ">"))
5628        (t                               ; 'parens or default
5629         (insert login " (")
5630         (let ((fullname-start (point)))
5631           (insert fullname)
5632           (goto-char fullname-start)
5633           ;; RFC 822 says \ and nonmatching parentheses
5634           ;; must be escaped in comments.
5635           ;; Escape every instance of ()\ ...
5636           (while (re-search-forward "[()\\]" nil 1)
5637             (replace-match "\\\\\\&" t))
5638           ;; ... then undo escaping of matching parentheses,
5639           ;; including matching nested parentheses.
5640           (goto-char fullname-start)
5641           (while (re-search-forward
5642                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5643                   nil 1)
5644             (replace-match "\\1(\\3)" t)
5645             (goto-char fullname-start)))
5646         (insert ")")))
5647       (buffer-string))))
5648
5649 (defun message-make-sender ()
5650   "Return the \"real\" user address.
5651 This function tries to ignore all user modifications, and
5652 give as trustworthy answer as possible."
5653   (concat (user-login-name) "@" (system-name)))
5654
5655 (defun message-make-address ()
5656   "Make the address of the user."
5657   (or (message-user-mail-address)
5658       (concat (user-login-name) "@" (message-make-domain))))
5659
5660 (defun message-user-mail-address ()
5661   "Return the pertinent part of `user-mail-address'."
5662   (when (and user-mail-address
5663              (string-match "@.*\\." user-mail-address))
5664     (if (string-match " " user-mail-address)
5665         (nth 1 (mail-extract-address-components user-mail-address))
5666       user-mail-address)))
5667
5668 (defun message-sendmail-envelope-from ()
5669   "Return the envelope from."
5670   (cond ((eq message-sendmail-envelope-from 'header)
5671          (nth 1 (mail-extract-address-components
5672                  (message-fetch-field "from"))))
5673         ((stringp message-sendmail-envelope-from)
5674          message-sendmail-envelope-from)
5675         (t
5676          (message-make-address))))
5677
5678 (defun message-make-fqdn ()
5679   "Return user's fully qualified domain name."
5680   (let* ((system-name (system-name))
5681          (user-mail (message-user-mail-address))
5682          (user-domain
5683           (if (and user-mail
5684                    (string-match "@\\(.*\\)\\'" user-mail))
5685               (match-string 1 user-mail)))
5686          (case-fold-search t))
5687     (cond
5688      ((and message-user-fqdn
5689            (stringp message-user-fqdn)
5690            (string-match message-valid-fqdn-regexp message-user-fqdn)
5691            (not (string-match message-bogus-system-names message-user-fqdn)))
5692       ;; `message-user-fqdn' seems to be valid
5693       message-user-fqdn)
5694      ((and (string-match message-valid-fqdn-regexp system-name)
5695            (not (string-match message-bogus-system-names system-name)))
5696       ;; `system-name' returned the right result.
5697       system-name)
5698      ;; Try `mail-host-address'.
5699      ((and (boundp 'mail-host-address)
5700            (stringp mail-host-address)
5701            (string-match message-valid-fqdn-regexp mail-host-address)
5702            (not (string-match message-bogus-system-names mail-host-address)))
5703       mail-host-address)
5704      ;; We try `user-mail-address' as a backup.
5705      ((and user-domain
5706            (stringp user-domain)
5707            (string-match message-valid-fqdn-regexp user-domain)
5708            (not (string-match message-bogus-system-names user-domain)))
5709       user-domain)
5710      ;; Default to this bogus thing.
5711      (t
5712       (concat system-name
5713               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5714
5715 (defun message-make-host-name ()
5716   "Return the name of the host."
5717   (let ((fqdn (message-make-fqdn)))
5718     (string-match "^[^.]+\\." fqdn)
5719     (substring fqdn 0 (1- (match-end 0)))))
5720
5721 (defun message-make-domain ()
5722   "Return the domain name."
5723   (or mail-host-address
5724       (message-make-fqdn)))
5725
5726 (defun message-to-list-only ()
5727   "Send a message to the list only.
5728 Remove all addresses but the list address from To and Cc headers."
5729   (interactive)
5730   (let ((listaddr (message-make-mail-followup-to t)))
5731     (when listaddr
5732       (save-excursion
5733         (message-remove-header "to")
5734         (message-remove-header "cc")
5735         (message-position-on-field "To" "X-Draft-From")
5736         (insert listaddr)))))
5737
5738 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5739   "Return the Mail-Followup-To header.
5740 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5741 subscribed address (and not the additional To and Cc header contents)."
5742   (let* ((case-fold-search t)
5743          (to (message-fetch-field "To"))
5744          (cc (message-fetch-field "cc"))
5745          (msg-recipients (concat to (and to cc ", ") cc))
5746          (recipients
5747           (mapcar 'mail-strip-quoted-names
5748                   (message-tokenize-header msg-recipients)))
5749          (file-regexps
5750           (if message-subscribed-address-file
5751               (let (begin end item re)
5752                 (save-excursion
5753                   (with-temp-buffer
5754                     (insert-file-contents message-subscribed-address-file)
5755                     (while (not (eobp))
5756                       (setq begin (point))
5757                       (forward-line 1)
5758                       (setq end (point))
5759                       (if (bolp) (setq end (1- end)))
5760                       (setq item (regexp-quote (buffer-substring begin end)))
5761                       (if re (setq re (concat re "\\|" item))
5762                         (setq re (concat "\\`\\(" item))))
5763                     (and re (list (concat re "\\)\\'"))))))))
5764          (mft-regexps (apply 'append message-subscribed-regexps
5765                              (mapcar 'regexp-quote
5766                                      message-subscribed-addresses)
5767                              file-regexps
5768                              (mapcar 'funcall
5769                                      message-subscribed-address-functions))))
5770     (save-match-data
5771       (let ((list
5772              (loop for recipient in recipients
5773                when (loop for regexp in mft-regexps
5774                       when (string-match regexp recipient) return t)
5775                return recipient)))
5776         (when list
5777           (if only-show-subscribed
5778               list
5779             msg-recipients))))))
5780
5781 (defun message-idna-to-ascii-rhs-1 (header)
5782   "Interactively potentially IDNA encode domain names in HEADER."
5783   (let ((field (message-fetch-field header))
5784         rhs ace  address)
5785     (when field
5786       (dolist (rhs
5787                (mm-delete-duplicates
5788                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5789                         (mapcar 'downcase
5790                                 (mapcar
5791                                  (lambda (elem)
5792                                    (or (cadr elem)
5793                                        ""))
5794                                  (mail-extract-address-components field t))))))
5795         ;; Note that `rhs' will be "" if the address does not have
5796         ;; the domain part, i.e., if it is a local user's address.
5797         (setq ace (if (string-match "\\`[[:ascii:]]*\\'" rhs)
5798                       rhs
5799                     (downcase (idna-to-ascii rhs))))
5800         (when (and (not (equal rhs ace))
5801                    (or (not (eq message-use-idna 'ask))
5802                        (y-or-n-p (format "Replace %s with %s in %s:? "
5803                                          rhs ace header))))
5804           (goto-char (point-min))
5805           (while (re-search-forward (concat "^" header ":") nil t)
5806             (message-narrow-to-field)
5807             (while (search-forward (concat "@" rhs) nil t)
5808               (replace-match (concat "@" ace) t t))
5809             (goto-char (point-max))
5810             (widen)))))))
5811
5812 (defun message-idna-to-ascii-rhs ()
5813   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5814 See `message-idna-encode'."
5815   (interactive)
5816   (when message-use-idna
5817     (save-excursion
5818       (save-restriction
5819         ;; `message-narrow-to-head' that recognizes only the first empty
5820         ;; line as the message header separator used to be used here.
5821         ;; However, since there is the "--text follows this line--" line
5822         ;; normally, it failed in narrowing to the headers and potentially
5823         ;; caused the IDNA encoding on lines that look like headers in
5824         ;; the message body.
5825         (message-narrow-to-headers-or-head)
5826         (message-idna-to-ascii-rhs-1 "From")
5827         (message-idna-to-ascii-rhs-1 "To")
5828         (message-idna-to-ascii-rhs-1 "Reply-To")
5829         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5830         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5831         (message-idna-to-ascii-rhs-1 "Cc")))))
5832
5833 (defun message-generate-headers (headers)
5834   "Prepare article HEADERS.
5835 Headers already prepared in the buffer are not modified."
5836   (setq headers (append headers message-required-headers))
5837   (save-restriction
5838     (message-narrow-to-headers)
5839     (let* ((Date (message-make-date))
5840            (Message-ID (message-make-message-id))
5841            (Organization (message-make-organization))
5842            (From (message-make-from))
5843            (Path (message-make-path))
5844            (Subject nil)
5845            (Newsgroups nil)
5846            (In-Reply-To (message-make-in-reply-to))
5847            (References (message-make-references))
5848            (To nil)
5849            (Distribution (message-make-distribution))
5850            (Lines (message-make-lines))
5851            (User-Agent message-newsreader)
5852            (Expires (message-make-expires))
5853            (case-fold-search t)
5854            (optionalp nil)
5855            header value elem header-string)
5856       ;; First we remove any old generated headers.
5857       (let ((headers message-deletable-headers))
5858         (unless (buffer-modified-p)
5859           (setq headers (delq 'Message-ID (copy-sequence headers))))
5860         (while headers
5861           (goto-char (point-min))
5862           (and (re-search-forward
5863                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5864                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5865                (message-delete-line))
5866           (pop headers)))
5867       ;; Go through all the required headers and see if they are in the
5868       ;; articles already.  If they are not, or are empty, they are
5869       ;; inserted automatically - except for Subject, Newsgroups and
5870       ;; Distribution.
5871       (while headers
5872         (goto-char (point-min))
5873         (setq elem (pop headers))
5874         (if (consp elem)
5875             (if (eq (car elem) 'optional)
5876                 (setq header (cdr elem)
5877                       optionalp t)
5878               (setq header (car elem)))
5879           (setq header elem))
5880         (setq header-string  (if (stringp header)
5881                                  header
5882                                (symbol-name header)))
5883         (when (or (not (re-search-forward
5884                         (concat "^"
5885                                 (regexp-quote (downcase header-string))
5886                                 ":")
5887                         nil t))
5888                   (progn
5889                     ;; The header was found.  We insert a space after the
5890                     ;; colon, if there is none.
5891                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5892                     ;; Find out whether the header is empty.
5893                     (looking-at "[ \t]*\n[^ \t]")))
5894           ;; So we find out what value we should insert.
5895           (setq value
5896                 (cond
5897                  ((and (consp elem)
5898                        (eq (car elem) 'optional)
5899                        (not (member header-string message-inserted-headers)))
5900                   ;; This is an optional header.  If the cdr of this
5901                   ;; is something that is nil, then we do not insert
5902                   ;; this header.
5903                   (setq header (cdr elem))
5904                   (or (and (functionp (cdr elem))
5905                            (funcall (cdr elem)))
5906                       (and (boundp (cdr elem))
5907                            (symbol-value (cdr elem)))))
5908                  ((consp elem)
5909                   ;; The element is a cons.  Either the cdr is a
5910                   ;; string to be inserted verbatim, or it is a
5911                   ;; function, and we insert the value returned from
5912                   ;; this function.
5913                   (or (and (stringp (cdr elem))
5914                            (cdr elem))
5915                       (and (functionp (cdr elem))
5916                            (funcall (cdr elem)))))
5917                  ((and (boundp header)
5918                        (symbol-value header))
5919                   ;; The element is a symbol.  We insert the value
5920                   ;; of this symbol, if any.
5921                   (symbol-value header))
5922                  ((not (message-check-element
5923                         (intern (downcase (symbol-name header)))))
5924                   ;; We couldn't generate a value for this header,
5925                   ;; so we just ask the user.
5926                   (read-from-minibuffer
5927                    (format "Empty header for %s; enter value: " header)))))
5928           ;; Finally insert the header.
5929           (when (and value
5930                      (not (equal value "")))
5931             (save-excursion
5932               (if (bolp)
5933                   (progn
5934                     ;; This header didn't exist, so we insert it.
5935                     (goto-char (point-max))
5936                     (let ((formatter
5937                            (cdr (assq header message-header-format-alist))))
5938                       (if formatter
5939                           (funcall formatter header value)
5940                         (insert header-string ": " value))
5941                       (push header-string message-inserted-headers)
5942                       (goto-char (message-fill-field))
5943                       ;; We check whether the value was ended by a
5944                       ;; newline.  If not, we insert one.
5945                       (unless (bolp)
5946                         (insert "\n"))
5947                       (forward-line -1)))
5948                 ;; The value of this header was empty, so we clear
5949                 ;; totally and insert the new value.
5950                 (delete-region (point) (point-at-eol))
5951                 ;; If the header is optional, and the header was
5952                 ;; empty, we can't insert it anyway.
5953                 (unless optionalp
5954                   (push header-string message-inserted-headers)
5955                   (insert value)
5956                   (message-fill-field)))
5957               ;; Add the deletable property to the headers that require it.
5958               (and (memq header message-deletable-headers)
5959                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5960                    (add-text-properties
5961                     (point) (match-end 0)
5962                     '(message-deletable t face italic) (current-buffer)))))))
5963       ;; Insert new Sender if the From is strange.
5964       (let ((from (message-fetch-field "from"))
5965             (sender (message-fetch-field "sender"))
5966             (secure-sender (message-make-sender)))
5967         (when (and from
5968                    (not (message-check-element 'sender))
5969                    (not (string=
5970                          (downcase
5971                           (cadr (mail-extract-address-components from)))
5972                          (downcase secure-sender)))
5973                    (or (null sender)
5974                        (not
5975                         (string=
5976                          (downcase
5977                           (cadr (mail-extract-address-components sender)))
5978                          (downcase secure-sender)))))
5979           (goto-char (point-min))
5980           ;; Rename any old Sender headers to Original-Sender.
5981           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5982             (beginning-of-line)
5983             (insert "Original-")
5984             (beginning-of-line))
5985           (when (or (message-news-p)
5986                     (string-match "@.+\\.." secure-sender))
5987             (insert "Sender: " secure-sender "\n"))))
5988       ;; Check for IDNA
5989       (message-idna-to-ascii-rhs))))
5990
5991 (defun message-insert-courtesy-copy (message)
5992   "Insert a courtesy message in mail copies of combined messages."
5993   (let (newsgroups)
5994     (save-excursion
5995       (save-restriction
5996         (message-narrow-to-headers)
5997         (when (setq newsgroups (message-fetch-field "newsgroups"))
5998           (goto-char (point-max))
5999           (insert "Posted-To: " newsgroups "\n")))
6000       (forward-line 1)
6001       (when message
6002         (cond
6003          ((string-match "%s" message)
6004           (insert (format message newsgroups)))
6005          (t
6006           (insert message)))))))
6007
6008 ;;;
6009 ;;; Setting up a message buffer
6010 ;;;
6011
6012 (defun message-skip-to-next-address ()
6013   (let ((end (save-excursion
6014                (message-next-header)
6015                (point)))
6016         quoted char)
6017     (when (looking-at ",")
6018       (forward-char 1))
6019     (while (and (not (= (point) end))
6020                 (or (not (eq char ?,))
6021                     quoted))
6022       (skip-chars-forward "^,\"" (point-max))
6023       (when (eq (setq char (following-char)) ?\")
6024         (setq quoted (not quoted)))
6025       (unless (= (point) end)
6026         (forward-char 1)))
6027     (skip-chars-forward " \t\n")))
6028
6029 (defun message-fill-address (header value)
6030   (insert (capitalize (symbol-name header))
6031           ": "
6032           (if (consp value) (car value) value)
6033           "\n")
6034   (message-fill-field-address))
6035
6036 (defun message-split-line ()
6037   "Split current line, moving portion beyond point vertically down.
6038 If the current line has `message-yank-prefix', insert it on the new line."
6039   (interactive "*")
6040   (condition-case nil
6041       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
6042     (error
6043      (split-line))))
6044
6045 (defun message-insert-header (header value)
6046   (insert (capitalize (symbol-name header))
6047           ": "
6048           (if (consp value) (car value) value)))
6049
6050 (defun message-field-name ()
6051   (save-excursion
6052     (goto-char (point-min))
6053     (when (looking-at "\\([^:]+\\):")
6054       (intern (capitalize (match-string 1))))))
6055
6056 (defun message-fill-field ()
6057   (save-excursion
6058     (save-restriction
6059       (message-narrow-to-field)
6060       (let ((field-name (message-field-name)))
6061         (funcall (or (cadr (assq field-name message-field-fillers))
6062                      'message-fill-field-general)))
6063       (point-max))))
6064
6065 (defun message-fill-field-address ()
6066   (while (not (eobp))
6067     (message-skip-to-next-address)
6068     (let (last)
6069       (if (and (> (current-column) 78)
6070                last)
6071           (progn
6072             (save-excursion
6073               (goto-char last)
6074               (insert "\n\t"))
6075             (setq last (1+ (point))))
6076         (setq last (1+ (point)))))))
6077
6078 (defun message-fill-field-general ()
6079   (let ((begin (point))
6080         (fill-column 78)
6081         (fill-prefix "\t"))
6082     (while (and (search-forward "\n" nil t)
6083                 (not (eobp)))
6084       (replace-match " " t t))
6085     (fill-region-as-paragraph begin (point-max))
6086     ;; Tapdance around looong Message-IDs.
6087     (forward-line -1)
6088     (when (looking-at "[ \t]*$")
6089       (message-delete-line))
6090     (goto-char begin)
6091     (search-forward ":" nil t)
6092     (when (looking-at "\n[ \t]+")
6093       (replace-match " " t t))
6094     (goto-char (point-max))))
6095
6096 (defun message-shorten-1 (list cut surplus)
6097   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
6098   (setcdr (nthcdr (- cut 2) list)
6099           (nthcdr (+ (- cut 2) surplus 1) list)))
6100
6101 (defun message-shorten-references (header references)
6102   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
6103 When sending via news, also check that the REFERENCES are less
6104 than 988 characters long, and if they are not, trim them until
6105 they are."
6106   ;; 21 is the number suggested by USEAGE.
6107   (let ((maxcount 21)
6108         (count 0)
6109         (cut 2)
6110         refs)
6111     (with-temp-buffer
6112       (insert references)
6113       (goto-char (point-min))
6114       ;; Cons a list of valid references.  GNKSA says we must not include MIDs
6115       ;; with whitespace or missing brackets (7.a "Does not propagate broken
6116       ;; Message-IDs in original References").
6117       (while (re-search-forward "<[^ <]+@[^ <]+>" nil t)
6118         (push (match-string 0) refs))
6119       (setq refs (nreverse refs)
6120             count (length refs)))
6121
6122     ;; If the list has more than MAXCOUNT elements, trim it by
6123     ;; removing the CUTth element and the required number of
6124     ;; elements that follow.
6125     (when (> count maxcount)
6126       (let ((surplus (- count maxcount)))
6127         (message-shorten-1 refs cut surplus)
6128         (decf count surplus)))
6129
6130     ;; When sending via news, make sure the total folded length will
6131     ;; be less than 998 characters.  This is to cater to broken INN
6132     ;; 2.3 which counts the total number of characters in a header
6133     ;; rather than the physical line length of each line, as it should.
6134     ;;
6135     ;; This hack should be removed when it's believed than INN 2.3 is
6136     ;; no longer widely used.
6137     ;;
6138     ;; At this point the headers have not been generated, thus we use
6139     ;; message-this-is-news directly.
6140     (when message-this-is-news
6141       (while (< 998
6142                 (with-temp-buffer
6143                   (message-insert-header
6144                    header (mapconcat #'identity refs " "))
6145                   (buffer-size)))
6146         (message-shorten-1 refs cut 1)))
6147     ;; Finally, collect the references back into a string and insert
6148     ;; it into the buffer.
6149     (message-insert-header header (mapconcat #'identity refs " "))))
6150
6151 (defun message-position-point ()
6152   "Move point to where the user probably wants to find it."
6153   (message-narrow-to-headers)
6154   (cond
6155    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
6156     (search-backward ":" )
6157     (widen)
6158     (forward-char 1)
6159     (if (eq (char-after) ? )
6160         (forward-char 1)
6161       (insert " ")))
6162    (t
6163     (goto-char (point-max))
6164     (widen)
6165     (forward-line 1)
6166     (unless (looking-at "$")
6167       (forward-line 2)))
6168    (sit-for 0)))
6169
6170 (defcustom message-beginning-of-line t
6171   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
6172  goes to beginning of header values."
6173   :version "22.1"
6174   :group 'message-buffers
6175   :link '(custom-manual "(message)Movement")
6176   :type 'boolean)
6177
6178 (defun message-beginning-of-line (&optional n)
6179   "Move point to beginning of header value or to beginning of line.
6180 The prefix argument N is passed directly to `beginning-of-line'.
6181
6182 This command is identical to `beginning-of-line' if point is
6183 outside the message header or if the option `message-beginning-of-line'
6184 is nil.
6185
6186 If point is in the message header and on a (non-continued) header
6187 line, move point to the beginning of the header value or the beginning of line,
6188 whichever is closer.  If point is already at beginning of line, move point to
6189 beginning of header value.  Therefore, repeated calls will toggle point
6190 between beginning of field and beginning of line."
6191   (interactive "p")
6192   (let ((zrs 'zmacs-region-stays))
6193     (when (and (featurep 'xemacs) (interactive-p) (boundp zrs))
6194       (set zrs t)))
6195   (if (and message-beginning-of-line
6196            (message-point-in-header-p))
6197       (let* ((here (point))
6198              (bol (progn (beginning-of-line n) (point)))
6199              (eol (point-at-eol))
6200              (eoh (re-search-forward ": *" eol t)))
6201         (goto-char
6202          (if (and eoh (or (< eoh here) (= bol here)))
6203              eoh bol)))
6204     (beginning-of-line n)))
6205
6206 (defun message-buffer-name (type &optional to group)
6207   "Return a new (unique) buffer name based on TYPE and TO."
6208   (cond
6209    ;; Generate a new buffer name The Message Way.
6210    ((memq message-generate-new-buffers '(unique t))
6211     (generate-new-buffer-name
6212      (concat "*" type
6213              (if to
6214                  (concat " to "
6215                          (or (car (mail-extract-address-components to))
6216                              to) "")
6217                "")
6218              (if (and group (not (string= group ""))) (concat " on " group) "")
6219              "*")))
6220    ;; Check whether `message-generate-new-buffers' is a function,
6221    ;; and if so, call it.
6222    ((functionp message-generate-new-buffers)
6223     (funcall message-generate-new-buffers type to group))
6224    ((eq message-generate-new-buffers 'unsent)
6225     (generate-new-buffer-name
6226      (concat "*unsent " type
6227              (if to
6228                  (concat " to "
6229                          (or (car (mail-extract-address-components to))
6230                              to) "")
6231                "")
6232              (if (and group (not (string= group ""))) (concat " on " group) "")
6233              "*")))
6234    ;; Search for the existing message buffer with the specified name.
6235    (t
6236     (let* ((new (if (eq message-generate-new-buffers 'standard)
6237                     (generate-new-buffer-name (concat "*" type " message*"))
6238                   (let ((message-generate-new-buffers 'unique))
6239                     (message-buffer-name type to group))))
6240            (regexp (concat "\\`"
6241                            (regexp-quote
6242                             (if (string-match "<[0-9]+>\\'" new)
6243                                 (substring new 0 (match-beginning 0))
6244                               new))
6245                            "\\(?:<\\([0-9]+\\)>\\)?\\'"))
6246            (case-fold-search nil))
6247       (or (cdar
6248            (last
6249             (sort
6250              (delq nil
6251                    (mapcar
6252                     (lambda (b)
6253                       (when (and (string-match regexp (setq b (buffer-name b)))
6254                                  (eq (with-current-buffer b major-mode)
6255                                      'message-mode))
6256                         (cons (string-to-number (or (match-string 1 b) "1"))
6257                               b)))
6258                     (buffer-list)))
6259              'car-less-than-car)))
6260           new)))))
6261
6262 (defun message-pop-to-buffer (name &optional switch-function)
6263   "Pop to buffer NAME, and warn if it already exists and is modified."
6264   (let ((buffer (get-buffer name)))
6265     (if (and buffer
6266              (buffer-name buffer))
6267         (let ((window (get-buffer-window buffer 0)))
6268           (if window
6269               ;; Raise the frame already displaying the message buffer.
6270               (progn
6271                 (gnus-select-frame-set-input-focus (window-frame window))
6272                 (select-window window))
6273             (funcall (or switch-function 'pop-to-buffer) buffer)
6274             (set-buffer buffer))
6275           (when (and (buffer-modified-p)
6276                      (not (prog1
6277                               (y-or-n-p
6278                                "Message already being composed; erase? ")
6279                             (message nil))))
6280             (error "Message being composed")))
6281       (funcall (or switch-function 'pop-to-buffer) name)
6282       (set-buffer name))
6283     (erase-buffer)
6284     (message-mode)))
6285
6286 (defun message-do-send-housekeeping ()
6287   "Kill old message buffers."
6288   ;; We might have sent this buffer already.  Delete it from the
6289   ;; list of buffers.
6290   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6291   (while (and message-max-buffers
6292               message-buffer-list
6293               (>= (length message-buffer-list) message-max-buffers))
6294     ;; Kill the oldest buffer -- unless it has been changed.
6295     (let ((buffer (pop message-buffer-list)))
6296       (when (and (buffer-name buffer)
6297                  (not (buffer-modified-p buffer)))
6298         (kill-buffer buffer))))
6299   ;; Rename the buffer.
6300   (if message-send-rename-function
6301       (funcall message-send-rename-function)
6302     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6303     (when (string-match
6304            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6305            (buffer-name))
6306       (let ((name (match-string 2 (buffer-name)))
6307             to group)
6308         (if (not (or (null name)
6309                      (string-equal name "mail")
6310                      (string-equal name "posting")))
6311             (setq name (concat "*sent " name "*"))
6312           (message-narrow-to-headers)
6313           (setq to (message-fetch-field "to"))
6314           (setq group (message-fetch-field "newsgroups"))
6315           (widen)
6316           (setq name
6317                 (cond
6318                  (to (concat "*sent mail to "
6319                              (or (car (mail-extract-address-components to))
6320                                  to) "*"))
6321                  ((and group (not (string= group "")))
6322                   (concat "*sent posting on " group "*"))
6323                  (t "*sent mail*"))))
6324         (unless (string-equal name (buffer-name))
6325           (rename-buffer name t)))))
6326   ;; Push the current buffer onto the list.
6327   (when message-max-buffers
6328     (setq message-buffer-list
6329           (nconc message-buffer-list (list (current-buffer))))))
6330
6331 (defun message-mail-user-agent ()
6332   (let ((mua (cond
6333               ((not message-mail-user-agent) nil)
6334               ((eq message-mail-user-agent t) mail-user-agent)
6335               (t message-mail-user-agent))))
6336     (if (memq mua '(message-user-agent gnus-user-agent))
6337         nil
6338       mua)))
6339
6340 ;; YANK-ACTION, if non-nil, can be a buffer or a yank action of the
6341 ;; form (FUNCTION . ARGS).
6342 (defun message-setup (headers &optional yank-action actions
6343                               continue switch-function)
6344   (let ((mua (message-mail-user-agent))
6345         subject to field)
6346     (if (not (and message-this-is-mail mua))
6347         (message-setup-1 headers yank-action actions)
6348       (setq headers (copy-sequence headers))
6349       (setq field (assq 'Subject headers))
6350       (when field
6351         (setq subject (cdr field))
6352         (setq headers (delq field headers)))
6353       (setq field (assq 'To headers))
6354       (when field
6355         (setq to (cdr field))
6356         (setq headers (delq field headers)))
6357       (let ((mail-user-agent mua))
6358         (compose-mail to subject
6359                       (mapcar (lambda (item)
6360                                 (cons
6361                                  (format "%s" (car item))
6362                                  (cdr item)))
6363                               headers)
6364                       continue switch-function
6365                       (if (bufferp yank-action)
6366                           (list 'insert-buffer yank-action)
6367                         yank-action)
6368                       actions)))))
6369
6370 (defun message-headers-to-generate (headers included-headers excluded-headers)
6371   "Return a list that includes all headers from HEADERS.
6372 If INCLUDED-HEADERS is a list, just include those headers.  If it is
6373 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6374 are not included."
6375   (let ((result nil)
6376         header-name)
6377     (dolist (header headers)
6378       (setq header-name (cond
6379                          ((and (consp header)
6380                                (eq (car header) 'optional))
6381                           ;; On the form (optional . Header)
6382                           (cdr header))
6383                          ((consp header)
6384                           ;; On the form (Header . function)
6385                           (car header))
6386                          (t
6387                           ;; Just a Header.
6388                           header)))
6389       (when (and (not (memq header-name excluded-headers))
6390                  (or (eq included-headers t)
6391                      (memq header-name included-headers)))
6392         (push header result)))
6393     (nreverse result)))
6394
6395 (defun message-setup-1 (headers &optional yank-action actions)
6396   (dolist (action actions)
6397     (condition-case nil
6398         (add-to-list 'message-send-actions
6399                      `(apply ',(car action) ',(cdr action)))))
6400   (setq message-reply-buffer
6401         (if (and (consp yank-action)
6402                  (eq (car yank-action) 'insert-buffer))
6403             (nth 1 yank-action)
6404           yank-action))
6405   (goto-char (point-min))
6406   ;; Insert all the headers.
6407   (mail-header-format
6408    (let ((h headers)
6409          (alist message-header-format-alist))
6410      (while h
6411        (unless (assq (caar h) message-header-format-alist)
6412          (push (list (caar h)) alist))
6413        (pop h))
6414      alist)
6415    headers)
6416   (delete-region (point) (progn (forward-line -1) (point)))
6417   (when message-default-headers
6418     (insert
6419      (if (functionp message-default-headers)
6420          (funcall message-default-headers)
6421        message-default-headers))
6422     (or (bolp) (insert ?\n)))
6423   (insert mail-header-separator "\n")
6424   (forward-line -1)
6425   (when (message-news-p)
6426     (when message-default-news-headers
6427       (insert message-default-news-headers)
6428       (or (bolp) (insert ?\n)))
6429     (when message-generate-headers-first
6430       (message-generate-headers
6431        (message-headers-to-generate
6432         (append message-required-news-headers
6433                 message-required-headers)
6434         message-generate-headers-first
6435         '(Lines Subject)))))
6436   (when (message-mail-p)
6437     (when message-default-mail-headers
6438       (insert message-default-mail-headers)
6439       (or (bolp) (insert ?\n)))
6440     (when message-generate-headers-first
6441       (message-generate-headers
6442        (message-headers-to-generate
6443         (append message-required-mail-headers
6444                 message-required-headers)
6445         message-generate-headers-first
6446         '(Lines Subject)))))
6447   (run-hooks 'message-signature-setup-hook)
6448   (message-insert-signature)
6449   (save-restriction
6450     (message-narrow-to-headers)
6451     (run-hooks 'message-header-setup-hook))
6452   (setq buffer-undo-list nil)
6453   (when message-generate-hashcash
6454     ;; Generate hashcash headers for recipients already known
6455     (mail-add-payment-async))
6456   ;; Gnus posting styles are applied via buffer-local `message-setup-hook'
6457   ;; values.
6458   (run-hooks 'message-setup-hook)
6459   ;; Do this last to give it precedence over posting styles, etc.
6460   (when (message-mail-p)
6461     (save-restriction
6462       (message-narrow-to-headers)
6463       (if message-alternative-emails
6464           (message-use-alternative-email-as-from))))
6465   (message-position-point)
6466   ;; Allow correct handling of `message-checksum' in `message-yank-original':
6467   (set-buffer-modified-p nil)
6468   (undo-boundary))
6469
6470 (defun message-set-auto-save-file-name ()
6471   "Associate the message buffer with a file in the drafts directory."
6472   (when message-auto-save-directory
6473     (unless (file-directory-p
6474              (directory-file-name message-auto-save-directory))
6475       (make-directory message-auto-save-directory t))
6476     (if (gnus-alive-p)
6477         (setq message-draft-article
6478               (nndraft-request-associate-buffer "drafts"))
6479
6480       ;; If Gnus were alive, draft messages would be saved in the drafts folder.
6481       ;; But Gnus is not alive, so arrange to save the draft message in a
6482       ;; regular file in message-auto-save-directory.  Append a unique
6483       ;; time-based suffix to the filename to allow multiple drafts to be saved
6484       ;; simultaneously without overwriting each other (which mimics the
6485       ;; functionality of the Gnus drafts folder).
6486       (setq buffer-file-name (expand-file-name
6487                               (concat
6488                               (if (memq system-type
6489                                         '(ms-dos windows-nt cygwin))
6490                                   "message"
6491                                 "*message*")
6492                                (format-time-string "-%Y%m%d-%H%M%S"))
6493                               message-auto-save-directory))
6494       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6495     (clear-visited-file-modtime)
6496     (setq buffer-file-coding-system message-draft-coding-system)))
6497
6498 (defun message-disassociate-draft ()
6499   "Disassociate the message buffer from the drafts directory."
6500   (when message-draft-article
6501     (nndraft-request-expire-articles
6502      (list message-draft-article) "drafts" nil t)))
6503
6504 (defun message-insert-headers ()
6505   "Generate the headers for the article."
6506   (interactive)
6507   (save-excursion
6508     (save-restriction
6509       (message-narrow-to-headers)
6510       (when (message-news-p)
6511         (message-generate-headers
6512          (delq 'Lines
6513                (delq 'Subject
6514                      (copy-sequence message-required-news-headers)))))
6515       (when (message-mail-p)
6516         (message-generate-headers
6517          (delq 'Lines
6518                (delq 'Subject
6519                      (copy-sequence message-required-mail-headers))))))))
6520
6521 \f
6522
6523 ;;;
6524 ;;; Commands for interfacing with message
6525 ;;;
6526
6527 ;;;###autoload
6528 (defun message-mail (&optional to subject
6529                                other-headers continue switch-function
6530                                yank-action send-actions)
6531   "Start editing a mail message to be sent.
6532 OTHER-HEADERS is an alist of header/value pairs.  CONTINUE says whether
6533 to continue editing a message already being composed.  SWITCH-FUNCTION
6534 is a function used to switch to and display the mail buffer."
6535   (interactive)
6536   (let ((message-this-is-mail t))
6537     (unless (message-mail-user-agent)
6538       (message-pop-to-buffer
6539        ;; Search for the existing message buffer if `continue' is non-nil.
6540        (let ((message-generate-new-buffers
6541               (when (or (not continue)
6542                         (eq message-generate-new-buffers 'standard)
6543                         (functionp message-generate-new-buffers))
6544                 message-generate-new-buffers)))
6545          (message-buffer-name "mail" to))
6546        switch-function))
6547     (message-setup
6548      (nconc
6549       `((To . ,(or to "")) (Subject . ,(or subject "")))
6550       (when other-headers other-headers))
6551      yank-action send-actions continue switch-function)
6552     ;; FIXME: Should return nil if failure.
6553     t))
6554
6555 ;;;###autoload
6556 (defun message-news (&optional newsgroups subject)
6557   "Start editing a news article to be sent."
6558   (interactive)
6559   (let ((message-this-is-news t))
6560     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6561     (message-setup `((Newsgroups . ,(or newsgroups ""))
6562                      (Subject . ,(or subject ""))))))
6563
6564 (defun message-alter-recipients-discard-bogus-full-name (addrcell)
6565   "Discard mail address in full names.
6566 When the full name in reply headers contains the mail
6567 address (e.g. \"foo@bar <foo@bar>\"), discard full name.
6568 ADDRCELL is a cons cell where the car is the mail address and the
6569 cdr is the complete address (full name and mail address)."
6570   (if (string-match (concat (regexp-quote (car addrcell)) ".*"
6571                             (regexp-quote (car addrcell)))
6572                     (cdr addrcell))
6573       (cons (car addrcell) (car addrcell))
6574     addrcell))
6575
6576 (defcustom message-alter-recipients-function nil
6577   "Function called to allow alteration of reply header structures.
6578 It is called in `message-get-reply-headers' for each recipient.
6579 The function is called with one parameter, a cons cell ..."
6580   :type '(choice (const :tag "None" nil)
6581                  (const :tag "Discard bogus full name"
6582                         message-alter-recipients-discard-bogus-full-name)
6583                  function)
6584   :version "23.1" ;; No Gnus
6585   :group 'message-headers)
6586
6587 (defun message-get-reply-headers (wide &optional to-address address-headers)
6588   (let (follow-to mct never-mct to cc author mft recipients extra)
6589     ;; Find all relevant headers we need.
6590     (save-restriction
6591       (message-narrow-to-headers-or-head)
6592       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6593       ;; message-header-synonyms.
6594       (setq to (or (message-fetch-field "to")
6595                    (and (loop for synonym in message-header-synonyms
6596                               when (memq 'Original-To synonym)
6597                               return t)
6598                         (message-fetch-field "original-to")))
6599             cc (message-fetch-field "cc")
6600             extra (when message-extra-wide-headers
6601                     (mapconcat 'identity
6602                                (mapcar 'message-fetch-field
6603                                        message-extra-wide-headers)
6604                                ", "))
6605             mct (message-fetch-field "mail-copies-to")
6606             author (or (message-fetch-field "mail-reply-to")
6607                        (message-fetch-field "reply-to")
6608                        (message-fetch-field "from")
6609                        "")
6610             mft (and message-use-mail-followup-to
6611                      (message-fetch-field "mail-followup-to"))))
6612
6613     ;; Handle special values of Mail-Copies-To.
6614     (when mct
6615       (cond ((or (equal (downcase mct) "never")
6616                  (equal (downcase mct) "nobody"))
6617              (setq never-mct t)
6618              (setq mct nil))
6619             ((or (equal (downcase mct) "always")
6620                  (equal (downcase mct) "poster"))
6621              (setq mct author))))
6622
6623     (save-match-data
6624       ;; Build (textual) list of new recipient addresses.
6625       (cond
6626        (to-address
6627         (setq recipients (concat ", " to-address))
6628         ;; If the author explicitly asked for a copy, we don't deny it to them.
6629         (if mct (setq recipients (concat recipients ", " mct))))
6630        ((not wide)
6631         (setq recipients (concat ", " author)))
6632        (address-headers
6633         (dolist (header address-headers)
6634           (let ((value (message-fetch-field header)))
6635             (when value
6636               (setq recipients (concat recipients ", " value))))))
6637        ((and mft
6638              (string-match "[^ \t,]" mft)
6639              (or (not (eq message-use-mail-followup-to 'ask))
6640                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6641 You should normally obey the Mail-Followup-To: header.  In this
6642 article, it has the value of
6643
6644 " mft "
6645
6646 which directs your response to " (if (string-match "," mft)
6647                                      "the specified addresses"
6648                                    "that address only") ".
6649
6650 Most commonly, Mail-Followup-To is used by a mailing list poster to
6651 express that responses should be sent to just the list, and not the
6652 poster as well.
6653
6654 If a message is posted to several mailing lists, Mail-Followup-To may
6655 also be used to direct the following discussion to one list only,
6656 because discussions that are spread over several lists tend to be
6657 fragmented and very difficult to follow.
6658
6659 Also, some source/announcement lists are not intended for discussion;
6660 responses here are directed to other addresses.
6661
6662 You may customize the variable `message-use-mail-followup-to', if you
6663 want to get rid of this query permanently.")))
6664         (setq recipients (concat ", " mft)))
6665        (t
6666         (setq recipients (if never-mct "" (concat ", " author)))
6667         (if to (setq recipients (concat recipients ", " to)))
6668         (if cc (setq recipients (concat recipients ", " cc)))
6669         (if extra (setq recipients (concat recipients ", " extra)))
6670         (if mct (setq recipients (concat recipients ", " mct)))))
6671       (if (>= (length recipients) 2)
6672           ;; Strip the leading ", ".
6673           (setq recipients (substring recipients 2)))
6674       ;; Squeeze whitespace.
6675       (while (string-match "[ \t][ \t]+" recipients)
6676         (setq recipients (replace-match " " t t recipients)))
6677       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6678       (let ((rmail-dont-reply-to-names (message-dont-reply-to-names)))
6679         (setq recipients (rmail-dont-reply-to recipients)))
6680       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6681       (if (string-equal recipients "")
6682           (setq recipients author))
6683       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6684       (setq recipients
6685             (mapcar
6686              (lambda (addr)
6687                (if message-alter-recipients-function
6688                    (funcall message-alter-recipients-function
6689                             (cons (downcase (mail-strip-quoted-names addr))
6690                                   addr))
6691                  (cons (downcase (mail-strip-quoted-names addr)) addr)))
6692              (message-tokenize-header recipients)))
6693       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6694       (let ((s recipients))
6695         (while s
6696           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6697
6698       ;; Remove hierarchical lists that are contained within each other,
6699       ;; if message-hierarchical-addresses is defined.
6700       (when message-hierarchical-addresses
6701         (let ((plain-addrs (mapcar 'car recipients))
6702               subaddrs recip)
6703           (while plain-addrs
6704             (setq subaddrs (assoc (car plain-addrs)
6705                                   message-hierarchical-addresses)
6706                   plain-addrs (cdr plain-addrs))
6707             (when subaddrs
6708               (setq subaddrs (cdr subaddrs))
6709               (while subaddrs
6710                 (setq recip (assoc (car subaddrs) recipients)
6711                       subaddrs (cdr subaddrs))
6712                 (if recip
6713                     (setq recipients (delq recip recipients))))))))
6714
6715       (setq recipients (message-prune-recipients recipients))
6716
6717       ;; Build the header alist.  Allow the user to be asked whether
6718       ;; or not to reply to all recipients in a wide reply.
6719       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6720       (when (and recipients
6721                  (or (not message-wide-reply-confirm-recipients)
6722                      (y-or-n-p "Reply to all recipients? ")))
6723         (setq recipients (mapconcat
6724                           (lambda (addr) (cdr addr)) recipients ", "))
6725         (if (string-match "^ +" recipients)
6726             (setq recipients (substring recipients (match-end 0))))
6727         (push (cons 'Cc recipients) follow-to)))
6728     follow-to))
6729
6730 (defun message-prune-recipients (recipients)
6731   (dolist (rule message-prune-recipient-rules)
6732     (let ((match (car rule))
6733           dup-match
6734           address)
6735       (dolist (recipient recipients)
6736         (setq address (car recipient))
6737         (when (string-match match address)
6738           (setq dup-match (replace-match (cadr rule) nil nil address))
6739           (dolist (recipient recipients)
6740             ;; Don't delete the address that triggered this.
6741             (when (and (not (eq address (car recipient)))
6742                        (string-match dup-match (car recipient)))
6743               (setq recipients (delq recipient recipients))))))))
6744   recipients)
6745
6746 (defcustom message-simplify-subject-functions
6747   '(message-strip-list-identifiers
6748     message-strip-subject-re
6749     message-strip-subject-trailing-was
6750     message-strip-subject-encoded-words)
6751   "List of functions taking a string argument that simplify subjects.
6752 The functions are applied when replying to a message.
6753
6754 Useful functions to put in this list include:
6755 `message-strip-list-identifiers', `message-strip-subject-re',
6756 `message-strip-subject-trailing-was', and
6757 `message-strip-subject-encoded-words'."
6758   :version "22.1" ;; Gnus 5.10.9
6759   :group 'message-various
6760   :type '(repeat function))
6761
6762 (defun message-simplify-subject (subject &optional functions)
6763   "Return simplified SUBJECT."
6764   (unless functions
6765     ;; Simplify fully:
6766     (setq functions message-simplify-subject-functions))
6767   (when (and (memq 'message-strip-list-identifiers functions)
6768              gnus-list-identifiers)
6769     (setq subject (message-strip-list-identifiers subject)))
6770   (when (memq 'message-strip-subject-re functions)
6771     (setq subject (concat "Re: " (message-strip-subject-re subject))))
6772   (when (and (memq 'message-strip-subject-trailing-was functions)
6773              message-subject-trailing-was-query)
6774     (setq subject (message-strip-subject-trailing-was subject)))
6775   (when (memq 'message-strip-subject-encoded-words functions)
6776     (setq subject (message-strip-subject-encoded-words subject)))
6777   subject)
6778
6779 ;;;###autoload
6780 (defun message-reply (&optional to-address wide)
6781   "Start editing a reply to the article in the current buffer."
6782   (interactive)
6783   (require 'gnus-sum)                   ; for gnus-list-identifiers
6784   (let ((cur (current-buffer))
6785         from subject date reply-to to cc
6786         references message-id follow-to
6787         (inhibit-point-motion-hooks t)
6788         (message-this-is-mail t)
6789         gnus-warning)
6790     (save-restriction
6791       (message-narrow-to-head-1)
6792       ;; Allow customizations to have their say.
6793       (if (not wide)
6794           ;; This is a regular reply.
6795           (when (functionp message-reply-to-function)
6796             (save-excursion
6797               (setq follow-to (funcall message-reply-to-function))))
6798         ;; This is a followup.
6799         (when (functionp message-wide-reply-to-function)
6800           (save-excursion
6801             (setq follow-to
6802                   (funcall message-wide-reply-to-function)))))
6803       (setq message-id (message-fetch-field "message-id" t)
6804             references (message-fetch-field "references")
6805             date (message-fetch-field "date")
6806             from (or (message-fetch-field "from") "nobody")
6807             subject (or (message-fetch-field "subject") "none"))
6808
6809       ;; Strip list identifiers, "Re: ", and "was:"
6810       (setq subject (message-simplify-subject subject))
6811
6812       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6813                  (string-match "<[^>]+>" gnus-warning))
6814         (setq message-id (match-string 0 gnus-warning)))
6815
6816       (unless follow-to
6817         (setq follow-to (message-get-reply-headers wide to-address))))
6818
6819     (unless (message-mail-user-agent)
6820       (message-pop-to-buffer
6821        (message-buffer-name
6822         (if wide "wide reply" "reply") from
6823         (if wide to-address nil))))
6824
6825     (setq message-reply-headers
6826           (vector 0 subject from date message-id references 0 0 ""))
6827
6828     (message-setup
6829      `((Subject . ,subject)
6830        ,@follow-to)
6831      cur)))
6832
6833 ;;;###autoload
6834 (defun message-wide-reply (&optional to-address)
6835   "Make a \"wide\" reply to the message in the current buffer."
6836   (interactive)
6837   (message-reply to-address t))
6838
6839 ;;;###autoload
6840 (defun message-followup (&optional to-newsgroups)
6841   "Follow up to the message in the current buffer.
6842 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6843   (interactive)
6844   (require 'gnus-sum)                   ; for gnus-list-identifiers
6845   (let ((cur (current-buffer))
6846         from subject date reply-to mrt mct
6847         references message-id follow-to
6848         (inhibit-point-motion-hooks t)
6849         (message-this-is-news t)
6850         followup-to distribution newsgroups gnus-warning posted-to)
6851     (save-restriction
6852       (narrow-to-region
6853        (goto-char (point-min))
6854        (if (search-forward "\n\n" nil t)
6855            (1- (point))
6856          (point-max)))
6857       (when (functionp message-followup-to-function)
6858         (setq follow-to
6859               (funcall message-followup-to-function)))
6860       (setq from (message-fetch-field "from")
6861             date (message-fetch-field "date")
6862             subject (or (message-fetch-field "subject") "none")
6863             references (message-fetch-field "references")
6864             message-id (message-fetch-field "message-id" t)
6865             followup-to (message-fetch-field "followup-to")
6866             newsgroups (message-fetch-field "newsgroups")
6867             posted-to (message-fetch-field "posted-to")
6868             reply-to (message-fetch-field "reply-to")
6869             mrt (message-fetch-field "mail-reply-to")
6870             distribution (message-fetch-field "distribution")
6871             mct (message-fetch-field "mail-copies-to"))
6872       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6873                  (string-match "<[^>]+>" gnus-warning))
6874         (setq message-id (match-string 0 gnus-warning)))
6875       ;; Remove bogus distribution.
6876       (when (and (stringp distribution)
6877                  (let ((case-fold-search t))
6878                    (string-match "world" distribution)))
6879         (setq distribution nil))
6880       ;; Strip list identifiers, "Re: ", and "was:"
6881       (setq subject (message-simplify-subject subject))
6882       (widen))
6883
6884     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6885
6886     (setq message-reply-headers
6887           (vector 0 subject from date message-id references 0 0 ""))
6888
6889     (message-setup
6890      `((Subject . ,subject)
6891        ,@(cond
6892           (to-newsgroups
6893            (list (cons 'Newsgroups to-newsgroups)))
6894           (follow-to follow-to)
6895           ((and followup-to message-use-followup-to)
6896            (list
6897             (cond
6898              ((equal (downcase followup-to) "poster")
6899               (if (or (eq message-use-followup-to 'use)
6900                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
6901 You should normally obey the Followup-To: header.
6902
6903 `Followup-To: poster' sends your response via e-mail instead of news.
6904
6905 A typical situation where `Followup-To: poster' is used is when the poster
6906 does not read the newsgroup, so he wouldn't see any replies sent to it.
6907
6908 You may customize the variable `message-use-followup-to', if you
6909 want to get rid of this query permanently."))
6910                   (progn
6911                     (setq message-this-is-news nil)
6912                     (cons 'To (or mrt reply-to from "")))
6913                 (cons 'Newsgroups newsgroups)))
6914              (t
6915               (if (or (equal followup-to newsgroups)
6916                       (not (eq message-use-followup-to 'ask))
6917                       (message-y-or-n-p
6918                        (concat "Obey Followup-To: " followup-to "? ") t "\
6919 You should normally obey the Followup-To: header.
6920
6921         `Followup-To: " followup-to "'
6922 directs your response to " (if (string-match "," followup-to)
6923                                "the specified newsgroups"
6924                              "that newsgroup only") ".
6925
6926 If a message is posted to several newsgroups, Followup-To is often
6927 used to direct the following discussion to one newsgroup only,
6928 because discussions that are spread over several newsgroup tend to
6929 be fragmented and very difficult to follow.
6930
6931 Also, some source/announcement newsgroups are not intended for discussion;
6932 responses here are directed to other newsgroups.
6933
6934 You may customize the variable `message-use-followup-to', if you
6935 want to get rid of this query permanently."))
6936                   (cons 'Newsgroups followup-to)
6937                 (cons 'Newsgroups newsgroups))))))
6938           (posted-to
6939            `((Newsgroups . ,posted-to)))
6940           (t
6941            `((Newsgroups . ,newsgroups))))
6942        ,@(and distribution (list (cons 'Distribution distribution)))
6943        ,@(when (and mct
6944                     (not (or (equal (downcase mct) "never")
6945                              (equal (downcase mct) "nobody"))))
6946            (list (cons 'Cc (if (or (equal (downcase mct) "always")
6947                                    (equal (downcase mct) "poster"))
6948                                (or mrt reply-to from "")
6949                              mct)))))
6950
6951      cur)))
6952
6953 (defun message-is-yours-p ()
6954   "Non-nil means current article is yours.
6955 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6956 are yours except those that have Cancel-Lock header not belonging to you.
6957 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6958 regexp to match all of yours addresses."
6959   ;; Canlock-logic as suggested by Per Abrahamsen
6960   ;; <abraham@dina.kvl.dk>
6961   ;;
6962   ;; IF article has cancel-lock THEN
6963   ;;   IF we can verify it THEN
6964   ;;     issue cancel
6965   ;;   ELSE
6966   ;;     error: cancellock: article is not yours
6967   ;; ELSE
6968   ;;   Use old rules, comparing sender...
6969   (save-excursion
6970     (save-restriction
6971       (message-narrow-to-head-1)
6972       (if (message-fetch-field "Cancel-Lock")
6973           (if (null (canlock-verify))
6974               t
6975             (error "Failed to verify Cancel-lock: This article is not yours"))
6976         (let (sender from)
6977           (or
6978            (message-gnksa-enable-p 'cancel-messages)
6979            (and (setq sender (message-fetch-field "sender"))
6980                 (string-equal (downcase sender)
6981                               (downcase (message-make-sender))))
6982            ;; Email address in From field equals to our address
6983            (and (setq from (message-fetch-field "from"))
6984                 (string-equal
6985                  (downcase (car (mail-header-parse-address from)))
6986                  (downcase (car (mail-header-parse-address
6987                                  (message-make-from))))))
6988            ;; Email address in From field matches
6989            ;; 'message-alternative-emails' regexp
6990            (and from
6991                 message-alternative-emails
6992                 (string-match
6993                  message-alternative-emails
6994                  (car (mail-header-parse-address from))))))))))
6995
6996 ;;;###autoload
6997 (defun message-cancel-news (&optional arg)
6998   "Cancel an article you posted.
6999 If ARG, allow editing of the cancellation message."
7000   (interactive "P")
7001   (unless (message-news-p)
7002     (error "This is not a news article; canceling is impossible"))
7003   (let (from newsgroups message-id distribution buf)
7004     (save-excursion
7005       ;; Get header info from original article.
7006       (save-restriction
7007         (message-narrow-to-head-1)
7008         (setq from (message-fetch-field "from")
7009               newsgroups (message-fetch-field "newsgroups")
7010               message-id (message-fetch-field "message-id" t)
7011               distribution (message-fetch-field "distribution")))
7012       ;; Make sure that this article was written by the user.
7013       (unless (message-is-yours-p)
7014         (error "This article is not yours"))
7015       (when (yes-or-no-p "Do you really want to cancel this article? ")
7016         ;; Make control message.
7017         (if arg
7018             (message-news)
7019           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
7020         (erase-buffer)
7021         (insert "Newsgroups: " newsgroups "\n"
7022                 "From: " from "\n"
7023                 "Subject: cmsg cancel " message-id "\n"
7024                 "Control: cancel " message-id "\n"
7025                 (if distribution
7026                     (concat "Distribution: " distribution "\n")
7027                   "")
7028                 mail-header-separator "\n"
7029                 message-cancel-message)
7030         (run-hooks 'message-cancel-hook)
7031         (unless arg
7032           (message "Canceling your article...")
7033           (if (let ((message-syntax-checks
7034                      'dont-check-for-anything-just-trust-me))
7035                 (funcall message-send-news-function))
7036               (message "Canceling your article...done"))
7037           (kill-buffer buf))))))
7038
7039 ;;;###autoload
7040 (defun message-supersede ()
7041   "Start composing a message to supersede the current message.
7042 This is done simply by taking the old article and adding a Supersedes
7043 header line with the old Message-ID."
7044   (interactive)
7045   (let ((cur (current-buffer)))
7046     ;; Check whether the user owns the article that is to be superseded.
7047     (unless (message-is-yours-p)
7048       (error "This article is not yours"))
7049     ;; Get a normal message buffer.
7050     (message-pop-to-buffer (message-buffer-name "supersede"))
7051     (insert-buffer-substring cur)
7052     (mime-to-mml)
7053     (message-narrow-to-head-1)
7054     ;; Remove unwanted headers.
7055     (when message-ignored-supersedes-headers
7056       (message-remove-header message-ignored-supersedes-headers t))
7057     (goto-char (point-min))
7058     (if (not (re-search-forward "^Message-ID: " nil t))
7059         (error "No Message-ID in this article")
7060       (replace-match "Supersedes: " t t))
7061     (goto-char (point-max))
7062     (insert mail-header-separator)
7063     (widen)
7064     (forward-line 1)))
7065
7066 ;;;###autoload
7067 (defun message-recover ()
7068   "Reread contents of current buffer from its last auto-save file."
7069   (interactive)
7070   (let ((file-name (make-auto-save-file-name)))
7071     (cond ((save-window-excursion
7072              (with-output-to-temp-buffer "*Directory*"
7073                (with-current-buffer standard-output
7074                  (fundamental-mode))    ; for Emacs 20.4+
7075                (buffer-disable-undo standard-output)
7076                (let ((default-directory "/"))
7077                  (call-process
7078                   "ls" nil standard-output nil "-l" file-name)))
7079              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
7080            (let ((buffer-read-only nil))
7081              (erase-buffer)
7082              (insert-file-contents file-name nil)))
7083           (t (error "message-recover cancelled")))))
7084
7085 ;;; Washing Subject:
7086
7087 (defun message-wash-subject (subject)
7088   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
7089 Previous forwarders, replyers, etc. may add it."
7090   (with-temp-buffer
7091     (insert subject)
7092     (goto-char (point-min))
7093     ;; strip Re/Fwd stuff off the beginning
7094     (while (re-search-forward
7095             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
7096       (replace-match ""))
7097
7098     ;; and gnus-style forwards [foo@bar.com] subject
7099     (goto-char (point-min))
7100     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
7101       (replace-match ""))
7102
7103     ;; and off the end
7104     (goto-char (point-max))
7105     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
7106       (replace-match ""))
7107
7108     ;; and finally, any whitespace that was left-over
7109     (goto-char (point-min))
7110     (while (re-search-forward "^[ \t]+" nil t)
7111       (replace-match ""))
7112     (goto-char (point-max))
7113     (while (re-search-backward "[ \t]+$" nil t)
7114       (replace-match ""))
7115
7116     (buffer-string)))
7117
7118 ;;; Forwarding messages.
7119
7120 (defvar message-forward-decoded-p nil
7121   "Non-nil means the original message is decoded.")
7122
7123 (defun message-forward-subject-name-subject (subject)
7124   "Generate a SUBJECT for a forwarded message.
7125 The form is: [Source] Subject, where if the original message was mail,
7126 Source is the name of the sender, and if the original message was
7127 news, Source is the list of newsgroups is was posted to."
7128   (let* ((group (message-fetch-field "newsgroups"))
7129          (from (message-fetch-field "from"))
7130          (prefix
7131           (if group
7132               (gnus-group-decoded-name group)
7133             (or (and from (or
7134                            (car (gnus-extract-address-components from))
7135                            (cadr (gnus-extract-address-components from))))
7136                 "(nowhere)"))))
7137     (concat "["
7138             (if message-forward-decoded-p
7139                 prefix
7140               (mail-decode-encoded-word-string prefix))
7141             "] " subject)))
7142
7143 (defun message-forward-subject-author-subject (subject)
7144   "Generate a SUBJECT for a forwarded message.
7145 The form is: [Source] Subject, where if the original message was mail,
7146 Source is the sender, and if the original message was news, Source is
7147 the list of newsgroups is was posted to."
7148   (let* ((group (message-fetch-field "newsgroups"))
7149          (prefix
7150           (if group
7151               (gnus-group-decoded-name group)
7152             (or (message-fetch-field "from")
7153                 "(nowhere)"))))
7154     (concat "["
7155             (if message-forward-decoded-p
7156                 prefix
7157               (mail-decode-encoded-word-string prefix))
7158             "] " subject)))
7159
7160 (defun message-forward-subject-fwd (subject)
7161   "Generate a SUBJECT for a forwarded message.
7162 The form is: Fwd: Subject, where Subject is the original subject of
7163 the message."
7164   (if (string-match "^Fwd: " subject)
7165       subject
7166     (concat "Fwd: " subject)))
7167
7168 (defun message-make-forward-subject ()
7169   "Return a Subject header suitable for the message in the current buffer."
7170   (save-excursion
7171     (save-restriction
7172       (message-narrow-to-head-1)
7173       (let ((funcs message-make-forward-subject-function)
7174             (subject (message-fetch-field "Subject")))
7175         (setq subject
7176               (if subject
7177                   (if message-forward-decoded-p
7178                       subject
7179                     (mail-decode-encoded-word-string subject))
7180                 ""))
7181         (when message-wash-forwarded-subjects
7182           (setq subject (message-wash-subject subject)))
7183         ;; Make sure funcs is a list.
7184         (and funcs
7185              (not (listp funcs))
7186              (setq funcs (list funcs)))
7187         ;; Apply funcs in order, passing subject generated by previous
7188         ;; func to the next one.
7189         (dolist (func funcs)
7190           (when (functionp func)
7191             (setq subject (funcall func subject))))
7192         subject))))
7193
7194 (defvar gnus-article-decoded-p)
7195
7196
7197 ;;;###autoload
7198 (defun message-forward (&optional news digest)
7199   "Forward the current message via mail.
7200 Optional NEWS will use news to forward instead of mail.
7201 Optional DIGEST will use digest to forward."
7202   (interactive "P")
7203   (let* ((cur (current-buffer))
7204          (message-forward-decoded-p
7205           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
7206               gnus-article-decoded-p ;; In an article buffer.
7207             message-forward-decoded-p))
7208          (subject (message-make-forward-subject)))
7209     (if news
7210         (message-news nil subject)
7211       (message-mail nil subject))
7212     (message-forward-make-body cur digest)))
7213
7214 (defun message-forward-make-body-plain (forward-buffer)
7215   (insert
7216    "\n-------------------- Start of forwarded message --------------------\n")
7217   (let ((b (point))
7218         (contents (with-current-buffer forward-buffer (buffer-string)))
7219         e)
7220     (unless (featurep 'xemacs)
7221       (unless (mm-multibyte-string-p contents)
7222         (error "Attempt to insert unibyte string from the buffer \"%s\"\
7223  to the multibyte buffer \"%s\""
7224                (if (bufferp forward-buffer)
7225                    (buffer-name forward-buffer)
7226                  forward-buffer)
7227                (buffer-name))))
7228     (insert (mm-with-multibyte-buffer
7229               (insert contents)
7230               (mime-to-mml)
7231               (goto-char (point-min))
7232               (when (looking-at "From ")
7233                 (replace-match "X-From-Line: "))
7234               (buffer-string)))
7235     (unless (bolp) (insert "\n"))
7236     (setq e (point))
7237     (insert
7238      "-------------------- End of forwarded message --------------------\n")
7239     (message-remove-ignored-headers b e)))
7240
7241 (defun message-remove-ignored-headers (b e)
7242   (when message-forward-ignored-headers
7243     (save-restriction
7244       (narrow-to-region b e)
7245       (goto-char b)
7246       (narrow-to-region (point)
7247                         (or (search-forward "\n\n" nil t) (point)))
7248       (let ((ignored (if (stringp message-forward-ignored-headers)
7249                          (list message-forward-ignored-headers)
7250                        message-forward-ignored-headers)))
7251         (dolist (elem ignored)
7252           (message-remove-header elem t))))))
7253
7254 (defun message-forward-make-body-mime (forward-buffer)
7255   (let ((b (point)))
7256     (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7257     (save-restriction
7258       (narrow-to-region (point) (point))
7259       (mml-insert-buffer forward-buffer)
7260       (goto-char (point-min))
7261       (when (looking-at "From ")
7262         (replace-match "X-From-Line: "))
7263       (goto-char (point-max)))
7264     (insert "<#/part>\n")
7265     ;; Consider there is no illegible text.
7266     (add-text-properties
7267      b (point)
7268      `(no-illegible-text t rear-nonsticky t start-open t))))
7269
7270 (defun message-forward-make-body-mml (forward-buffer)
7271   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7272   (let ((b (point)) e)
7273     (if (not message-forward-decoded-p)
7274         (let ((contents (with-current-buffer forward-buffer (buffer-string))))
7275           (unless (featurep 'xemacs)
7276             (unless (mm-multibyte-string-p contents)
7277               (error "Attempt to insert unibyte string from the buffer \"%s\"\
7278  to the multibyte buffer \"%s\""
7279                      (if (bufferp forward-buffer)
7280                          (buffer-name forward-buffer)
7281                        forward-buffer)
7282                      (buffer-name))))
7283           (insert (mm-with-multibyte-buffer
7284                     (insert contents)
7285                     (mime-to-mml)
7286                     (goto-char (point-min))
7287                     (when (looking-at "From ")
7288                       (replace-match "X-From-Line: "))
7289                     (buffer-string))))
7290       (save-restriction
7291         (narrow-to-region (point) (point))
7292         (mml-insert-buffer forward-buffer)
7293         (goto-char (point-min))
7294         (when (looking-at "From ")
7295           (replace-match "X-From-Line: "))
7296         (goto-char (point-max))))
7297     (setq e (point))
7298     (insert "<#/mml>\n")
7299     (when (and (not message-forward-decoded-p)
7300                message-forward-ignored-headers)
7301       (message-remove-ignored-headers b e))))
7302
7303 (defun message-forward-make-body-digest-plain (forward-buffer)
7304   (insert
7305    "\n-------------------- Start of forwarded message --------------------\n")
7306   (let ((b (point)) e)
7307     (mml-insert-buffer forward-buffer)
7308     (setq e (point))
7309     (insert
7310      "\n-------------------- End of forwarded message --------------------\n")))
7311
7312 (defun message-forward-make-body-digest-mime (forward-buffer)
7313   (insert "\n<#multipart type=digest>\n")
7314   (let ((b (point)) e)
7315     (insert-buffer-substring forward-buffer)
7316     (setq e (point))
7317     (insert "<#/multipart>\n")
7318     (save-restriction
7319       (narrow-to-region b e)
7320       (goto-char b)
7321       (narrow-to-region (point)
7322                         (or (search-forward "\n\n" nil t) (point)))
7323       (delete-region (point-min) (point-max)))))
7324
7325 (defun message-forward-make-body-digest (forward-buffer)
7326   (if message-forward-as-mime
7327       (message-forward-make-body-digest-mime forward-buffer)
7328     (message-forward-make-body-digest-plain forward-buffer)))
7329
7330 (autoload 'mm-uu-dissect-text-parts "mm-uu")
7331 (autoload 'mm-uu-dissect "mm-uu")
7332
7333 (defun message-signed-or-encrypted-p (&optional dont-emulate-mime handles)
7334   "Say whether the current buffer contains signed or encrypted message.
7335 If DONT-EMULATE-MIME is nil, this function does the MIME emulation on
7336 messages that don't conform to PGP/MIME described in RFC2015.  HANDLES
7337 is for the internal use."
7338   (unless handles
7339     (let ((mm-decrypt-option 'never)
7340           (mm-verify-option 'never))
7341       (if (setq handles (mm-dissect-buffer nil t))
7342           (unless dont-emulate-mime
7343             (mm-uu-dissect-text-parts handles))
7344         (unless dont-emulate-mime
7345           (setq handles (mm-uu-dissect))))))
7346   ;; Check text/plain message in which there is a signed or encrypted
7347   ;; body that has been encoded by B or Q.
7348   (unless (or handles dont-emulate-mime)
7349     (let ((cur (current-buffer))
7350           (mm-decrypt-option 'never)
7351           (mm-verify-option 'never))
7352       (with-temp-buffer
7353         (insert-buffer-substring cur)
7354         (when (setq handles (mm-dissect-buffer t t))
7355           (if (and (prog1
7356                        (bufferp (car handles))
7357                      (mm-destroy-parts handles))
7358                    (equal (mm-handle-media-type handles) "text/plain"))
7359               (progn
7360                 (mm-decode-content-transfer-encoding
7361                  (mm-handle-encoding handles))
7362                 (setq handles (mm-uu-dissect)))
7363             (setq handles nil))))))
7364   (when handles
7365     (prog1
7366         (catch 'found
7367           (dolist (handle (if (stringp (car handles))
7368                               (if (member (car handles)
7369                                           '("multipart/signed"
7370                                             "multipart/encrypted"))
7371                                   (throw 'found t)
7372                                 (cdr handles))
7373                             (list handles)))
7374             (if (stringp (car handle))
7375                 (when (message-signed-or-encrypted-p dont-emulate-mime handle)
7376                   (throw 'found t))
7377               (when (and (bufferp (car handle))
7378                          (equal (mm-handle-media-type handle)
7379                                 "message/rfc822"))
7380                 (with-current-buffer (mm-handle-buffer handle)
7381                   (when (message-signed-or-encrypted-p dont-emulate-mime)
7382                     (throw 'found t)))))))
7383       (mm-destroy-parts handles))))
7384
7385 ;;;###autoload
7386 (defun message-forward-make-body (forward-buffer &optional digest)
7387   ;; Put point where we want it before inserting the forwarded
7388   ;; message.
7389   (if message-forward-before-signature
7390       (message-goto-body)
7391     (goto-char (point-max)))
7392   (if digest
7393       (message-forward-make-body-digest forward-buffer)
7394     (if message-forward-as-mime
7395         (if (and message-forward-show-mml
7396                  (not (and (eq message-forward-show-mml 'best)
7397                            ;; Use the raw form in the body if it contains
7398                            ;; signed or encrypted message so as not to be
7399                            ;; destroyed by re-encoding.
7400                            (with-current-buffer forward-buffer
7401                              (condition-case nil
7402                                  (message-signed-or-encrypted-p)
7403                                (error t))))))
7404             (message-forward-make-body-mml forward-buffer)
7405           (message-forward-make-body-mime forward-buffer))
7406       (message-forward-make-body-plain forward-buffer)))
7407   (message-position-point))
7408
7409 (declare-function rmail-toggle-header "rmail" (&optional arg))
7410
7411 ;;;###autoload
7412 (defun message-forward-rmail-make-body (forward-buffer)
7413   (save-window-excursion
7414     (set-buffer forward-buffer)
7415     (if (rmail-msg-is-pruned)
7416         (if (fboundp 'rmail-msg-restore-non-pruned-header)
7417             (rmail-msg-restore-non-pruned-header) ; Emacs 22
7418           (rmail-toggle-header 0))))              ; Emacs 23
7419   (message-forward-make-body forward-buffer))
7420
7421 ;; Fixme: Should have defcustom.
7422 ;;;###autoload
7423 (defun message-insinuate-rmail ()
7424   "Let RMAIL use message to forward."
7425   (interactive)
7426   (setq rmail-enable-mime-composing t)
7427   (setq rmail-insert-mime-forwarded-message-function
7428         'message-forward-rmail-make-body))
7429
7430 ;;;###autoload
7431 (defun message-resend (address)
7432   "Resend the current article to ADDRESS."
7433   (interactive
7434    (list (message-read-from-minibuffer "Resend message to: ")))
7435   (message "Resending message to %s..." address)
7436   (save-excursion
7437     (let ((cur (current-buffer))
7438           beg)
7439       ;; We first set up a normal mail buffer.
7440       (unless (message-mail-user-agent)
7441         (set-buffer (get-buffer-create " *message resend*"))
7442         (erase-buffer))
7443       (let ((message-this-is-mail t)
7444             message-generate-hashcash
7445             message-setup-hook)
7446         (message-setup `((To . ,address))))
7447       ;; Insert our usual headers.
7448       (message-generate-headers '(From Date To Message-ID))
7449       (message-narrow-to-headers)
7450       ;; Remove X-Draft-From header etc.
7451       (message-remove-header message-ignored-mail-headers t)
7452       ;; Rename them all to "Resent-*".
7453       (goto-char (point-min))
7454       (while (re-search-forward "^[A-Za-z]" nil t)
7455         (forward-char -1)
7456         (insert "Resent-"))
7457       (widen)
7458       (forward-line)
7459       (delete-region (point) (point-max))
7460       (setq beg (point))
7461       ;; Insert the message to be resent.
7462       (insert-buffer-substring cur)
7463       (goto-char (point-min))
7464       (search-forward "\n\n")
7465       (forward-char -1)
7466       (save-restriction
7467         (narrow-to-region beg (point))
7468         (message-remove-header message-ignored-resent-headers t)
7469         (goto-char (point-max)))
7470       (insert mail-header-separator)
7471       ;; Rename all old ("Also-")Resent headers.
7472       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7473         (beginning-of-line)
7474         (insert "Also-"))
7475       ;; Quote any "From " lines at the beginning.
7476       (goto-char beg)
7477       (when (looking-at "From ")
7478         (replace-match "X-From-Line: "))
7479       ;; Send it.
7480       (let ((message-inhibit-body-encoding
7481              ;; Don't do any further encoding if it looks like the
7482              ;; message has already been encoded.
7483              (let ((case-fold-search t))
7484                (re-search-forward "^mime-version:" nil t)))
7485             (message-inhibit-ecomplete t)
7486             message-required-mail-headers
7487             message-generate-hashcash
7488             rfc2047-encode-encoded-words)
7489         (message-send-mail))
7490       (kill-buffer (current-buffer)))
7491     (message "Resending message to %s...done" address)))
7492
7493 ;;;###autoload
7494 (defun message-bounce ()
7495   "Re-mail the current message.
7496 This only makes sense if the current message is a bounce message that
7497 contains some mail you have written which has been bounced back to
7498 you."
7499   (interactive)
7500   (let ((handles (mm-dissect-buffer t))
7501         boundary)
7502     (message-pop-to-buffer (message-buffer-name "bounce"))
7503     (if (stringp (car handles))
7504         ;; This is a MIME bounce.
7505         (mm-insert-part (car (last handles)))
7506       ;; This is a non-MIME bounce, so we try to remove things
7507       ;; manually.
7508       (mm-insert-part handles)
7509       (undo-boundary)
7510       (goto-char (point-min))
7511       (re-search-forward "\n\n+" nil t)
7512       (setq boundary (point))
7513       ;; We remove everything before the bounced mail.
7514       (if (or (re-search-forward message-unsent-separator nil t)
7515               (progn
7516                 (search-forward "\n\n" nil 'move)
7517                 (re-search-backward "^Return-Path:.*\n" boundary t)))
7518           (progn
7519             (forward-line 1)
7520             (delete-region (point-min)
7521                            (if (re-search-forward "^[^ \n\t]+:" nil t)
7522                                (match-beginning 0)
7523                              (point))))
7524         (goto-char boundary)
7525         (when (re-search-backward "^.?From .*\n" nil t)
7526           (delete-region (match-beginning 0) (match-end 0)))))
7527     (mime-to-mml)
7528     (save-restriction
7529       (message-narrow-to-head-1)
7530       (message-remove-header message-ignored-bounced-headers t)
7531       (goto-char (point-max))
7532       (insert mail-header-separator))
7533     (message-position-point)))
7534
7535 ;;;
7536 ;;; Interactive entry points for new message buffers.
7537 ;;;
7538
7539 ;;;###autoload
7540 (defun message-mail-other-window (&optional to subject)
7541   "Like `message-mail' command, but display mail buffer in another window."
7542   (interactive)
7543   (unless (message-mail-user-agent)
7544     (let ((pop-up-windows t)
7545           (special-display-buffer-names nil)
7546           (special-display-regexps nil)
7547           (same-window-buffer-names nil)
7548           (same-window-regexps nil))
7549       (message-pop-to-buffer (message-buffer-name "mail" to))))
7550   (let ((message-this-is-mail t))
7551     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7552                    nil nil nil 'switch-to-buffer-other-window)))
7553
7554 ;;;###autoload
7555 (defun message-mail-other-frame (&optional to subject)
7556   "Like `message-mail' command, but display mail buffer in another frame."
7557   (interactive)
7558   (unless (message-mail-user-agent)
7559     (let ((pop-up-frames t)
7560           (special-display-buffer-names nil)
7561           (special-display-regexps nil)
7562           (same-window-buffer-names nil)
7563           (same-window-regexps nil))
7564       (message-pop-to-buffer (message-buffer-name "mail" to))))
7565   (let ((message-this-is-mail t))
7566     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7567                    nil nil nil 'switch-to-buffer-other-frame)))
7568
7569 ;;;###autoload
7570 (defun message-news-other-window (&optional newsgroups subject)
7571   "Start editing a news article to be sent."
7572   (interactive)
7573   (let ((pop-up-windows t)
7574         (special-display-buffer-names nil)
7575         (special-display-regexps nil)
7576         (same-window-buffer-names nil)
7577         (same-window-regexps nil))
7578     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7579   (let ((message-this-is-news t))
7580     (message-setup `((Newsgroups . ,(or newsgroups ""))
7581                      (Subject . ,(or subject ""))))))
7582
7583 ;;;###autoload
7584 (defun message-news-other-frame (&optional newsgroups subject)
7585   "Start editing a news article to be sent."
7586   (interactive)
7587   (let ((pop-up-frames t)
7588         (special-display-buffer-names nil)
7589         (special-display-regexps nil)
7590         (same-window-buffer-names nil)
7591         (same-window-regexps nil))
7592     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7593   (let ((message-this-is-news t))
7594     (message-setup `((Newsgroups . ,(or newsgroups ""))
7595                      (Subject . ,(or subject ""))))))
7596
7597 ;;; underline.el
7598
7599 ;; This code should be moved to underline.el (from which it is stolen).
7600
7601 ;;;###autoload
7602 (defun message-bold-region (start end)
7603   "Bold all nonblank characters in the region.
7604 Works by overstriking characters.
7605 Called from program, takes two arguments START and END
7606 which specify the range to operate on."
7607   (interactive "r")
7608   (save-excursion
7609     (let ((end1 (make-marker)))
7610       (move-marker end1 (max start end))
7611       (goto-char (min start end))
7612       (while (< (point) end1)
7613         (or (looking-at "[_\^@- ]")
7614             (insert (char-after) "\b"))
7615         (forward-char 1)))))
7616
7617 ;;;###autoload
7618 (defun message-unbold-region (start end)
7619   "Remove all boldness (overstruck characters) in the region.
7620 Called from program, takes two arguments START and END
7621 which specify the range to operate on."
7622   (interactive "r")
7623   (save-excursion
7624     (let ((end1 (make-marker)))
7625       (move-marker end1 (max start end))
7626       (goto-char (min start end))
7627       (while (search-forward "\b" end1 t)
7628         (if (eq (char-after) (char-after (- (point) 2)))
7629             (delete-char -2))))))
7630
7631 (defun message-exchange-point-and-mark ()
7632   "Exchange point and mark, but don't activate region if it was inactive."
7633   (goto-char (prog1 (mark t)
7634                (set-marker (mark-marker) (point)))))
7635
7636 (defalias 'message-make-overlay 'make-overlay)
7637 (defalias 'message-delete-overlay 'delete-overlay)
7638 (defalias 'message-overlay-put 'overlay-put)
7639 (defun message-kill-all-overlays ()
7640   (if (featurep 'xemacs)
7641       (map-extents (lambda (extent ignore) (delete-extent extent)))
7642     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7643
7644 ;; Support for toolbar
7645 (defvar tool-bar-mode)
7646
7647 ;; Note: The :set function in the `message-tool-bar*' variables will only
7648 ;; affect _new_ message buffers.  We might add a function that walks thru all
7649 ;; message-mode buffers and force the update.
7650 (defun message-tool-bar-update (&optional symbol value)
7651   "Update message mode toolbar.
7652 Setter function for custom variables."
7653   (setq-default message-tool-bar-map nil)
7654   (when symbol
7655     ;; When used as ":set" function:
7656     (set-default symbol value)))
7657
7658 (defcustom message-tool-bar (if (eq gmm-tool-bar-style 'gnome)
7659                                 'message-tool-bar-gnome
7660                               'message-tool-bar-retro)
7661   "Specifies the message mode tool bar.
7662
7663 It can be either a list or a symbol refering to a list.  See
7664 `gmm-tool-bar-from-list' for the format of the list.  The
7665 default key map is `message-mode-map'.
7666
7667 Pre-defined symbols include `message-tool-bar-gnome' and
7668 `message-tool-bar-retro'."
7669   :type '(repeat gmm-tool-bar-list-item)
7670   :type '(choice (const :tag "GNOME style" message-tool-bar-gnome)
7671                  (const :tag "Retro look"  message-tool-bar-retro)
7672                  (repeat :tag "User defined list" gmm-tool-bar-item)
7673                  (symbol))
7674   :version "23.1" ;; No Gnus
7675   :initialize 'custom-initialize-default
7676   :set 'message-tool-bar-update
7677   :group 'message)
7678
7679 (defcustom message-tool-bar-gnome
7680   '((ispell-message "spell" nil
7681                     :visible (or (not (boundp 'flyspell-mode))
7682                                  (not flyspell-mode)))
7683     (flyspell-buffer "spell" t
7684                      :visible (and (boundp 'flyspell-mode)
7685                                    flyspell-mode)
7686                      :help "Flyspell whole buffer")
7687     (gmm-ignore "separator")
7688     (message-send-and-exit "mail/send")
7689     (message-dont-send "mail/save-draft")
7690     (message-kill-buffer "close") ;; stock_cancel
7691     (mml-attach-file "attach" mml-mode-map)
7692     (mml-preview "mail/preview" mml-mode-map)
7693     (mml-secure-message-sign-encrypt "lock" mml-mode-map :visible nil)
7694     (message-insert-importance-high "important" nil :visible nil)
7695     (message-insert-importance-low "unimportant" nil :visible nil)
7696     (message-insert-disposition-notification-to "receipt" nil :visible nil)
7697     (gmm-customize-mode "preferences" t :help "Edit mode preferences")
7698     (message-info "help" t :help "Message manual"))
7699   "List of items for the message tool bar (GNOME style).
7700
7701 See `gmm-tool-bar-from-list' for details on the format of the list."
7702   :type '(repeat gmm-tool-bar-item)
7703   :version "23.1" ;; No Gnus
7704   :initialize 'custom-initialize-default
7705   :set 'message-tool-bar-update
7706   :group 'message)
7707
7708 (defcustom message-tool-bar-retro
7709   '(;; Old Emacs 21 icon for consistency.
7710     (message-send-and-exit "gnus/mail-send")
7711     (message-kill-buffer "close")
7712     (message-dont-send "cancel")
7713     (mml-attach-file "attach" mml-mode-map)
7714     (ispell-message "spell")
7715     (mml-preview "preview" mml-mode-map)
7716     (message-insert-importance-high "gnus/important")
7717     (message-insert-importance-low "gnus/unimportant")
7718     (message-insert-disposition-notification-to "gnus/receipt"))
7719   "List of items for the message tool bar (retro style).
7720
7721 See `gmm-tool-bar-from-list' for details on the format of the list."
7722   :type '(repeat gmm-tool-bar-item)
7723   :version "23.1" ;; No Gnus
7724   :initialize 'custom-initialize-default
7725   :set 'message-tool-bar-update
7726   :group 'message)
7727
7728 (defcustom message-tool-bar-zap-list
7729   '(new-file open-file dired kill-buffer write-file
7730              print-buffer customize help)
7731   "List of icon items from the global tool bar.
7732 These items are not displayed on the message mode tool bar.
7733
7734 See `gmm-tool-bar-from-list' for the format of the list."
7735   :type 'gmm-tool-bar-zap-list
7736   :version "23.1" ;; No Gnus
7737   :initialize 'custom-initialize-default
7738   :set 'message-tool-bar-update
7739   :group 'message)
7740
7741 (defvar image-load-path)
7742
7743 (defun message-make-tool-bar (&optional force)
7744   "Make a message mode tool bar from `message-tool-bar-list'.
7745 When FORCE, rebuild the tool bar."
7746   (when (and (not (featurep 'xemacs))
7747              (boundp 'tool-bar-mode)
7748              tool-bar-mode
7749              (or (not message-tool-bar-map) force))
7750     (setq message-tool-bar-map
7751           (let* ((load-path
7752                   (gmm-image-load-path-for-library "message"
7753                                                    "mail/save-draft.xpm"
7754                                                    nil t))
7755                  (image-load-path (cons (car load-path)
7756                                         (when (boundp 'image-load-path)
7757                                           image-load-path))))
7758             (gmm-tool-bar-from-list message-tool-bar
7759                                     message-tool-bar-zap-list
7760                                     'message-mode-map))))
7761   message-tool-bar-map)
7762
7763 ;;; Group name completion.
7764
7765 (defcustom message-newgroups-header-regexp
7766   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7767   "Regexp that match headers that lists groups."
7768   :group 'message
7769   :type 'regexp)
7770
7771 (defcustom message-completion-alist
7772   (list (cons message-newgroups-header-regexp 'message-expand-group)
7773         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7774         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7775           . message-expand-name)
7776         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7777           . message-expand-name))
7778   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7779   :version "22.1"
7780   :group 'message
7781   :type '(alist :key-type regexp :value-type function))
7782
7783 (defcustom message-expand-name-databases
7784   (list 'bbdb 'eudc)
7785   "List of databases to try for name completion (`message-expand-name').
7786 Each element is a symbol and can be `bbdb' or `eudc'."
7787   :group 'message
7788   :type '(set (const bbdb) (const eudc)))
7789
7790 (defcustom message-tab-body-function nil
7791   "*Function to execute when `message-tab' (TAB) is executed in the body.
7792 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7793   :version "22.1"
7794   :group 'message
7795   :link '(custom-manual "(message)Various Commands")
7796   :type '(choice (const nil)
7797                  function))
7798
7799 (declare-function mail-abbrev-in-expansion-header-p "mailabbrev" ())
7800
7801 (defun message-tab ()
7802   "Complete names according to `message-completion-alist'.
7803 Execute function specified by `message-tab-body-function' when not in
7804 those headers."
7805   (interactive)
7806   (let ((alist message-completion-alist))
7807     (while (and alist
7808                 (let ((mail-abbrev-mode-regexp (caar alist)))
7809                   (not (mail-abbrev-in-expansion-header-p))))
7810       (setq alist (cdr alist)))
7811     (funcall (or (cdar alist) message-tab-body-function
7812                  (lookup-key text-mode-map "\t")
7813                  (lookup-key global-map "\t")
7814                  'indent-relative))))
7815
7816 (eval-and-compile
7817   (condition-case nil
7818       (with-temp-buffer
7819         (let ((standard-output (current-buffer)))
7820           (eval '(display-completion-list nil "")))
7821         (defalias 'message-display-completion-list 'display-completion-list))
7822     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
7823      (defun message-display-completion-list (completions &optional ignore)
7824        "Display the list of completions, COMPLETIONS, using `standard-output'."
7825        (display-completion-list completions)))))
7826
7827 (defun message-expand-group ()
7828   "Expand the group name under point."
7829   (let* ((b (save-excursion
7830               (save-restriction
7831                 (narrow-to-region
7832                  (save-excursion
7833                    (beginning-of-line)
7834                    (skip-chars-forward "^:")
7835                    (1+ (point)))
7836                  (point))
7837                 (skip-chars-backward "^, \t\n") (point))))
7838          (completion-ignore-case t)
7839          (e (progn (skip-chars-forward "^,\t\n ") (point)))
7840          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb)))
7841     (message-completion-in-region e b hashtb)))
7842
7843 (defalias 'message-completion-in-region
7844   (if (fboundp 'completion-in-region)
7845       'completion-in-region
7846     (lambda (e b hashtb)
7847       (let* ((string (buffer-substring b e))
7848              (completions (all-completions string hashtb))
7849              comp)
7850         (delete-region b (point))
7851         (cond
7852          ((= (length completions) 1)
7853           (if (string= (car completions) string)
7854               (progn
7855                 (insert string)
7856                 (message "Only matching group"))
7857             (insert (car completions))))
7858          ((and (setq comp (try-completion string hashtb))
7859                (not (string= comp string)))
7860           (insert comp))
7861          (t
7862           (insert string)
7863           (if (not comp)
7864               (message "No matching groups")
7865             (save-selected-window
7866               (pop-to-buffer "*Completions*")
7867               (buffer-disable-undo)
7868               (let ((buffer-read-only nil))
7869                 (erase-buffer)
7870                 (let ((standard-output (current-buffer)))
7871                   (message-display-completion-list (sort completions 'string<)
7872                                                    string))
7873                 (setq buffer-read-only nil)
7874                 (goto-char (point-min))
7875                 (delete-region (point)
7876                                (progn (forward-line 3) (point))))))))))))
7877
7878 (defun message-expand-name ()
7879   (cond ((and (memq 'eudc message-expand-name-databases)
7880                     (boundp 'eudc-protocol)
7881                     eudc-protocol)
7882          (eudc-expand-inline))
7883         ((and (memq 'bbdb message-expand-name-databases)
7884               (fboundp 'bbdb-complete-name))
7885          (bbdb-complete-name))
7886         (t
7887          (expand-abbrev))))
7888
7889 ;;; Help stuff.
7890
7891 (defun message-talkative-question (ask question show &rest text)
7892   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7893 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7894 The following arguments may contain lists of values."
7895   (if (and show
7896            (setq text (message-flatten-list text)))
7897       (save-window-excursion
7898         (with-output-to-temp-buffer " *MESSAGE information message*"
7899           (with-current-buffer " *MESSAGE information message*"
7900             (fundamental-mode)          ; for Emacs 20.4+
7901             (mapc 'princ text)
7902             (goto-char (point-min))))
7903         (funcall ask question))
7904     (funcall ask question)))
7905
7906 (defun message-flatten-list (list)
7907   "Return a new, flat list that contains all elements of LIST.
7908
7909 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7910 => (1 2 3 4 5 6 7)"
7911   (cond ((consp list)
7912          (apply 'append (mapcar 'message-flatten-list list)))
7913         (list
7914          (list list))))
7915
7916 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7917   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7918 Then clone the local variables and values from the old buffer to the
7919 new one, cloning only the locals having a substring matching the
7920 regexp VARSTR."
7921   (let ((oldbuf (current-buffer)))
7922     (with-current-buffer (generate-new-buffer name)
7923       (message-clone-locals oldbuf varstr)
7924       (current-buffer))))
7925
7926 (defun message-clone-locals (buffer &optional varstr)
7927   "Clone the local variables from BUFFER to the current buffer."
7928   (let ((locals (with-current-buffer buffer (buffer-local-variables)))
7929         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
7930     (mapcar
7931      (lambda (local)
7932        (when (and (consp local)
7933                   (car local)
7934                   (string-match regexp (symbol-name (car local)))
7935                   (or (null varstr)
7936                       (string-match varstr (symbol-name (car local)))))
7937          (ignore-errors
7938            (set (make-local-variable (car local))
7939                 (cdr local)))))
7940      locals)))
7941
7942 ;;;
7943 ;;; MIME functions
7944 ;;;
7945
7946 (defvar message-inhibit-body-encoding nil)
7947
7948 (defun message-encode-message-body ()
7949   (unless message-inhibit-body-encoding
7950     (let ((mail-parse-charset (or mail-parse-charset
7951                                   message-default-charset))
7952           (case-fold-search t)
7953           lines content-type-p)
7954       (message-goto-body)
7955       (save-restriction
7956         (narrow-to-region (point) (point-max))
7957         (let ((new (mml-generate-mime)))
7958           (when new
7959             (delete-region (point-min) (point-max))
7960             (insert new)
7961             (goto-char (point-min))
7962             (if (eq (aref new 0) ?\n)
7963                 (delete-char 1)
7964               (search-forward "\n\n")
7965               (setq lines (buffer-substring (point-min) (1- (point))))
7966               (delete-region (point-min) (point))))))
7967       (save-restriction
7968         (message-narrow-to-headers-or-head)
7969         (message-remove-header "Mime-Version")
7970         (goto-char (point-max))
7971         (insert "MIME-Version: 1.0\n")
7972         (when lines
7973           (insert lines))
7974         (setq content-type-p
7975               (or mml-boundary
7976                   (re-search-backward "^Content-Type:" nil t))))
7977       (save-restriction
7978         (message-narrow-to-headers-or-head)
7979         (message-remove-first-header "Content-Type")
7980         (message-remove-first-header "Content-Transfer-Encoding"))
7981       ;; We always make sure that the message has a Content-Type
7982       ;; header.  This is because some broken MTAs and MUAs get
7983       ;; awfully confused when confronted with a message with a
7984       ;; MIME-Version header and without a Content-Type header.  For
7985       ;; instance, Solaris' /usr/bin/mail.
7986       (unless content-type-p
7987         (goto-char (point-min))
7988         ;; For unknown reason, MIME-Version doesn't exist.
7989         (when (re-search-forward "^MIME-Version:" nil t)
7990           (forward-line 1)
7991           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7992
7993 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7994   "Read from the minibuffer while providing abbrev expansion."
7995   (if (fboundp 'mail-abbrevs-setup)
7996       (let ((mail-abbrev-mode-regexp "")
7997             (minibuffer-setup-hook 'mail-abbrevs-setup)
7998             (minibuffer-local-map message-minibuffer-local-map))
7999         (read-from-minibuffer prompt initial-contents))
8000     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
8001           (minibuffer-local-map message-minibuffer-local-map))
8002       (read-string prompt initial-contents))))
8003
8004 (defun message-use-alternative-email-as-from ()
8005   "Set From field of the outgoing message to the first matching
8006 address in `message-alternative-emails', looking at To, Cc and
8007 From headers in the original article."
8008   (require 'mail-utils)
8009   (let* ((fields '("To" "Cc" "From"))
8010          (emails
8011           (split-string
8012            (mail-strip-quoted-names
8013             (mapconcat 'message-fetch-reply-field fields ","))
8014            "[ \f\t\n\r\v,]+"))
8015          email)
8016     (while emails
8017       (if (string-match message-alternative-emails (car emails))
8018           (setq email (car emails)
8019                 emails nil))
8020       (pop emails))
8021     (unless (or (not email) (equal email user-mail-address))
8022       (message-remove-header "From")
8023       (goto-char (point-max))
8024       (insert "From: " (let ((user-mail-address email)) (message-make-from))
8025               "\n"))))
8026
8027 (defun message-options-get (symbol)
8028   (cdr (assq symbol message-options)))
8029
8030 (defun message-options-set (symbol value)
8031   (let ((the-cons (assq symbol message-options)))
8032     (if the-cons
8033         (if value
8034             (setcdr the-cons value)
8035           (setq message-options (delq the-cons message-options)))
8036       (and value
8037            (push (cons symbol value) message-options))))
8038   value)
8039
8040 (defun message-options-set-recipient ()
8041   (save-restriction
8042     (message-narrow-to-headers-or-head)
8043     (message-options-set 'message-sender
8044                          (mail-strip-quoted-names
8045                           (message-fetch-field "from")))
8046     (message-options-set 'message-recipients
8047                          (mail-strip-quoted-names
8048                           (let ((to (message-fetch-field "to"))
8049                                 (cc (message-fetch-field "cc"))
8050                                 (bcc (message-fetch-field "bcc")))
8051                             (concat
8052                              (or to "")
8053                              (if (and to cc) ", ")
8054                              (or cc "")
8055                              (if (and (or to cc) bcc) ", ")
8056                              (or bcc "")))))))
8057
8058 (defun message-hide-headers ()
8059   "Hide headers based on the `message-hidden-headers' variable."
8060   (let ((regexps (if (stringp message-hidden-headers)
8061                      (list message-hidden-headers)
8062                    message-hidden-headers))
8063         (inhibit-point-motion-hooks t)
8064         (after-change-functions nil)
8065         (end-of-headers (point-min)))
8066     (when regexps
8067       (save-excursion
8068         (save-restriction
8069           (message-narrow-to-headers)
8070           (goto-char (point-min))
8071           (while (not (eobp))
8072             (if (not (message-hide-header-p regexps))
8073                 (message-next-header)
8074               (let ((begin (point))
8075                     header header-len)
8076                 (message-next-header)
8077                 (setq header (buffer-substring begin (point))
8078                       header-len (- (point) begin))
8079                 (delete-region begin (point))
8080                 (goto-char end-of-headers)
8081                 (insert header)
8082                 (setq end-of-headers
8083                       (+ end-of-headers header-len))))))))
8084     (narrow-to-region end-of-headers (point-max))))
8085
8086 (defun message-hide-header-p (regexps)
8087   (let ((result nil)
8088         (reverse nil))
8089     (when (eq (car regexps) 'not)
8090       (setq reverse t)
8091       (pop regexps))
8092     (dolist (regexp regexps)
8093       (setq result (or result (looking-at regexp))))
8094     (if reverse
8095         (not result)
8096       result)))
8097
8098 (declare-function ecomplete-add-item "ecomplete" (type key text))
8099 (declare-function ecomplete-save "ecomplete" ())
8100
8101 (defun message-put-addresses-in-ecomplete ()
8102   (require 'ecomplete)
8103   (dolist (header '("to" "cc" "from" "reply-to"))
8104     (let ((value (message-field-value header)))
8105       (dolist (string (mail-header-parse-addresses value 'raw))
8106         (setq string
8107               (gnus-replace-in-string
8108                (gnus-replace-in-string string "^ +\\| +$" "") "\n" ""))
8109         (ecomplete-add-item 'mail (car (mail-header-parse-address string))
8110                             string))))
8111   (ecomplete-save))
8112
8113 (autoload 'ecomplete-display-matches "ecomplete")
8114
8115 (defun message-display-abbrev (&optional choose)
8116   "Display the next possible abbrev for the text before point."
8117   (interactive (list t))
8118   (when (and (memq (char-after (point-at-bol)) '(?C ?T ?\t ? ))
8119              (message-point-in-header-p)
8120              (save-excursion
8121                (beginning-of-line)
8122                (while (and (memq (char-after) '(?\t ? ))
8123                            (zerop (forward-line -1))))
8124                (looking-at "To:\\|Cc:")))
8125     (let* ((end (point))
8126            (start (save-excursion
8127                     (and (re-search-backward "[\n\t ]" nil t)
8128                          (1+ (point)))))
8129            (word (when start (buffer-substring start end)))
8130            (match (when (and word
8131                              (not (zerop (length word))))
8132                     (ecomplete-display-matches 'mail word choose))))
8133       (when (and choose match)
8134         (delete-region start end)
8135         (insert match)))))
8136
8137 ;; To send pre-formatted letters like the example below, you can use
8138 ;; `message-send-form-letter':
8139 ;; --8<---------------cut here---------------start------------->8---
8140 ;; To: alice@invalid.invalid
8141 ;; Subject: Verification of your contact information
8142 ;; From: Contact verification <admin@foo.invalid>
8143 ;; --text follows this line--
8144 ;; Hi Alice,
8145 ;; please verify that your contact information is still valid:
8146 ;; Alice A, A avenue 11, 1111 A town, Austria
8147 ;; ----------next form letter message follows this line----------
8148 ;; To: bob@invalid.invalid
8149 ;; Subject: Verification of your contact information
8150 ;; From: Contact verification <admin@foo.invalid>
8151 ;; --text follows this line--
8152 ;; Hi Bob,
8153 ;; please verify that your contact information is still valid:
8154 ;; Bob, B street 22, 22222 Be town, Belgium
8155 ;; ----------next form letter message follows this line----------
8156 ;; To: charlie@invalid.invalid
8157 ;; Subject: Verification of your contact information
8158 ;; From: Contact verification <admin@foo.invalid>
8159 ;; --text follows this line--
8160 ;; Hi Charlie,
8161 ;; please verify that your contact information is still valid:
8162 ;; Charlie Chaplin, C plaza 33, 33333 C town, Chile
8163 ;; --8<---------------cut here---------------end--------------->8---
8164
8165 ;; FIXME: What is the most common term (circular letter, form letter, serial
8166 ;; letter, standard letter) for such kind of letter?  See also
8167 ;; <http://en.wikipedia.org/wiki/Form_letter>
8168
8169 ;; FIXME: Maybe extent message-mode's font-lock support to recognize
8170 ;; `message-form-letter-separator', i.e. highlight each message like a single
8171 ;; message.
8172
8173 (defcustom message-form-letter-separator
8174   "\n----------next form letter message follows this line----------\n"
8175   "Separator for `message-send-form-letter'."
8176   ;; :group 'message-form-letter
8177   :group 'message-various
8178   :version "23.1" ;; No Gnus
8179   :type 'string)
8180
8181 (defcustom message-send-form-letter-delay 1
8182   "Delay in seconds when sending a message with `message-send-form-letter'.
8183 Only used when `message-send-form-letter' is called with non-nil
8184 argument `force'."
8185   ;; :group 'message-form-letter
8186   :group 'message-various
8187   :version "23.1" ;; No Gnus
8188   :type 'integer)
8189
8190 (defun message-send-form-letter (&optional force)
8191   "Sent all form letter messages from current buffer.
8192 Unless FORCE, prompt before sending.
8193
8194 The messages are separated by `message-form-letter-separator'.
8195 Header and body are separated by `mail-header-separator'."
8196   (interactive "P")
8197   (let ((sent 0) (skipped 0)
8198         start end text
8199         buff
8200         to done)
8201     (goto-char (point-min))
8202     (while (not done)
8203       (setq start (point)
8204             end (if (search-forward message-form-letter-separator nil t)
8205                     (- (point) (length message-form-letter-separator) -1)
8206                   (setq done t)
8207                   (point-max)))
8208       (setq text
8209             (buffer-substring-no-properties start end))
8210       (setq buff (generate-new-buffer "*mail - form letter*"))
8211       (with-current-buffer buff
8212         (insert text)
8213         (message-mode)
8214         (setq to (message-fetch-field "To"))
8215         (switch-to-buffer buff)
8216         (when force
8217           (sit-for message-send-form-letter-delay))
8218         (if (or force
8219                   (y-or-n-p (format "Send message to `%s'? " to)))
8220             (progn
8221               (setq sent (1+ sent))
8222               (message-send-and-exit))
8223           (message (format "Message to `%s' skipped." to))
8224           (setq skipped (1+ skipped)))
8225         (when (buffer-live-p buff)
8226           (kill-buffer buff))))
8227     (message "%s message(s) sent, %s skipped." sent skipped)))
8228
8229 (defun message-replace-header (header new-value &optional after force)
8230   "Remove HEADER and insert the NEW-VALUE.
8231 If AFTER, insert after this header.  If FORCE, insert new field
8232 even if NEW-VALUE is empty."
8233   ;; Similar to `nnheader-replace-header' but for message buffers.
8234   (save-excursion
8235     (save-restriction
8236       (message-narrow-to-headers)
8237       (message-remove-header header))
8238     (when (or force (> (length new-value) 0))
8239       (if after
8240           (message-position-on-field header after)
8241         (message-position-on-field header))
8242       (insert new-value))))
8243
8244 (defcustom message-recipients-without-full-name
8245   (list "ding@gnus.org"
8246         "bugs@gnus.org"
8247         "emacs-devel@gnu.org"
8248         "emacs-pretest-bug@gnu.org"
8249         "bug-gnu-emacs@gnu.org")
8250   "Mail addresses that have no full name.
8251 Used in `message-simplify-recipients'."
8252   ;; Maybe the addresses could be extracted from
8253   ;; `gnus-parameter-to-list-alist'?
8254   :type '(choice (const :tag "None" nil)
8255                  (repeat string))
8256   :version "23.1" ;; No Gnus
8257   :group 'message-headers)
8258
8259 (defun message-simplify-recipients ()
8260   (interactive)
8261   (dolist (hdr '("Cc" "To"))
8262     (message-replace-header
8263      hdr
8264      (mapconcat
8265       (lambda (addrcomp)
8266         (if (and message-recipients-without-full-name
8267                  (string-match
8268                   (regexp-opt message-recipients-without-full-name)
8269                   (cadr addrcomp)))
8270             (cadr addrcomp)
8271           (if (car addrcomp)
8272               (message-make-from (car addrcomp) (cadr addrcomp))
8273             (cadr addrcomp))))
8274       (when (message-fetch-field hdr)
8275         (mail-extract-address-components
8276          (message-fetch-field hdr) t))
8277       ", "))))
8278
8279 (when (featurep 'xemacs)
8280   (require 'messagexmas)
8281   (message-xmas-redefine))
8282
8283 (provide 'message)
8284
8285 (run-hooks 'message-load-hook)
8286
8287 ;; Local Variables:
8288 ;; coding: iso-8859-1
8289 ;; End:
8290
8291 ;;; message.el ends here