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