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