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