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