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