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