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