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