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