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