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