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