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