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