message.el (message-mode): Use message-mode-abbrev-table, with text-mode-abbrev-table...
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2
3 ;; Copyright (C) 1996-2013 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:\\|^X-Message-SMTP-Method:"
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 '(choice (const nil) 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   (set (make-local-variable 'message-reply-buffer) nil)
2987   (set (make-local-variable 'message-inserted-headers) nil)
2988   (set (make-local-variable 'message-send-actions) nil)
2989   (set (make-local-variable 'message-return-action) nil)
2990   (set (make-local-variable 'message-exit-actions) nil)
2991   (set (make-local-variable 'message-kill-actions) nil)
2992   (set (make-local-variable 'message-postpone-actions) nil)
2993   (set (make-local-variable 'message-draft-article) nil)
2994   (setq buffer-offer-save t)
2995   (set (make-local-variable 'facemenu-add-face-function)
2996        (lambda (face end)
2997          (let ((face-fun (cdr (assq face message-face-alist))))
2998            (if face-fun
2999                (funcall face-fun (point) end)
3000              (error "Face %s not configured for %s mode" face mode-name)))
3001          ""))
3002   (set (make-local-variable 'facemenu-remove-face-function) t)
3003   (set (make-local-variable 'message-reply-headers) nil)
3004   (make-local-variable 'message-newsreader)
3005   (make-local-variable 'message-mailer)
3006   (make-local-variable 'message-post-method)
3007   (set (make-local-variable 'message-sent-message-via) nil)
3008   (set (make-local-variable 'message-checksum) nil)
3009   (set (make-local-variable 'message-mime-part) 0)
3010   (message-setup-fill-variables)
3011   (when message-fill-column
3012     (setq fill-column message-fill-column)
3013     (turn-on-auto-fill))
3014   ;; Allow using comment commands to add/remove quoting.
3015   ;; (set (make-local-variable 'comment-start) message-yank-prefix)
3016   (when message-yank-prefix
3017     (set (make-local-variable 'comment-start) message-yank-prefix)
3018     (set (make-local-variable 'comment-start-skip)
3019          (concat "^" (regexp-quote message-yank-prefix) "[ \t]*")))
3020   (if (featurep 'xemacs)
3021       (message-setup-toolbar)
3022     (set (make-local-variable 'font-lock-defaults)
3023          '(message-font-lock-keywords t))
3024     (if (boundp 'tool-bar-map)
3025         (set (make-local-variable 'tool-bar-map) (message-make-tool-bar))))
3026   (easy-menu-add message-mode-menu message-mode-map)
3027   (easy-menu-add message-mode-field-menu message-mode-map)
3028   (gnus-make-local-hook 'after-change-functions)
3029   ;; Mmmm... Forbidden properties...
3030   (add-hook 'after-change-functions 'message-strip-forbidden-properties
3031             nil 'local)
3032   ;; Allow mail alias things.
3033   (cond
3034    ((message-mail-alias-type-p 'abbrev)
3035     (if (fboundp 'mail-abbrevs-setup)
3036         (mail-abbrevs-setup)
3037       (if (fboundp 'mail-aliases-setup) ; warning avoidance
3038           (mail-aliases-setup))))
3039    ((message-mail-alias-type-p 'ecomplete)
3040     (ecomplete-setup)))
3041   (add-hook 'completion-at-point-functions 'message-completion-function nil t)
3042   (unless buffer-file-name
3043     (message-set-auto-save-file-name))
3044   (unless (buffer-base-buffer)
3045     ;; Don't enable multibyte on an indirect buffer.  Maybe enabling
3046     ;; multibyte is not necessary at all. -- zsh
3047     (mm-enable-multibyte))
3048   (set (make-local-variable 'indent-tabs-mode) nil) ;No tabs for indentation.
3049   (mml-mode))
3050
3051 (defun message-setup-fill-variables ()
3052   "Setup message fill variables."
3053   (set (make-local-variable 'fill-paragraph-function)
3054        'message-fill-paragraph)
3055   (make-local-variable 'paragraph-separate)
3056   (make-local-variable 'paragraph-start)
3057   (make-local-variable 'adaptive-fill-regexp)
3058   (unless (boundp 'adaptive-fill-first-line-regexp)
3059     (setq adaptive-fill-first-line-regexp nil))
3060   (make-local-variable 'adaptive-fill-first-line-regexp)
3061   (let ((quote-prefix-regexp
3062          ;; User should change message-cite-prefix-regexp if
3063          ;; message-yank-prefix is set to an abnormal value.
3064          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
3065     (setq paragraph-start
3066           (concat
3067            (regexp-quote mail-header-separator) "$\\|"
3068            "[ \t]*$\\|"                 ; blank lines
3069            "-- $\\|"                    ; signature delimiter
3070            "---+$\\|"              ; delimiters for forwarded messages
3071            page-delimiter "$\\|"        ; spoiler warnings
3072            ".*wrote:$\\|"               ; attribution lines
3073            quote-prefix-regexp "$\\|"   ; empty lines in quoted text
3074                                         ; mml tags
3075            "<#!*/?\\(multipart\\|part\\|external\\|mml\\|secure\\)"))
3076     (setq paragraph-separate paragraph-start)
3077     (setq adaptive-fill-regexp
3078           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
3079     (setq adaptive-fill-first-line-regexp
3080           (concat quote-prefix-regexp "\\|"
3081                   adaptive-fill-first-line-regexp)))
3082   (make-local-variable 'auto-fill-inhibit-regexp)
3083   ;;(setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
3084   (setq auto-fill-inhibit-regexp nil)
3085   (make-local-variable 'normal-auto-fill-function)
3086   (setq normal-auto-fill-function 'message-do-auto-fill)
3087   ;; KLUDGE: auto fill might already be turned on in `text-mode-hook'.
3088   ;; In that case, ensure that it uses the right function.  The real
3089   ;; solution would be not to use `define-derived-mode', and run
3090   ;; `text-mode-hook' ourself at the end of the mode.
3091   ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-19.
3092   ;; This kludge is unneeded in Emacs>=21 since define-derived-mode is
3093   ;; now careful to run parent hooks after the body.  --Stef
3094   (when auto-fill-function
3095     (setq auto-fill-function normal-auto-fill-function)))
3096
3097 \f
3098
3099 ;;;
3100 ;;; Message mode commands
3101 ;;;
3102
3103 ;;; Movement commands
3104
3105 (defun message-goto-to ()
3106   "Move point to the To header."
3107   (interactive)
3108   (push-mark)
3109   (message-position-on-field "To"))
3110
3111 (defun message-goto-from ()
3112   "Move point to the From header."
3113   (interactive)
3114   (push-mark)
3115   (message-position-on-field "From"))
3116
3117 (defun message-goto-subject ()
3118   "Move point to the Subject header."
3119   (interactive)
3120   (push-mark)
3121   (message-position-on-field "Subject"))
3122
3123 (defun message-goto-cc ()
3124   "Move point to the Cc header."
3125   (interactive)
3126   (push-mark)
3127   (message-position-on-field "Cc" "To"))
3128
3129 (defun message-goto-bcc ()
3130   "Move point to the Bcc  header."
3131   (interactive)
3132   (push-mark)
3133   (message-position-on-field "Bcc" "Cc" "To"))
3134
3135 (defun message-goto-fcc ()
3136   "Move point to the Fcc header."
3137   (interactive)
3138   (push-mark)
3139   (message-position-on-field "Fcc" "To" "Newsgroups"))
3140
3141 (defun message-goto-reply-to ()
3142   "Move point to the Reply-To header."
3143   (interactive)
3144   (push-mark)
3145   (message-position-on-field "Reply-To" "Subject"))
3146
3147 (defun message-goto-newsgroups ()
3148   "Move point to the Newsgroups header."
3149   (interactive)
3150   (push-mark)
3151   (message-position-on-field "Newsgroups"))
3152
3153 (defun message-goto-distribution ()
3154   "Move point to the Distribution header."
3155   (interactive)
3156   (push-mark)
3157   (message-position-on-field "Distribution"))
3158
3159 (defun message-goto-followup-to ()
3160   "Move point to the Followup-To header."
3161   (interactive)
3162   (push-mark)
3163   (message-position-on-field "Followup-To" "Newsgroups"))
3164
3165 (defun message-goto-mail-followup-to ()
3166   "Move point to the Mail-Followup-To header."
3167   (interactive)
3168   (push-mark)
3169   (message-position-on-field "Mail-Followup-To" "To"))
3170
3171 (defun message-goto-keywords ()
3172   "Move point to the Keywords header."
3173   (interactive)
3174   (push-mark)
3175   (message-position-on-field "Keywords" "Subject"))
3176
3177 (defun message-goto-summary ()
3178   "Move point to the Summary header."
3179   (interactive)
3180   (push-mark)
3181   (message-position-on-field "Summary" "Subject"))
3182
3183 (defun message-goto-body ()
3184   "Move point to the beginning of the message body."
3185   (interactive)
3186   (when (and (gmm-called-interactively-p 'any)
3187              (looking-at "[ \t]*\n"))
3188     (expand-abbrev))
3189   (push-mark)
3190   (goto-char (point-min))
3191   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
3192       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)))
3193
3194 (defun message-in-body-p ()
3195   "Return t if point is in the message body."
3196   (>= (point)
3197       (save-excursion
3198         (goto-char (point-min))
3199         (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
3200             (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t))
3201         (point))))
3202
3203 (defun message-goto-eoh ()
3204   "Move point to the end of the headers."
3205   (interactive)
3206   (message-goto-body)
3207   (forward-line -1))
3208
3209 (defun message-goto-signature ()
3210   "Move point to the beginning of the message signature.
3211 If there is no signature in the article, go to the end and
3212 return nil."
3213   (interactive)
3214   (push-mark)
3215   (goto-char (point-min))
3216   (if (re-search-forward message-signature-separator nil t)
3217       (forward-line 1)
3218     (goto-char (point-max))
3219     nil))
3220
3221 (defun message-generate-unsubscribed-mail-followup-to (&optional include-cc)
3222   "Insert a reasonable MFT header in a post to an unsubscribed list.
3223 When making original posts to a mailing list you are not subscribed to,
3224 you have to type in a MFT header by hand.  The contents, usually, are
3225 the addresses of the list and your own address.  This function inserts
3226 such a header automatically.  It fetches the contents of the To: header
3227 in the current mail buffer, and appends the current `user-mail-address'.
3228
3229 If the optional argument INCLUDE-CC is non-nil, the addresses in the
3230 Cc: header are also put into the MFT."
3231
3232   (interactive "P")
3233   (let* (cc tos)
3234     (save-restriction
3235       (message-narrow-to-headers)
3236       (message-remove-header "Mail-Followup-To")
3237       (setq cc (and include-cc (message-fetch-field "Cc")))
3238       (setq tos (if cc
3239                     (concat (message-fetch-field "To") "," cc)
3240                   (message-fetch-field "To"))))
3241     (message-goto-mail-followup-to)
3242     (insert (concat tos ", " user-mail-address))))
3243
3244 \f
3245
3246 (defun message-insert-to (&optional force)
3247   "Insert a To header that points to the author of the article being replied to.
3248 If the original author requested not to be sent mail, don't insert unless the
3249 prefix FORCE is given."
3250   (interactive "P")
3251   (let* ((mct (message-fetch-reply-field "mail-copies-to"))
3252          (dont (and mct (or (equal (downcase mct) "never")
3253                             (equal (downcase mct) "nobody"))))
3254          (to (or (message-fetch-reply-field "mail-reply-to")
3255                  (message-fetch-reply-field "reply-to")
3256                  (message-fetch-reply-field "from"))))
3257     (when (and dont to)
3258       (message
3259        (if force
3260            "Ignoring the user request not to have copies sent via mail"
3261          "Complying with the user request not to have copies sent via mail")))
3262     (when (and force (not to))
3263       (error "No mail address in the article"))
3264     (when (and to (or force (not dont)))
3265       (message-carefully-insert-headers (list (cons 'To to))))))
3266
3267 (defun message-insert-wide-reply ()
3268   "Insert To and Cc headers as if you were doing a wide reply."
3269   (interactive)
3270   (let ((headers (message-with-reply-buffer
3271                    (message-get-reply-headers t))))
3272     (message-carefully-insert-headers headers)))
3273
3274 (defcustom message-header-synonyms
3275   '((To Cc Bcc)
3276     (Original-To))
3277   "List of lists of header synonyms.
3278 E.g., if this list contains a member list with elements `Cc' and `To',
3279 then `message-carefully-insert-headers' will not insert a `To' header
3280 when the message is already `Cc'ed to the recipient."
3281   :version "22.1"
3282   :group 'message-headers
3283   :link '(custom-manual "(message)Message Headers")
3284   :type '(repeat sexp))
3285
3286 (defun message-carefully-insert-headers (headers)
3287   "Insert the HEADERS, an alist, into the message buffer.
3288 Does not insert the headers when they are already present there
3289 or in the synonym headers, defined by `message-header-synonyms'."
3290   ;; FIXME: Should compare only the address and not the full name.  Comparison
3291   ;; should be done case-folded (and with `string=' rather than
3292   ;; `string-match').
3293   ;; (mail-strip-quoted-names "Foo Bar <foo@bar>, bla@fasel (Bla Fasel)")
3294   (dolist (header headers)
3295     (let* ((header-name (symbol-name (car header)))
3296            (new-header (cdr header))
3297            (synonyms (loop for synonym in message-header-synonyms
3298                            when (memq (car header) synonym) return synonym))
3299            (old-header
3300             (loop for synonym in synonyms
3301                   for old-header = (mail-fetch-field (symbol-name synonym))
3302                   when (and old-header (string-match new-header old-header))
3303                   return synonym)))
3304       (if old-header
3305           (message "already have `%s' in `%s'" new-header old-header)
3306         (when (and (message-position-on-field header-name)
3307                    (setq old-header (mail-fetch-field header-name))
3308                    (not (string-match "\\` *\\'" old-header)))
3309           (insert ", "))
3310         (insert new-header)))))
3311
3312 (defun message-widen-reply ()
3313   "Widen the reply to include maximum recipients."
3314   (interactive)
3315   (let ((follow-to
3316          (and (bufferp message-reply-buffer)
3317               (buffer-name message-reply-buffer)
3318               (with-current-buffer message-reply-buffer
3319                 (message-get-reply-headers t)))))
3320     (save-excursion
3321       (save-restriction
3322         (message-narrow-to-headers)
3323         (dolist (elem follow-to)
3324           (message-remove-header (symbol-name (car elem)))
3325           (goto-char (point-min))
3326           (insert (symbol-name (car elem)) ": "
3327                   (cdr elem) "\n"))))))
3328
3329 (defun message-insert-newsgroups ()
3330   "Insert the Newsgroups header from the article being replied to."
3331   (interactive)
3332   (let ((old-newsgroups (mail-fetch-field "newsgroups"))
3333         (new-newsgroups (message-fetch-reply-field "newsgroups"))
3334         (first t)
3335         insert-newsgroups)
3336     (message-position-on-field "Newsgroups")
3337     (cond
3338      ((not new-newsgroups)
3339       (error "No Newsgroups to insert"))
3340      ((not old-newsgroups)
3341       (insert new-newsgroups))
3342      (t
3343       (setq new-newsgroups (split-string new-newsgroups "[, ]+")
3344             old-newsgroups (split-string old-newsgroups "[, ]+"))
3345       (dolist (group new-newsgroups)
3346         (unless (member group old-newsgroups)
3347           (push group insert-newsgroups)))
3348       (if (null insert-newsgroups)
3349           (error "Newgroup%s already in the header"
3350                  (if (> (length new-newsgroups) 1)
3351                      "s" ""))
3352         (when old-newsgroups
3353           (setq first nil))
3354         (dolist (group insert-newsgroups)
3355           (unless first
3356             (insert ","))
3357           (setq first nil)
3358           (insert group)))))))
3359
3360 \f
3361
3362 ;;; Various commands
3363
3364 (defun message-delete-not-region (beg end)
3365   "Delete everything in the body of the current message outside of the region."
3366   (interactive "r")
3367   (let (citeprefix)
3368     (save-excursion
3369       (goto-char beg)
3370       ;; snarf citation prefix, if appropriate
3371       (unless (eq (point) (progn (beginning-of-line) (point)))
3372         (when (looking-at message-cite-prefix-regexp)
3373           (setq citeprefix (match-string 0))))
3374       (goto-char end)
3375       (delete-region (point) (if (not (message-goto-signature))
3376                                  (point)
3377                                (forward-line -2)
3378                                (point)))
3379       (insert "\n")
3380       (goto-char beg)
3381       (delete-region beg (progn (message-goto-body)
3382                                 (forward-line 2)
3383                                 (point)))
3384       (when citeprefix
3385         (insert citeprefix))))
3386   (when (message-goto-signature)
3387     (forward-line -2)))
3388
3389 (defun message-kill-to-signature (&optional arg)
3390   "Kill all text up to the signature.
3391 If a numeric argument or prefix arg is given, leave that number
3392 of lines before the signature intact."
3393   (interactive "P")
3394   (save-excursion
3395     (save-restriction
3396       (let ((point (point)))
3397         (narrow-to-region point (point-max))
3398         (message-goto-signature)
3399         (unless (eobp)
3400           (if (and arg (numberp arg))
3401               (forward-line (- -1 arg))
3402             (end-of-line -1)))
3403         (unless (= point (point))
3404           (kill-region point (point))
3405           (unless (bolp)
3406             (insert "\n")))))))
3407
3408 (defun message-newline-and-reformat (&optional arg not-break)
3409   "Insert four newlines, and then reformat if inside quoted text.
3410 Prefix arg means justify as well."
3411   (interactive (list (if current-prefix-arg 'full)))
3412   (let (quoted point beg end leading-space bolp fill-paragraph-function)
3413     (setq point (point))
3414     (beginning-of-line)
3415     (setq beg (point))
3416     (setq bolp (= beg point))
3417     ;; Find first line of the paragraph.
3418     (if not-break
3419         (while (and (not (eobp))
3420                     (not (looking-at message-cite-prefix-regexp))
3421                     (looking-at paragraph-start))
3422           (forward-line 1)))
3423     ;; Find the prefix
3424     (when (looking-at message-cite-prefix-regexp)
3425       (setq quoted (match-string 0))
3426       (goto-char (match-end 0))
3427       (looking-at "[ \t]*")
3428       (setq leading-space (match-string 0)))
3429     (if (and quoted
3430              (not not-break)
3431              (not bolp)
3432              (< (- point beg) (length quoted)))
3433         ;; break inside the cite prefix.
3434         (setq quoted nil
3435               end nil))
3436     (if quoted
3437         (progn
3438           (forward-line 1)
3439           (while (and (not (eobp))
3440                       (not (looking-at paragraph-separate))
3441                       (looking-at message-cite-prefix-regexp)
3442                       (equal quoted (match-string 0)))
3443             (goto-char (match-end 0))
3444             (looking-at "[ \t]*")
3445             (if (> (length leading-space) (length (match-string 0)))
3446                 (setq leading-space (match-string 0)))
3447             (forward-line 1))
3448           (setq end (point))
3449           (goto-char beg)
3450           (while (and (if (bobp) nil (forward-line -1) t)
3451                       (not (looking-at paragraph-start))
3452                       (looking-at message-cite-prefix-regexp)
3453                       (equal quoted (match-string 0)))
3454             (setq beg (point))
3455             (goto-char (match-end 0))
3456             (looking-at "[ \t]*")
3457             (if (> (length leading-space) (length (match-string 0)))
3458                 (setq leading-space (match-string 0)))))
3459       (while (and (not (eobp))
3460                   (not (looking-at paragraph-separate))
3461                   (not (looking-at message-cite-prefix-regexp)))
3462         (forward-line 1))
3463       (setq end (point))
3464       (goto-char beg)
3465       (while (and (if (bobp) nil (forward-line -1) t)
3466                   (not (looking-at paragraph-start))
3467                   (not (looking-at message-cite-prefix-regexp)))
3468         (setq beg (point))))
3469     (goto-char point)
3470     (save-restriction
3471       (narrow-to-region beg end)
3472       (if not-break
3473           (setq point nil)
3474         (if bolp
3475             (newline)
3476           (newline)
3477           (newline))
3478         (setq point (point))
3479         ;; (newline 2) doesn't mark both newline's as hard, so call
3480         ;; newline twice. -jas
3481         (newline)
3482         (newline)
3483         (delete-region (point) (re-search-forward "[ \t]*"))
3484         (when (and quoted (not bolp))
3485           (insert quoted leading-space)))
3486       (undo-boundary)
3487       (if quoted
3488           (let* ((adaptive-fill-regexp
3489                   (regexp-quote (concat quoted leading-space)))
3490                  (adaptive-fill-first-line-regexp
3491                   adaptive-fill-regexp ))
3492             (fill-paragraph arg))
3493         (fill-paragraph arg))
3494       (if point (goto-char point)))))
3495
3496 (defun message-fill-paragraph (&optional arg)
3497   "Message specific function to fill a paragraph.
3498 This function is used as the value of `fill-paragraph-function' in
3499 Message buffers and is not meant to be called directly."
3500   (interactive (list (if current-prefix-arg 'full)))
3501   (if (if (boundp 'filladapt-mode) filladapt-mode)
3502       nil
3503     (if (message-point-in-header-p)
3504         (message-fill-field)
3505       (message-newline-and-reformat arg t))
3506     t))
3507
3508 (defun message-point-in-header-p ()
3509   "Return t if point is in the header."
3510   (save-excursion
3511     (and
3512      (not
3513       (re-search-backward
3514        (concat "^" (regexp-quote mail-header-separator) "\n") nil t))
3515      (re-search-forward
3516       (concat "^" (regexp-quote mail-header-separator) "\n") nil t))))
3517
3518 (defun message-do-auto-fill ()
3519   "Like `do-auto-fill', but don't fill in message header."
3520   (unless (message-point-in-header-p)
3521     (do-auto-fill)))
3522
3523 (defun message-insert-signature (&optional force)
3524   "Insert a signature.  See documentation for variable `message-signature'."
3525   (interactive (list 0))
3526   (let* ((signature
3527           (cond
3528            ((and (null message-signature)
3529                  (eq force 0))
3530             (save-excursion
3531               (goto-char (point-max))
3532               (not (re-search-backward message-signature-separator nil t))))
3533            ((and (null message-signature)
3534                  force)
3535             t)
3536            ((functionp message-signature)
3537             (funcall message-signature))
3538            ((listp message-signature)
3539             (eval message-signature))
3540            (t message-signature)))
3541          signature-file)
3542     (setq signature
3543           (cond ((stringp signature)
3544                  signature)
3545                 ((and (eq t signature) message-signature-file)
3546                  (setq signature-file
3547                        (if (and message-signature-directory
3548                                 ;; don't actually use the signature directory
3549                                 ;; if message-signature-file contains a path.
3550                                 (not (file-name-directory
3551                                       message-signature-file)))
3552                            (expand-file-name message-signature-file
3553                                              message-signature-directory)
3554                          message-signature-file))
3555                  (file-exists-p signature-file))))
3556     (when signature
3557       (goto-char (point-max))
3558       ;; Insert the signature.
3559       (unless (bolp)
3560         (insert "\n"))
3561       (when message-signature-insert-empty-line
3562         (insert "\n"))
3563       (insert "-- \n")
3564       (if (eq signature t)
3565           (insert-file-contents signature-file)
3566         (insert signature))
3567       (goto-char (point-max))
3568       (or (bolp) (insert "\n")))))
3569
3570 (defun message-insert-importance-high ()
3571   "Insert header to mark message as important."
3572   (interactive)
3573   (save-excursion
3574     (save-restriction
3575       (message-narrow-to-headers)
3576       (message-remove-header "Importance"))
3577     (message-goto-eoh)
3578     (insert "Importance: high\n")))
3579
3580 (defun message-insert-importance-low ()
3581   "Insert header to mark message as unimportant."
3582   (interactive)
3583   (save-excursion
3584     (save-restriction
3585       (message-narrow-to-headers)
3586       (message-remove-header "Importance"))
3587     (message-goto-eoh)
3588     (insert "Importance: low\n")))
3589
3590 (defun message-insert-or-toggle-importance ()
3591   "Insert a \"Importance: high\" header, or cycle through the header values.
3592 The three allowed values according to RFC 1327 are `high', `normal'
3593 and `low'."
3594   (interactive)
3595   (save-excursion
3596     (let ((new "high")
3597           cur)
3598       (save-restriction
3599         (message-narrow-to-headers)
3600         (when (setq cur (message-fetch-field "Importance"))
3601           (message-remove-header "Importance")
3602           (setq new (cond ((string= cur "high")
3603                            "low")
3604                           ((string= cur "low")
3605                            "normal")
3606                           (t
3607                            "high")))))
3608       (message-goto-eoh)
3609       (insert (format "Importance: %s\n" new)))))
3610
3611 (defun message-insert-disposition-notification-to ()
3612   "Request a disposition notification (return receipt) to this message.
3613 Note that this should not be used in newsgroups."
3614   (interactive)
3615   (save-excursion
3616     (save-restriction
3617       (message-narrow-to-headers)
3618       (message-remove-header "Disposition-Notification-To"))
3619     (message-goto-eoh)
3620     (insert (format "Disposition-Notification-To: %s\n"
3621                     (or (message-field-value "Reply-to")
3622                         (message-field-value "From")
3623                         (message-make-from))))))
3624
3625 (defun message-elide-region (b e)
3626   "Elide the text in the region.
3627 An ellipsis (from `message-elide-ellipsis') will be inserted where the
3628 text was killed."
3629   (interactive "r")
3630   (let ((lines (count-lines b e))
3631         (chars (- e b)))
3632     (kill-region b e)
3633     (insert (format-spec message-elide-ellipsis
3634                          `((?l . ,lines)
3635                            (?c . ,chars))))))
3636
3637 (defvar message-caesar-translation-table nil)
3638
3639 (defun message-caesar-region (b e &optional n)
3640   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
3641   (interactive
3642    (list
3643     (min (point) (or (mark t) (point)))
3644     (max (point) (or (mark t) (point)))
3645     (when current-prefix-arg
3646       (prefix-numeric-value current-prefix-arg))))
3647
3648   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
3649   (unless (or (zerop n)                 ; no action needed for a rot of 0
3650               (= b e))                  ; no region to rotate
3651     ;; We build the table, if necessary.
3652     (when (or (not message-caesar-translation-table)
3653               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
3654       (setq message-caesar-translation-table
3655             (message-make-caesar-translation-table n)))
3656     (translate-region b e message-caesar-translation-table)))
3657
3658 (defun message-make-caesar-translation-table (n)
3659   "Create a rot table with offset N."
3660   (let ((i -1)
3661         (table (make-string 256 0)))
3662     (while (< (incf i) 256)
3663       (aset table i i))
3664     (concat
3665      (substring table 0 ?A)
3666      (substring table (+ ?A n) (+ ?A n (- 26 n)))
3667      (substring table ?A (+ ?A n))
3668      (substring table (+ ?A 26) ?a)
3669      (substring table (+ ?a n) (+ ?a n (- 26 n)))
3670      (substring table ?a (+ ?a n))
3671      (substring table (+ ?a 26) 255))))
3672
3673 (defun message-caesar-buffer-body (&optional rotnum wide)
3674   "Caesar rotate all letters in the current buffer by 13 places.
3675 Used to encode/decode possibly offensive messages (commonly in rec.humor).
3676 With prefix arg, specifies the number of places to rotate each letter forward.
3677 Mail and USENET news headers are not rotated unless WIDE is non-nil."
3678   (interactive (if current-prefix-arg
3679                    (list (prefix-numeric-value current-prefix-arg))
3680                  (list nil)))
3681   (save-excursion
3682     (save-restriction
3683       (when (and (not wide) (message-goto-body))
3684         (narrow-to-region (point) (point-max)))
3685       (message-caesar-region (point-min) (point-max) rotnum))))
3686
3687 (defun message-pipe-buffer-body (program)
3688   "Pipe the message body in the current buffer through PROGRAM."
3689   (save-excursion
3690     (save-restriction
3691       (when (message-goto-body)
3692         (narrow-to-region (point) (point-max)))
3693       (shell-command-on-region
3694        (point-min) (point-max) program nil t))))
3695
3696 (defun message-rename-buffer (&optional enter-string)
3697   "Rename the *message* buffer to \"*message* RECIPIENT\".
3698 If the function is run with a prefix, it will ask for a new buffer
3699 name, rather than giving an automatic name."
3700   (interactive "Pbuffer name: ")
3701   (save-excursion
3702     (save-restriction
3703       (goto-char (point-min))
3704       (narrow-to-region (point)
3705                         (search-forward mail-header-separator nil 'end))
3706       (let* ((mail-to (or
3707                        (if (message-news-p) (message-fetch-field "Newsgroups")
3708                          (message-fetch-field "To"))
3709                        ""))
3710              (mail-trimmed-to
3711               (if (string-match "," mail-to)
3712                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
3713                 mail-to))
3714              (name-default (concat "*message* " mail-trimmed-to))
3715              (name (if enter-string
3716                        (read-string "New buffer name: " name-default)
3717                      name-default)))
3718         (rename-buffer name t)))))
3719
3720 (defun message-fill-yanked-message (&optional justifyp)
3721   "Fill the paragraphs of a message yanked into this one.
3722 Numeric argument means justify as well."
3723   (interactive "P")
3724   (save-excursion
3725     (goto-char (point-min))
3726     (search-forward (concat "\n" mail-header-separator "\n") nil t)
3727     (let ((fill-prefix message-yank-prefix))
3728       (fill-individual-paragraphs (point) (point-max) justifyp))))
3729
3730 (defun message-indent-citation (&optional start end yank-only)
3731   "Modify text just inserted from a message to be cited.
3732 The inserted text should be the region.
3733 When this function returns, the region is again around the modified text.
3734
3735 Normally, indent each nonblank line `message-indentation-spaces' spaces.
3736 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
3737   (unless start (setq start (point)))
3738   (unless yank-only
3739     ;; Remove unwanted headers.
3740     (when message-ignored-cited-headers
3741       (let (all-removed)
3742         (save-restriction
3743           (narrow-to-region
3744            (goto-char start)
3745            (if (search-forward "\n\n" nil t)
3746                (1- (point))
3747              (point)))
3748           (message-remove-header message-ignored-cited-headers t)
3749           (when (= (point-min) (point-max))
3750             (setq all-removed t))
3751           (goto-char (point-max)))
3752         (if all-removed
3753             (goto-char start)
3754           (forward-line 1))))
3755     ;; Delete blank lines at the start of the buffer.
3756     (while (and (point-min)
3757                 (eolp)
3758                 (not (eobp)))
3759       (message-delete-line))
3760     ;; Delete blank lines at the end of the buffer.
3761     (goto-char (point-max))
3762     (unless (eq (preceding-char) ?\n)
3763       (insert "\n"))
3764     (while (and (zerop (forward-line -1))
3765                 (looking-at "$"))
3766       (message-delete-line)))
3767   ;; Do the indentation.
3768   (if (null message-yank-prefix)
3769       (indent-rigidly start (or end (mark t)) message-indentation-spaces)
3770     (save-excursion
3771       (goto-char start)
3772       (while (< (point) (or end (mark t)))
3773         (cond ((looking-at ">")
3774                (insert message-yank-cited-prefix))
3775               ((looking-at "^$")
3776                (insert message-yank-empty-prefix))
3777               (t
3778                (insert message-yank-prefix)))
3779         (forward-line 1))))
3780   (goto-char start))
3781
3782 (defun message-remove-blank-cited-lines (&optional remove)
3783   "Remove cited lines containing only blanks.
3784 If REMOVE is non-nil, remove newlines, too.
3785
3786 To use this automatically, you may add this function to
3787 `gnus-message-setup-hook'."
3788   (interactive "P")
3789   (let ((citexp
3790          (concat
3791           "^\\("
3792           (when (boundp 'message-yank-cited-prefix)
3793             (concat message-yank-cited-prefix "\\|"))
3794           message-yank-prefix
3795           "\\)+ *\n"
3796           )))
3797     (gnus-message 8 "removing `%s'" citexp)
3798     (save-excursion
3799       (message-goto-body)
3800       (while (re-search-forward citexp nil t)
3801         (replace-match (if remove "" "\n"))))))
3802
3803 (defun message--yank-original-internal (arg)
3804   (let ((modified (buffer-modified-p))
3805         body-text)
3806         (when (and message-reply-buffer
3807                    message-cite-function)
3808           (when (equal message-cite-reply-position 'above)
3809             (save-excursion
3810               (setq body-text
3811                     (buffer-substring (message-goto-body)
3812                                       (point-max)))
3813               (delete-region (message-goto-body) (point-max))))
3814           (if (bufferp message-reply-buffer)
3815               (delete-windows-on message-reply-buffer t))
3816           (push-mark (save-excursion
3817                        (cond
3818                         ((bufferp message-reply-buffer)
3819                          (insert-buffer-substring message-reply-buffer))
3820                         ((and (consp message-reply-buffer)
3821                               (functionp (car message-reply-buffer)))
3822                          (apply (car message-reply-buffer)
3823                                 (cdr message-reply-buffer))))
3824                        (unless (bolp)
3825                          (insert ?\n))
3826                        (point)))
3827           (unless arg
3828             (funcall message-cite-function)
3829             (unless (eq (char-before (mark t)) ?\n)
3830               (let ((pt (point)))
3831                 (goto-char (mark t))
3832                 (insert-before-markers ?\n)
3833                 (goto-char pt))))
3834           (case message-cite-reply-position
3835             (above
3836              (message-goto-body)
3837              (insert body-text)
3838              (insert (if (bolp) "\n" "\n\n"))
3839              (message-goto-body))
3840             (below
3841              (message-goto-signature)))
3842           ;; Add a `message-setup-very-last-hook' here?
3843           ;; Add `gnus-article-highlight-citation' here?
3844           (unless modified
3845         (setq message-checksum (message-checksum))))))
3846
3847 (defun message-yank-original (&optional arg)
3848   "Insert the message being replied to, if any.
3849 Puts point before the text and mark after.
3850 Normally indents each nonblank line ARG spaces (default 3).  However,
3851 if `message-yank-prefix' is non-nil, insert that prefix on each line.
3852
3853 This function uses `message-cite-function' to do the actual citing.
3854
3855 Just \\[universal-argument] as argument means don't indent, insert no
3856 prefix, and don't delete any headers."
3857   (interactive "P")
3858   ;; eval the let forms contained in message-cite-style
3859   (eval
3860    `(let ,(if (symbolp message-cite-style)
3861               (symbol-value message-cite-style)
3862             message-cite-style)
3863       (message--yank-original-internal ',arg))))
3864
3865 (defun message-yank-buffer (buffer)
3866   "Insert BUFFER into the current buffer and quote it."
3867   (interactive "bYank buffer: ")
3868   (let ((message-reply-buffer (get-buffer buffer)))
3869     (save-window-excursion
3870       (message-yank-original))))
3871
3872 (defun message-buffers ()
3873   "Return a list of active message buffers."
3874   (let (buffers)
3875     (save-current-buffer
3876       (dolist (buffer (buffer-list t))
3877         (set-buffer buffer)
3878         (when (and (derived-mode-p 'message-mode)
3879                    (null message-sent-message-via))
3880           (push (buffer-name buffer) buffers))))
3881     (nreverse buffers)))
3882
3883 (defun message-cite-original-1 (strip-signature)
3884   "Cite an original message.
3885 If STRIP-SIGNATURE is non-nil, strips off the signature from the
3886 original message.
3887
3888 This function uses `mail-citation-hook' if that is non-nil."
3889   (if (and (boundp 'mail-citation-hook)
3890            mail-citation-hook)
3891       (run-hooks 'mail-citation-hook)
3892     (let* ((start (point))
3893            (end (mark t))
3894            (x-no-archive nil)
3895            (functions
3896             (when message-indent-citation-function
3897               (if (listp message-indent-citation-function)
3898                   message-indent-citation-function
3899                 (list message-indent-citation-function))))
3900            ;; This function may be called by `gnus-summary-yank-message' and
3901            ;; may insert a different article from the original.  So, we will
3902            ;; modify the value of `message-reply-headers' with that article.
3903            (message-reply-headers
3904             (save-restriction
3905               (narrow-to-region start end)
3906               (message-narrow-to-head-1)
3907               (setq x-no-archive (message-fetch-field "x-no-archive"))
3908               (vector 0
3909                       (or (message-fetch-field "subject") "none")
3910                       (or (message-fetch-field "from") "nobody")
3911                       (message-fetch-field "date")
3912                       (message-fetch-field "message-id" t)
3913                       (message-fetch-field "references")
3914                       0 0 ""))))
3915       (mml-quote-region start end)
3916       (when strip-signature
3917         ;; Allow undoing.
3918         (undo-boundary)
3919         (goto-char end)
3920         (when (re-search-backward message-signature-separator start t)
3921           ;; Also peel off any blank lines before the signature.
3922           (forward-line -1)
3923           (while (looking-at "^[ \t]*$")
3924             (forward-line -1))
3925           (forward-line 1)
3926           (delete-region (point) end)
3927           (unless (search-backward "\n\n" start t)
3928             ;; Insert a blank line if it is peeled off.
3929             (insert "\n"))))
3930       (goto-char start)
3931       (mapc 'funcall functions)
3932       (when message-citation-line-function
3933         (unless (bolp)
3934           (insert "\n"))
3935         (funcall message-citation-line-function))
3936       (when (and x-no-archive
3937                  (not message-cite-articles-with-x-no-archive)
3938                  (string-match "yes" x-no-archive))
3939         (undo-boundary)
3940         (delete-region (point) (mark t))
3941         (insert "> [Quoted text removed due to X-No-Archive]\n")
3942         (push-mark)
3943         (forward-line -1)))))
3944
3945 (defun message-cite-original ()
3946   "Cite function in the standard Message manner."
3947   (message-cite-original-1 nil))
3948
3949 (defvar gnus-extract-address-components)
3950
3951 (autoload 'format-spec "format-spec")
3952
3953 (defun message-insert-formatted-citation-line (&optional from date)
3954   "Function that inserts a formatted citation line.
3955
3956 See `message-citation-line-format'."
3957   ;; The optional args are for testing/debugging.  They will disappear later.
3958   ;; Example:
3959   ;; (with-temp-buffer
3960   ;;   (message-insert-formatted-citation-line
3961   ;;    "John Doe <john.doe@example.invalid>"
3962   ;;    (current-time))
3963   ;;   (buffer-string))
3964   (when (or message-reply-headers (and from date))
3965     (unless from
3966       (setq from (mail-header-from message-reply-headers)))
3967     (let* ((data (condition-case ()
3968                      (funcall (if (boundp gnus-extract-address-components)
3969                                   gnus-extract-address-components
3970                                 'mail-extract-address-components)
3971                               from)
3972                    (error nil)))
3973            (name (car data))
3974            (fname name)
3975            (lname name)
3976            (net (car (cdr data)))
3977            (name-or-net (or (car data)
3978                             (car (cdr data)) from))
3979            (replydate
3980             (or
3981              date
3982              ;; We need Gnus functionality if the user wants date or time from
3983              ;; the original article:
3984              (when (string-match "%[^fnNFL]" message-citation-line-format)
3985                (autoload 'gnus-date-get-time "gnus-util")
3986                (gnus-date-get-time (mail-header-date message-reply-headers)))))
3987            (flist
3988             (let ((i ?A) lst)
3989               (when (stringp name)
3990                 ;; Guess first name and last name:
3991                 (cond ((string-match
3992                         "\\`\\(\\w\\|[-.]\\)+ \\(\\w\\|[-.]\\)+\\'" name)
3993                        (setq fname (nth 0 (split-string name "[ \t]+"))
3994                              lname (nth 1 (split-string name "[ \t]+"))))
3995                       ((string-match
3996                         "\\`\\(\\w\\|[-.]\\)+, \\(\\w\\|[-.]\\)+\\'" name)
3997                        (setq fname (nth 1 (split-string name "[ \t,]+"))
3998                              lname (nth 0 (split-string name "[ \t,]+"))))
3999                       ((string-match
4000                         "\\`\\(\\w\\|[-.]\\)+\\'" name)
4001                        (setq fname name
4002                              lname ""))))
4003               ;; The following letters are not used in `format-time-string':
4004               (push ?E lst) (push "<E>" lst)
4005               (push ?F lst) (push fname lst)
4006               ;; We might want to use "" instead of "<X>" later.
4007               (push ?J lst) (push "<J>" lst)
4008               (push ?K lst) (push "<K>" lst)
4009               (push ?L lst) (push lname lst)
4010               (push ?N lst) (push name-or-net lst)
4011               (push ?O lst) (push "<O>" lst)
4012               (push ?P lst) (push "<P>" lst)
4013               (push ?Q lst) (push "<Q>" lst)
4014               (push ?f lst) (push from lst)
4015               (push ?i lst) (push "<i>" lst)
4016               (push ?n lst) (push net lst)
4017               (push ?o lst) (push "<o>" lst)
4018               (push ?q lst) (push "<q>" lst)
4019               (push ?t lst) (push "<t>" lst)
4020               (push ?v lst) (push "<v>" lst)
4021               ;; Delegate the rest to `format-time-string':
4022               (while (<= i ?z)
4023                 (when (and (not (memq i lst))
4024                            ;; Skip (Z,a)
4025                            (or (<= i ?Z)
4026                                (>= i ?a)))
4027                   (push i lst)
4028                   (push (condition-case nil
4029                             (format-time-string (format "%%%c" i) replydate)
4030                           (error (format ">%c<" i)))
4031                         lst))
4032                 (setq i (1+ i)))
4033               (reverse lst)))
4034            (spec (apply 'format-spec-make flist)))
4035       (insert (format-spec message-citation-line-format spec)))
4036     (newline)))
4037
4038 (defun message-cite-original-without-signature ()
4039   "Cite function in the standard Message manner.
4040 This function strips off the signature from the original message."
4041   (message-cite-original-1 t))
4042
4043 (defun message-insert-citation-line ()
4044   "Insert a simple citation line."
4045   (when message-reply-headers
4046     (insert (mail-header-from message-reply-headers) " writes:")
4047     (newline)
4048     (newline)))
4049
4050 (defun message-position-on-field (header &rest afters)
4051   (let ((case-fold-search t))
4052     (save-restriction
4053       (narrow-to-region
4054        (goto-char (point-min))
4055        (progn
4056          (re-search-forward
4057           (concat "^" (regexp-quote mail-header-separator) "$"))
4058          (match-beginning 0)))
4059       (goto-char (point-min))
4060       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
4061           (progn
4062             (re-search-forward "^[^ \t]" nil 'move)
4063             (beginning-of-line)
4064             (skip-chars-backward "\n")
4065             t)
4066         (while (and afters
4067                     (not (re-search-forward
4068                           (concat "^" (regexp-quote (car afters)) ":")
4069                           nil t)))
4070           (pop afters))
4071         (when afters
4072           (re-search-forward "^[^ \t]" nil 'move)
4073           (beginning-of-line))
4074         (insert header ": \n")
4075         (forward-char -1)
4076         nil))))
4077
4078 \f
4079
4080 ;;;
4081 ;;; Sending messages
4082 ;;;
4083
4084 (defun message-send-and-exit (&optional arg)
4085   "Send message like `message-send', then, if no errors, exit from mail buffer.
4086 The usage of ARG is defined by the instance that called Message.
4087 It should typically alter the sending method in some way or other."
4088   (interactive "P")
4089   (let ((buf (current-buffer))
4090         (actions message-exit-actions))
4091     (when (and (message-send arg)
4092                (buffer-name buf))
4093       (message-bury buf)
4094       (if message-kill-buffer-on-exit
4095           (kill-buffer buf))
4096       (message-do-actions actions)
4097       t)))
4098
4099 (defun message-dont-send ()
4100   "Don't send the message you have been editing.
4101 Instead, just auto-save the buffer and then bury it."
4102   (interactive)
4103   (set-buffer-modified-p t)
4104   (save-buffer)
4105   (let ((actions message-postpone-actions))
4106     (message-bury (current-buffer))
4107     (message-do-actions actions)))
4108
4109 (defun message-kill-buffer ()
4110   "Kill the current buffer."
4111   (interactive)
4112   (when (or (not (buffer-modified-p))
4113             (not message-kill-buffer-query)
4114             (yes-or-no-p "Message modified; kill anyway? "))
4115     (let ((actions message-kill-actions)
4116           (draft-article message-draft-article)
4117           (auto-save-file-name buffer-auto-save-file-name)
4118           (file-name buffer-file-name)
4119           (modified (buffer-modified-p)))
4120       (setq buffer-file-name nil)
4121       (kill-buffer (current-buffer))
4122       (when (and (or (and auto-save-file-name
4123                           (file-exists-p auto-save-file-name))
4124                      (and file-name
4125                           (file-exists-p file-name)))
4126                  (progn
4127                    ;; If the message buffer has lived in a dedicated window,
4128                    ;; `kill-buffer' has killed the frame.  Thus the
4129                    ;; `yes-or-no-p' may show up in a lowered frame.  Make sure
4130                    ;; that the user can see the question by raising the
4131                    ;; current frame:
4132                    (raise-frame)
4133                    (yes-or-no-p (format "Remove the backup file%s? "
4134                                         (if modified " too" "")))))
4135         (ignore-errors
4136           (delete-file auto-save-file-name))
4137         (let ((message-draft-article draft-article))
4138           (message-disassociate-draft)))
4139       (message-do-actions actions))))
4140
4141 (defun message-bury (buffer)
4142   "Bury this mail BUFFER."
4143   (if message-return-action
4144       (progn
4145         (bury-buffer buffer)
4146         (apply (car message-return-action) (cdr message-return-action)))
4147     (with-current-buffer buffer (bury-buffer))))
4148
4149 (defun message-send (&optional arg)
4150   "Send the message in the current buffer.
4151 If `message-interactive' is non-nil, wait for success indication or
4152 error messages, and inform user.
4153 Otherwise any failure is reported in a message back to the user from
4154 the mailer.
4155 The usage of ARG is defined by the instance that called Message.
4156 It should typically alter the sending method in some way or other."
4157   (interactive "P")
4158   ;; Make it possible to undo the coming changes.
4159   (undo-boundary)
4160   (let ((inhibit-read-only t))
4161     (put-text-property (point-min) (point-max) 'read-only nil))
4162   (message-fix-before-sending)
4163   (run-hooks 'message-send-hook)
4164   (when message-confirm-send
4165     (or (y-or-n-p "Send message? ")
4166         (keyboard-quit)))
4167   (message message-sending-message)
4168   (let ((alist message-send-method-alist)
4169         (success t)
4170         elem sent dont-barf-on-no-method
4171         (message-options message-options))
4172     (message-options-set-recipient)
4173     (while (and success
4174                 (setq elem (pop alist)))
4175       (when (funcall (cadr elem))
4176         (when (and (or (not (memq (car elem)
4177                                   message-sent-message-via))
4178                        (message-fetch-field "supersedes")
4179                        (if (or (message-gnksa-enable-p 'multiple-copies)
4180                                (not (eq (car elem) 'news)))
4181                            (y-or-n-p
4182                             (format
4183                              "Already sent message via %s; resend? "
4184                              (car elem)))
4185                          (error "Denied posting -- multiple copies")))
4186                    (setq success (funcall (caddr elem) arg)))
4187           (setq sent t))))
4188     (unless (or sent
4189                 (not success)
4190                 (let ((fcc (message-fetch-field "Fcc"))
4191                       (gcc (message-fetch-field "Gcc")))
4192                   (when (or fcc gcc)
4193                     (or (eq message-allow-no-recipients 'always)
4194                         (and (not (eq message-allow-no-recipients 'never))
4195                              (setq dont-barf-on-no-method
4196                                    (gnus-y-or-n-p
4197                                     (format "No receiver, perform %s anyway? "
4198                                             (cond ((and fcc gcc) "Fcc and Gcc")
4199                                                   (fcc "Fcc")
4200                                                   (t "Gcc"))))))))))
4201       (error "No methods specified to send by"))
4202     (when (or dont-barf-on-no-method
4203               (and success sent))
4204       (message-do-fcc)
4205       (save-excursion
4206         (run-hooks 'message-sent-hook))
4207       (message "Sending...done")
4208       ;; Do ecomplete address snarfing.
4209       (when (and (message-mail-alias-type-p 'ecomplete)
4210                  (not message-inhibit-ecomplete))
4211         (message-put-addresses-in-ecomplete))
4212       ;; Mark the buffer as unmodified and delete auto-save.
4213       (set-buffer-modified-p nil)
4214       (delete-auto-save-file-if-necessary t)
4215       (message-disassociate-draft)
4216       ;; Delete other mail buffers and stuff.
4217       (message-do-send-housekeeping)
4218       (message-do-actions message-send-actions)
4219       ;; Return success.
4220       t)))
4221
4222 (defun message-send-via-mail (arg)
4223   "Send the current message via mail."
4224   (message-send-mail arg))
4225
4226 (defun message-send-via-news (arg)
4227   "Send the current message via news."
4228   (funcall message-send-news-function arg))
4229
4230 (defmacro message-check (type &rest forms)
4231   "Eval FORMS if TYPE is to be checked."
4232   `(or (message-check-element ,type)
4233        (save-excursion
4234          ,@forms)))
4235
4236 (put 'message-check 'lisp-indent-function 1)
4237 (put 'message-check 'edebug-form-spec '(form body))
4238
4239 (defun message-text-with-property (prop &optional start end reverse)
4240   "Return a list of start and end positions where the text has PROP.
4241 START and END bound the search, they default to `point-min' and
4242 `point-max' respectively.  If REVERSE is non-nil, find text which does
4243 not have PROP."
4244   (unless start
4245     (setq start (point-min)))
4246   (unless end
4247     (setq end (point-max)))
4248   (let (next regions)
4249     (if reverse
4250         (while (and start
4251                     (setq start (text-property-any start end prop nil)))
4252           (setq next (next-single-property-change start prop nil end))
4253           (push (cons start (or next end)) regions)
4254           (setq start next))
4255       (while (and start
4256                   (or (get-text-property start prop)
4257                       (and (setq start (next-single-property-change
4258                                         start prop nil end))
4259                            (get-text-property start prop))))
4260         (setq next (text-property-any start end prop nil))
4261         (push (cons start (or next end)) regions)
4262         (setq start next)))
4263     (nreverse regions)))
4264
4265 (defcustom message-bogus-addresses
4266   '("noreply" "nospam" "invalid" "@@" "[^[:ascii:]].*@" "[ \t]")
4267   "List of regexps of potentially bogus mail addresses.
4268 See `message-check-recipients' how to setup checking.
4269
4270 This list should make it possible to catch typos or warn about
4271 spam-trap addresses.  It doesn't aim to verify strict RFC
4272 conformance."
4273   :version "23.1" ;; No Gnus
4274   :group 'message-headers
4275   :type '(choice
4276           (const :tag "None" nil)
4277           (list
4278            (set :inline t
4279                 (const "noreply")
4280                 (const "nospam")
4281                 (const "invalid")
4282                 (const :tag "duplicate @" "@@")
4283                 (const :tag "non-ascii local part" "[^[:ascii:]].*@")
4284                 ;; Already caught by `message-valid-fqdn-regexp'
4285                 ;; (const :tag "`_' in domain part" "@.*_")
4286                 (const :tag "whitespace" "[ \t]"))
4287            (repeat :inline t
4288                    :tag "Other"
4289                    (regexp)))))
4290
4291 (defun message-fix-before-sending ()
4292   "Do various things to make the message nice before sending it."
4293   ;; Make sure there's a newline at the end of the message.
4294   (goto-char (point-max))
4295   (unless (bolp)
4296     (insert "\n"))
4297   ;; Make the hidden headers visible.
4298   (widen)
4299   ;; Sort headers before sending the message.
4300   (message-sort-headers)
4301   ;; Make invisible text visible.
4302   ;; It doesn't seem as if this is useful, since the invisible property
4303   ;; is clobbered by an after-change hook anyhow.
4304   (message-check 'invisible-text
4305     (let ((regions (message-text-with-property 'invisible))
4306           from to)
4307       (when regions
4308         (while regions
4309           (setq from (caar regions)
4310                 to (cdar regions)
4311                 regions (cdr regions))
4312           (put-text-property from to 'invisible nil)
4313           (message-overlay-put (message-make-overlay from to)
4314                                'face 'highlight))
4315         (unless (yes-or-no-p
4316                  "Invisible text found and made visible; continue sending? ")
4317           (error "Invisible text found and made visible")))))
4318   (message-check 'illegible-text
4319     (let (char found choice nul-chars)
4320       (message-goto-body)
4321       (setq nul-chars (save-excursion
4322                         (search-forward "\000" nil t)))
4323       (while (progn
4324                (skip-chars-forward mm-7bit-chars)
4325                (when (get-text-property (point) 'no-illegible-text)
4326                  ;; There is a signed or encrypted raw message part
4327                  ;; that is considered to be safe.
4328                  (goto-char (or (next-single-property-change
4329                                  (point) 'no-illegible-text)
4330                                 (point-max))))
4331                (setq char (char-after)))
4332         (when (or (< (mm-char-int char) 128)
4333                   (and (mm-multibyte-p)
4334                        (memq (char-charset char)
4335                              '(eight-bit-control eight-bit-graphic
4336                                                  ;; Emacs 23, Bug#1770:
4337                                                  eight-bit
4338                                                  control-1))
4339                        (not (get-text-property
4340                              (point) 'untranslated-utf-8))))
4341           (message-overlay-put (message-make-overlay (point) (1+ (point)))
4342                                'face 'highlight)
4343           (setq found t))
4344         (forward-char))
4345       (when found
4346         (setq choice
4347               (gnus-multiple-choice
4348                (if nul-chars
4349                    "NUL characters found, which may cause problems.  Continue sending?"
4350                  "Non-printable characters found.  Continue sending?")
4351                `((?d "Remove non-printable characters and send")
4352                  (?r ,(format
4353                        "Replace non-printable characters with \"%s\" and send"
4354                        message-replacement-char))
4355                  (?s "Send as is without removing anything")
4356                  (?e "Continue editing"))))
4357         (if (eq choice ?e)
4358           (error "Non-printable characters"))
4359         (message-goto-body)
4360         (skip-chars-forward mm-7bit-chars)
4361         (while (not (eobp))
4362           (when (let ((char (char-after)))
4363                   (or (< (mm-char-int char) 128)
4364                       (and (mm-multibyte-p)
4365                            ;; FIXME: Wrong for Emacs 23 (unicode) and for
4366                            ;; things like undecodable utf-8 (in Emacs 21?).
4367                            ;; Should at least use find-coding-systems-region.
4368                            ;; -- fx
4369                            (memq (char-charset char)
4370                                  '(eight-bit-control eight-bit-graphic
4371                                                      ;; Emacs 23, Bug#1770:
4372                                                      eight-bit
4373                                                      control-1))
4374                            (not (get-text-property
4375                                  (point) 'untranslated-utf-8)))))
4376             (if (eq choice ?i)
4377                 (message-kill-all-overlays)
4378               (delete-char 1)
4379               (when (eq choice ?r)
4380                 (insert message-replacement-char))))
4381           (forward-char)
4382           (skip-chars-forward mm-7bit-chars)))))
4383   (message-check 'bogus-recipient
4384     ;; Warn before sending a mail to an invalid address.
4385     (message-check-recipients)))
4386
4387 (defun message-bogus-recipient-p (recipients)
4388   "Check if a mail address in RECIPIENTS looks bogus.
4389
4390 RECIPIENTS is a mail header.  Return a list of potentially bogus
4391 addresses.  If none is found, return nil.
4392
4393 An address might be bogus if the domain part is not fully
4394 qualified, see `message-valid-fqdn-regexp', or if there's a
4395 matching entry in `message-bogus-addresses'."
4396   ;; FIXME: How about "foo@subdomain", when the MTA adds ".domain.tld"?
4397   (let (found)
4398     (mapc (lambda (address)
4399             (setq address (or (cadr address) ""))
4400             (when
4401                 (or (string= "" address)
4402                     (not
4403                      (or
4404                       (not (string-match "@" address))
4405                       (string-match
4406                        (concat ".@.*\\("
4407                                message-valid-fqdn-regexp "\\)\\'") address)))
4408                     (and message-bogus-addresses
4409                          (let ((re
4410                                 (if (listp message-bogus-addresses)
4411                                     (mapconcat 'identity
4412                                                message-bogus-addresses
4413                                                "\\|")
4414                                   message-bogus-addresses)))
4415                            (string-match re address))))
4416               (push address found)))
4417           ;;
4418           (mail-extract-address-components recipients t))
4419     found))
4420
4421 (defun message-check-recipients ()
4422   "Warn before composing or sending a mail to an invalid address.
4423
4424 This function could be useful in `message-setup-hook'."
4425   (interactive)
4426   (save-restriction
4427     (message-narrow-to-headers)
4428     (dolist (hdr '("To" "Cc" "Bcc"))
4429       (let ((addr (message-fetch-field hdr)))
4430         (when (stringp addr)
4431           (dolist (bog (message-bogus-recipient-p addr))
4432             (and bog
4433                  (not (y-or-n-p
4434                        (format
4435                         "Address `%s'%s might be bogus.  Continue? "
4436                         bog
4437                         ;; If the encoded version of the email address
4438                         ;; is different from the unencoded version,
4439                         ;; then we likely have invisible characters or
4440                         ;; the like.  Display the encoded version,
4441                         ;; too.
4442                         (let ((encoded (rfc2047-encode-string bog)))
4443                           (if (string= encoded bog)
4444                               ""
4445                             (format " (%s)" encoded))))))
4446                  (error "Bogus address"))))))))
4447
4448 (custom-add-option 'message-setup-hook 'message-check-recipients)
4449
4450 (defun message-add-action (action &rest types)
4451   "Add ACTION to be performed when doing an exit of type TYPES."
4452   (while types
4453     (add-to-list (intern (format "message-%s-actions" (pop types)))
4454                  action)))
4455
4456 (defun message-delete-action (action &rest types)
4457   "Delete ACTION from lists of actions performed when doing an exit of type TYPES."
4458   (let (var)
4459     (while types
4460       (set (setq var (intern (format "message-%s-actions" (pop types))))
4461            (delq action (symbol-value var))))))
4462
4463 (defun message-do-actions (actions)
4464   "Perform all actions in ACTIONS."
4465   ;; Now perform actions on successful sending.
4466   (dolist (action actions)
4467     (ignore-errors
4468       (cond
4469        ;; A simple function.
4470        ((functionp action)
4471         (funcall action))
4472        ;; Something to be evalled.
4473        (t
4474         (eval action))))))
4475
4476 (defun message-send-mail-partially ()
4477   "Send mail as message/partial."
4478   ;; replace the header delimiter with a blank line
4479   (goto-char (point-min))
4480   (re-search-forward
4481    (concat "^" (regexp-quote mail-header-separator) "\n"))
4482   (replace-match "\n")
4483   (run-hooks 'message-send-mail-hook)
4484   (let ((p (goto-char (point-min)))
4485         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
4486         (curbuf (current-buffer))
4487         (id (message-make-message-id)) (n 1)
4488         plist total header)
4489     (while (not (eobp))
4490       (if (< (point-max) (+ p message-send-mail-partially-limit))
4491           (goto-char (point-max))
4492         (goto-char (+ p message-send-mail-partially-limit))
4493         (beginning-of-line)
4494         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
4495       (push p plist)
4496       (setq p (point)))
4497     (setq total (length plist))
4498     (push (point-max) plist)
4499     (setq plist (nreverse plist))
4500     (unwind-protect
4501         (save-excursion
4502           (setq p (pop plist))
4503           (while plist
4504             (set-buffer curbuf)
4505             (copy-to-buffer tembuf p (car plist))
4506             (set-buffer tembuf)
4507             (goto-char (point-min))
4508             (if header
4509                 (progn
4510                   (goto-char (point-min))
4511                   (narrow-to-region (point) (point))
4512                   (insert header))
4513               (message-goto-eoh)
4514               (setq header (buffer-substring (point-min) (point)))
4515               (goto-char (point-min))
4516               (narrow-to-region (point) (point))
4517               (insert header)
4518               (message-remove-header "Mime-Version")
4519               (message-remove-header "Content-Type")
4520               (message-remove-header "Content-Transfer-Encoding")
4521               (message-remove-header "Message-ID")
4522               (message-remove-header "Lines")
4523               (goto-char (point-max))
4524               (insert "Mime-Version: 1.0\n")
4525               (setq header (buffer-string)))
4526             (goto-char (point-max))
4527             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n\n"
4528                             id n total))
4529             (forward-char -1)
4530             (let ((mail-header-separator ""))
4531               (when (memq 'Message-ID message-required-mail-headers)
4532                 (insert "Message-ID: " (message-make-message-id) "\n"))
4533               (when (memq 'Lines message-required-mail-headers)
4534                 (insert "Lines: " (message-make-lines) "\n"))
4535               (message-goto-subject)
4536               (end-of-line)
4537               (insert (format " (%d/%d)" n total))
4538               (widen)
4539               (if message-send-mail-real-function
4540                   (funcall message-send-mail-real-function)
4541                 (message-multi-smtp-send-mail)))
4542             (setq n (+ n 1))
4543             (setq p (pop plist))
4544             (erase-buffer)))
4545       (kill-buffer tembuf))))
4546
4547 (declare-function hashcash-wait-async "hashcash" (&optional buffer))
4548
4549 (defun message-send-mail (&optional arg)
4550   (require 'mail-utils)
4551   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
4552          (case-fold-search nil)
4553          (news (message-news-p))
4554          (mailbuf (current-buffer))
4555          (message-this-is-mail t)
4556          ;; gnus-setup-posting-charset is autoloaded in mml.el (FIXME
4557          ;; maybe it should not be), which this file requires.  Hence
4558          ;; the fboundp test is always true.  Loading it from gnus-msg
4559          ;; loads many Gnus files (Bug#5642).  If
4560          ;; gnus-group-posting-charset-alist hasn't been customized,
4561          ;; this is just going to return nil anyway.  FIXME it would
4562          ;; be good to improve this further, because even if g-g-p-c-a
4563          ;; has been customized, that is likely to just be for news.
4564          ;; Eg either move the definition from gnus-msg, or separate out
4565          ;; the mail and news parts.
4566          (message-posting-charset
4567           (if (and (fboundp 'gnus-setup-posting-charset)
4568                    (boundp 'gnus-group-posting-charset-alist))
4569               (gnus-setup-posting-charset nil)
4570             message-posting-charset))
4571          (headers message-required-mail-headers)
4572          options)
4573     (when (and message-generate-hashcash
4574                (not (eq message-generate-hashcash 'opportunistic)))
4575       (message "Generating hashcash...")
4576       (require 'hashcash)
4577       ;; Wait for calculations already started to finish...
4578       (hashcash-wait-async)
4579       ;; ...and do calculations not already done.  mail-add-payment
4580       ;; will leave existing X-Hashcash headers alone.
4581       (mail-add-payment)
4582       (message "Generating hashcash...done"))
4583     (save-restriction
4584       (message-narrow-to-headers)
4585       ;; Generate the Mail-Followup-To header if the header is not there...
4586       (if (and (message-subscribed-p)
4587                (not (mail-fetch-field "mail-followup-to")))
4588           (setq headers
4589                 (cons
4590                  (cons "Mail-Followup-To" (message-make-mail-followup-to))
4591                  message-required-mail-headers))
4592         ;; otherwise, delete the MFT header if the field is empty
4593         (when (equal "" (mail-fetch-field "mail-followup-to"))
4594           (message-remove-header "^Mail-Followup-To:")))
4595       ;; Insert some headers.
4596       (let ((message-deletable-headers
4597              (if news nil message-deletable-headers)))
4598         (message-generate-headers headers))
4599       ;; Check continuation headers.
4600       (message-check 'continuation-headers
4601         (goto-char (point-min))
4602         (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
4603           (goto-char (match-beginning 0))
4604           (if (y-or-n-p "Fix continuation lines? ")
4605               (insert " ")
4606             (forward-line 1)
4607             (unless (y-or-n-p "Send anyway? ")
4608               (error "Failed to send the message")))))
4609       ;; Let the user do all of the above.
4610       (run-hooks 'message-header-hook))
4611     (setq options message-options)
4612     (unwind-protect
4613         (with-current-buffer tembuf
4614           (erase-buffer)
4615           (setq message-options options)
4616           ;; Avoid copying text props (except hard newlines).
4617           (insert (with-current-buffer mailbuf
4618                     (mml-buffer-substring-no-properties-except-hard-newlines
4619                      (point-min) (point-max))))
4620           ;; Remove some headers.
4621           (message-encode-message-body)
4622           (save-restriction
4623             (message-narrow-to-headers)
4624             ;; We (re)generate the Lines header.
4625             (when (memq 'Lines message-required-mail-headers)
4626               (message-generate-headers '(Lines)))
4627             ;; Remove some headers.
4628             (message-remove-header message-ignored-mail-headers t)
4629             (let ((mail-parse-charset message-default-charset))
4630               (mail-encode-encoded-word-buffer)))
4631           (goto-char (point-max))
4632           ;; require one newline at the end.
4633           (or (= (preceding-char) ?\n)
4634               (insert ?\n))
4635           (message-cleanup-headers)
4636           ;; FIXME: we're inserting the courtesy copy after encoding.
4637           ;; This is wrong if the courtesy copy string contains
4638           ;; non-ASCII characters. -- jh
4639           (when
4640               (save-restriction
4641                 (message-narrow-to-headers)
4642                 (and news
4643                      (not (message-fetch-field "List-Post"))
4644                      (not (message-fetch-field "List-ID"))
4645                      (or (message-fetch-field "cc")
4646                          (message-fetch-field "bcc")
4647                          (message-fetch-field "to"))
4648                      (let ((content-type (message-fetch-field
4649                                           "content-type")))
4650                        (and
4651                         (or
4652                          (not content-type)
4653                          (string= "text/plain"
4654                                   (car
4655                                    (mail-header-parse-content-type
4656                                     content-type))))
4657                         (not
4658                          (string= "base64"
4659                                   (message-fetch-field
4660                                    "content-transfer-encoding")))))))
4661             (message-insert-courtesy-copy
4662              (with-current-buffer mailbuf
4663                message-courtesy-message)))
4664           ;; Let's make sure we encoded all the body.
4665           (assert (save-excursion
4666                     (goto-char (point-min))
4667                     (not (re-search-forward "[^\000-\377]" nil t))))
4668           (mm-disable-multibyte)
4669           (if (or (not message-send-mail-partially-limit)
4670                   (< (buffer-size) message-send-mail-partially-limit)
4671                   (not (message-y-or-n-p
4672                         "The message size is too large, split? "
4673                         t
4674                         "\
4675 The message size, "
4676                         (/ (buffer-size) 1000) "KB, is too large.
4677
4678 Some mail gateways (MTA's) bounce large messages.  To avoid the
4679 problem, answer `y', and the message will be split into several
4680 smaller pieces, the size of each is about "
4681                         (/ message-send-mail-partially-limit 1000)
4682                         "KB except the last
4683 one.
4684
4685 However, some mail readers (MUA's) can't read split messages, i.e.,
4686 mails in message/partially format. Answer `n', and the message will be
4687 sent in one piece.
4688
4689 The size limit is controlled by `message-send-mail-partially-limit'.
4690 If you always want Gnus to send messages in one piece, set
4691 `message-send-mail-partially-limit' to nil.
4692 ")))
4693               (progn
4694                 (message "Sending via mail...")
4695                 (if message-send-mail-real-function
4696                     (funcall message-send-mail-real-function)
4697                   (message-multi-smtp-send-mail)))
4698             (message-send-mail-partially))
4699           (setq options message-options))
4700       (kill-buffer tembuf))
4701     (set-buffer mailbuf)
4702     (setq message-options options)
4703     (push 'mail message-sent-message-via)))
4704
4705 (defvar sendmail-program)
4706 (defvar smtpmail-smtp-user)
4707
4708 (defun message-multi-smtp-send-mail ()
4709   "Send the current buffer to `message-send-mail-function'.
4710 Or, if there's a header that specifies a different method, use
4711 that instead."
4712   (let ((method (message-field-value "X-Message-SMTP-Method")))
4713     (if (not method)
4714         (funcall message-send-mail-function)
4715       (message-remove-header "X-Message-SMTP-Method")
4716       (setq method (split-string method))
4717       (cond
4718        ((equal (car method) "sendmail")
4719         (message-send-mail-with-sendmail))
4720        ((equal (car method) "smtp")
4721         (require 'smtpmail)
4722         (let ((smtpmail-smtp-server (nth 1 method))
4723               (smtpmail-smtp-service (nth 2 method))
4724               (smtpmail-smtp-user (or (nth 3 method) smtpmail-smtp-user)))
4725           (message-smtpmail-send-it)))
4726        (t
4727         (error "Unknown method %s" method))))))
4728
4729 (defun message-send-mail-with-sendmail ()
4730   "Send off the prepared buffer with sendmail."
4731   (require 'sendmail)
4732   (let ((errbuf (if message-interactive
4733                     (message-generate-new-buffer-clone-locals
4734                      " sendmail errors")
4735                   0))
4736         resend-to-addresses delimline)
4737     (unwind-protect
4738         (progn
4739           (let ((case-fold-search t))
4740             (save-restriction
4741               (message-narrow-to-headers)
4742               (setq resend-to-addresses (message-fetch-field "resent-to")))
4743             ;; Change header-delimiter to be what sendmail expects.
4744             (goto-char (point-min))
4745             (re-search-forward
4746              (concat "^" (regexp-quote mail-header-separator) "\n"))
4747             (replace-match "\n")
4748             (backward-char 1)
4749             (setq delimline (point-marker))
4750             (run-hooks 'message-send-mail-hook)
4751             ;; Insert an extra newline if we need it to work around
4752             ;; Sun's bug that swallows newlines.
4753             (goto-char (1+ delimline))
4754             (when (eval message-mailer-swallows-blank-line)
4755               (newline))
4756             (when message-interactive
4757               (with-current-buffer errbuf
4758                 (erase-buffer))))
4759           (let* ((default-directory "/")
4760                  (coding-system-for-write message-send-coding-system)
4761                  (cpr (apply
4762                        'call-process-region
4763                        (append
4764                         (list (point-min) (point-max) sendmail-program
4765                               nil errbuf nil "-oi")
4766                         message-sendmail-extra-arguments
4767                         ;; Always specify who from,
4768                         ;; since some systems have broken sendmails.
4769                         ;; But some systems are more broken with -f, so
4770                         ;; we'll let users override this.
4771                         (and (null message-sendmail-f-is-evil)
4772                              (list "-f" (message-sendmail-envelope-from)))
4773                         ;; These mean "report errors by mail"
4774                         ;; and "deliver in background".
4775                         (if (null message-interactive) '("-oem" "-odb"))
4776                         ;; Get the addresses from the message
4777                         ;; unless this is a resend.
4778                         ;; We must not do that for a resend
4779                         ;; because we would find the original addresses.
4780                         ;; For a resend, include the specific addresses.
4781                         (if resend-to-addresses
4782                             (list resend-to-addresses)
4783                           '("-t"))))))
4784             (unless (or (null cpr) (and (numberp cpr) (zerop cpr)))
4785               (if errbuf (pop-to-buffer errbuf))
4786               (error "Sending...failed with exit value %d" cpr)))
4787           (when message-interactive
4788             (with-current-buffer errbuf
4789               (goto-char (point-min))
4790               (while (re-search-forward "\n+ *" nil t)
4791                 (replace-match "; "))
4792               (if (not (zerop (buffer-size)))
4793                   (error "Sending...failed to %s"
4794                          (buffer-string))))))
4795       (when (bufferp errbuf)
4796         (kill-buffer errbuf)))))
4797
4798 (defun message-send-mail-with-qmail ()
4799   "Pass the prepared message buffer to qmail-inject.
4800 Refer to the documentation for the variable `message-send-mail-function'
4801 to find out how to use this."
4802   ;; replace the header delimiter with a blank line
4803   (goto-char (point-min))
4804   (re-search-forward
4805    (concat "^" (regexp-quote mail-header-separator) "\n"))
4806   (replace-match "\n")
4807   (run-hooks 'message-send-mail-hook)
4808   ;; send the message
4809   (case
4810       (let ((coding-system-for-write message-send-coding-system))
4811         (apply
4812          'call-process-region (point-min) (point-max)
4813          message-qmail-inject-program nil nil nil
4814          ;; qmail-inject's default behavior is to look for addresses on the
4815          ;; command line; if there're none, it scans the headers.
4816          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4817          ;;
4818          ;; in general, ALL of qmail-inject's defaults are perfect for simply
4819          ;; reading a formatted (i. e., at least a To: or Resent-To header)
4820          ;; message from stdin.
4821          ;;
4822          ;; qmail also has the advantage of not having been raped by
4823          ;; various vendors, so we don't have to allow for that, either --
4824          ;; compare this with message-send-mail-with-sendmail and weep
4825          ;; for sendmail's lost innocence.
4826          ;;
4827          ;; all this is way cool coz it lets us keep the arguments entirely
4828          ;; free for -inject-arguments -- a big win for the user and for us
4829          ;; since we don't have to play that double-guessing game and the user
4830          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4831          (if (functionp message-qmail-inject-args)
4832              (funcall message-qmail-inject-args)
4833            message-qmail-inject-args)))
4834     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4835     ;; we have to look at the retval instead
4836     (0 nil)
4837     (100 (error "qmail-inject reported permanent failure"))
4838     (111 (error "qmail-inject reported transient failure"))
4839     ;; should never happen
4840     (t   (error "qmail-inject reported unknown failure"))))
4841
4842 (defvar mh-previous-window-config)
4843
4844 (defun message-send-mail-with-mh ()
4845   "Send the prepared message buffer with mh."
4846   (let ((mh-previous-window-config nil)
4847         (name (mh-new-draft-name)))
4848     (setq buffer-file-name name)
4849     ;; MH wants to generate these headers itself.
4850     (when message-mh-deletable-headers
4851       (let ((headers message-mh-deletable-headers))
4852         (while headers
4853           (goto-char (point-min))
4854           (and (re-search-forward
4855                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4856                (message-delete-line))
4857           (pop headers))))
4858     (run-hooks 'message-send-mail-hook)
4859     ;; Pass it on to mh.
4860     (mh-send-letter)))
4861
4862 (defun message-smtpmail-send-it ()
4863   "Send the prepared message buffer with `smtpmail-send-it'.
4864 The only difference from `smtpmail-send-it' is that this command
4865 evaluates `message-send-mail-hook' just before sending a message.
4866 It is useful if your ISP requires the POP-before-SMTP
4867 authentication.  See the Gnus manual for details."
4868   (run-hooks 'message-send-mail-hook)
4869   (smtpmail-send-it))
4870
4871 (defun message-send-mail-with-mailclient ()
4872   "Send the prepared message buffer with `mailclient-send-it'.
4873 The only difference from `mailclient-send-it' is that this
4874 command evaluates `message-send-mail-hook' just before sending a message."
4875   (run-hooks 'message-send-mail-hook)
4876   (mailclient-send-it))
4877
4878 (defun message-canlock-generate ()
4879   "Return a string that is non-trivial to guess.
4880 Do not use this for anything important, it is cryptographically weak."
4881   (require 'sha1)
4882   (let (sha1-maximum-internal-length)
4883     (sha1 (concat (message-unique-id)
4884                   (format "%x%x%x" (random) (random) (random))
4885                   (prin1-to-string (recent-keys))
4886                   (prin1-to-string (garbage-collect))))))
4887
4888 (defvar canlock-password)
4889 (defvar canlock-password-for-verify)
4890
4891 (defun message-canlock-password ()
4892   "The password used by message for cancel locks.
4893 This is the value of `canlock-password', if that option is non-nil.
4894 Otherwise, generate and save a value for `canlock-password' first."
4895   (require 'canlock)
4896   (unless canlock-password
4897     (customize-save-variable 'canlock-password (message-canlock-generate))
4898     (setq canlock-password-for-verify canlock-password))
4899   canlock-password)
4900
4901 (defun message-insert-canlock ()
4902   (when message-insert-canlock
4903     (message-canlock-password)
4904     (canlock-insert-header)))
4905
4906 (autoload 'nnheader-get-report "nnheader")
4907
4908 (declare-function gnus-setup-posting-charset "gnus-msg" (group))
4909
4910 (defun message-send-news (&optional arg)
4911   (require 'gnus-msg)
4912   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4913          (case-fold-search nil)
4914          (method (if (functionp message-post-method)
4915                      (funcall message-post-method arg)
4916                    message-post-method))
4917          (newsgroups-field (save-restriction
4918                             (message-narrow-to-headers-or-head)
4919                             (message-fetch-field "Newsgroups")))
4920          (followup-field (save-restriction
4921                            (message-narrow-to-headers-or-head)
4922                            (message-fetch-field "Followup-To")))
4923          ;; BUG: We really need to get the charset for each name in the
4924          ;; Newsgroups and Followup-To lines to allow crossposting
4925          ;; between group names with incompatible character sets.
4926          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4927          (group-field-charset
4928           (gnus-group-name-charset method newsgroups-field))
4929          (followup-field-charset
4930           (gnus-group-name-charset method (or followup-field "")))
4931          (rfc2047-header-encoding-alist
4932           (append (when group-field-charset
4933                     (list (cons "Newsgroups" group-field-charset)))
4934                   (when followup-field-charset
4935                     (list (cons "Followup-To" followup-field-charset)))
4936                   rfc2047-header-encoding-alist))
4937          (messbuf (current-buffer))
4938          (message-syntax-checks
4939           (if (and arg
4940                    (listp message-syntax-checks))
4941               (cons '(existing-newsgroups . disabled)
4942                     message-syntax-checks)
4943             message-syntax-checks))
4944          (message-this-is-news t)
4945          (message-posting-charset
4946           (gnus-setup-posting-charset newsgroups-field))
4947          result)
4948     (if (not (message-check-news-body-syntax))
4949         nil
4950       (save-restriction
4951         (message-narrow-to-headers)
4952         ;; Insert some headers.
4953         (message-generate-headers message-required-news-headers)
4954         (message-insert-canlock)
4955         ;; Let the user do all of the above.
4956         (run-hooks 'message-header-hook))
4957       ;; Note: This check will be disabled by the ".*" default value for
4958       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4959       (when (and group-field-charset
4960                  (listp message-syntax-checks))
4961         (setq message-syntax-checks
4962               (cons '(valid-newsgroups . disabled)
4963                     message-syntax-checks)))
4964       (message-cleanup-headers)
4965       (if (not (let ((message-post-method method))
4966                  (message-check-news-syntax)))
4967           nil
4968         (unwind-protect
4969             (with-current-buffer tembuf
4970               (buffer-disable-undo)
4971               (erase-buffer)
4972               ;; Avoid copying text props (except hard newlines).
4973               (insert
4974                (with-current-buffer messbuf
4975                  (mml-buffer-substring-no-properties-except-hard-newlines
4976                   (point-min) (point-max))))
4977               (message-encode-message-body)
4978               ;; Remove some headers.
4979               (save-restriction
4980                 (message-narrow-to-headers)
4981                 ;; We (re)generate the Lines header.
4982                 (when (memq 'Lines message-required-mail-headers)
4983                   (message-generate-headers '(Lines)))
4984                 ;; Remove some headers.
4985                 (message-remove-header message-ignored-news-headers t)
4986                 (let ((mail-parse-charset message-default-charset))
4987                   (mail-encode-encoded-word-buffer)))
4988               (goto-char (point-max))
4989               ;; require one newline at the end.
4990               (or (= (preceding-char) ?\n)
4991                   (insert ?\n))
4992               (let ((case-fold-search t))
4993                 ;; Remove the delimiter.
4994                 (goto-char (point-min))
4995                 (re-search-forward
4996                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4997                 (replace-match "\n")
4998                 (backward-char 1))
4999               (run-hooks 'message-send-news-hook)
5000               (gnus-open-server method)
5001               (message "Sending news via %s..." (gnus-server-string method))
5002               (setq result (let ((mail-header-separator ""))
5003                              (gnus-request-post method))))
5004           (kill-buffer tembuf))
5005         (set-buffer messbuf)
5006         (if result
5007             (push 'news message-sent-message-via)
5008           (message "Couldn't send message via news: %s"
5009                    (nnheader-get-report (car method)))
5010           nil)))))
5011
5012 ;;;
5013 ;;; Header generation & syntax checking.
5014 ;;;
5015
5016 (defun message-check-element (type)
5017   "Return non-nil if this TYPE is not to be checked."
5018   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
5019       t
5020     (let ((able (assq type message-syntax-checks)))
5021       (and (consp able)
5022            (eq (cdr able) 'disabled)))))
5023
5024 (defun message-check-news-syntax ()
5025   "Check the syntax of the message."
5026   (save-excursion
5027     (save-restriction
5028       (widen)
5029       ;; We narrow to the headers and check them first.
5030       (save-excursion
5031         (save-restriction
5032           (message-narrow-to-headers)
5033           (message-check-news-header-syntax))))))
5034
5035 (defun message-check-news-header-syntax ()
5036   (and
5037    ;; Check Newsgroups header.
5038    (message-check 'newsgroups
5039      (let ((group (message-fetch-field "newsgroups")))
5040        (or
5041         (and group
5042              (not (string-match "\\`[ \t]*\\'" group)))
5043         (ignore
5044          (message
5045           "The newsgroups field is empty or missing.  Posting is denied.")))))
5046    ;; Check the Subject header.
5047    (message-check 'subject
5048      (let* ((case-fold-search t)
5049             (subject (message-fetch-field "subject")))
5050        (or
5051         (and subject
5052              (not (string-match "\\`[ \t]*\\'" subject)))
5053         (ignore
5054          (message
5055           "The subject field is empty or missing.  Posting is denied.")))))
5056    ;; Check for commands in Subject.
5057    (message-check 'subject-cmsg
5058      (if (string-match "^cmsg " (message-fetch-field "subject"))
5059          (y-or-n-p
5060           "The control code \"cmsg\" is in the subject.  Really post? ")
5061        t))
5062    ;; Check long header lines.
5063    (message-check 'long-header-lines
5064      (let ((header nil)
5065            (length 0)
5066            found)
5067        (while (and (not found)
5068                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
5069          (if (> (- (point) (match-beginning 0)) 998)
5070              (setq found t
5071                    length (- (point) (match-beginning 0)))
5072            (setq header (match-string-no-properties 1)))
5073          (forward-line 1))
5074        (if found
5075            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
5076                              header length))
5077          t)))
5078    ;; Check for multiple identical headers.
5079    (message-check 'multiple-headers
5080      (let (found)
5081        (while (and (not found)
5082                    (re-search-forward "^[^ \t:]+: " nil t))
5083          (save-excursion
5084            (or (re-search-forward
5085                 (concat "^"
5086                         (regexp-quote
5087                          (setq found
5088                                (buffer-substring
5089                                 (match-beginning 0) (- (match-end 0) 2))))
5090                         ":")
5091                 nil t)
5092                (setq found nil))))
5093        (if found
5094            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
5095          t)))
5096    ;; Check for Version and Sendsys.
5097    (message-check 'sendsys
5098      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
5099          (y-or-n-p
5100           (format "The article contains a %s command.  Really post? "
5101                   (buffer-substring (match-beginning 0)
5102                                     (1- (match-end 0)))))
5103        t))
5104    ;; See whether we can shorten Followup-To.
5105    (message-check 'shorten-followup-to
5106      (let ((newsgroups (message-fetch-field "newsgroups"))
5107            (followup-to (message-fetch-field "followup-to"))
5108            to)
5109        (when (and newsgroups
5110                   (string-match "," newsgroups)
5111                   (not followup-to)
5112                   (not
5113                    (zerop
5114                     (length
5115                      (setq to (completing-read
5116                                "Followups to (default no Followup-To header): "
5117                                (mapcar #'list
5118                                        (cons "poster"
5119                                              (message-tokenize-header
5120                                               newsgroups)))))))))
5121          (goto-char (point-min))
5122          (insert "Followup-To: " to "\n"))
5123        t))
5124    ;; Check "Shoot me".
5125    (message-check 'shoot
5126      (if (re-search-forward
5127           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
5128          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
5129        t))
5130    ;; Check for Approved.
5131    (message-check 'approved
5132      (if (re-search-forward "^Approved:" nil t)
5133          (y-or-n-p "The article contains an Approved header.  Really post? ")
5134        t))
5135    ;; Check the Message-ID header.
5136    (message-check 'message-id
5137      (let* ((case-fold-search t)
5138             (message-id (message-fetch-field "message-id" t)))
5139        (or (not message-id)
5140            ;; Is there an @ in the ID?
5141            (and (string-match "@" message-id)
5142                 ;; Is there a dot in the ID?
5143                 (string-match "@[^.]*\\." message-id)
5144                 ;; Does the ID end with a dot?
5145                 (not (string-match "\\.>" message-id)))
5146            (y-or-n-p
5147             (format "The Message-ID looks strange: \"%s\".  Really post? "
5148                     message-id)))))
5149    ;; Check the Newsgroups & Followup-To headers.
5150    (message-check 'existing-newsgroups
5151      (let* ((case-fold-search t)
5152             (newsgroups (message-fetch-field "newsgroups"))
5153             (followup-to (message-fetch-field "followup-to"))
5154             (groups (message-tokenize-header
5155                      (if followup-to
5156                          (concat newsgroups "," followup-to)
5157                        newsgroups)))
5158             (post-method (if (functionp message-post-method)
5159                              (funcall message-post-method)
5160                            message-post-method))
5161             ;; KLUDGE to handle nnvirtual groups.  Doing this right
5162             ;; would probably involve a new nnoo function.
5163             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
5164             (method (if (and (consp post-method)
5165                              (eq (car post-method) 'nnvirtual)
5166                              gnus-message-group-art)
5167                         (let ((group (car (nnvirtual-find-group-art
5168                                            (car gnus-message-group-art)
5169                                            (cdr gnus-message-group-art)))))
5170                           (gnus-find-method-for-group group))
5171                       post-method))
5172             (known-groups
5173              (mapcar (lambda (n)
5174                        (gnus-group-name-decode
5175                         (gnus-group-real-name n)
5176                         (gnus-group-name-charset method n)))
5177                      (gnus-groups-from-server method)))
5178             errors)
5179        (while groups
5180          (when (and (not (equal (car groups) "poster"))
5181                     (not (member (car groups) known-groups))
5182                     (not (member (car groups) errors)))
5183            (push (car groups) errors))
5184          (pop groups))
5185        (cond
5186         ;; Gnus is not running.
5187         ((or (not (and (boundp 'gnus-active-hashtb)
5188                        gnus-active-hashtb))
5189              (not (boundp 'gnus-read-active-file)))
5190          t)
5191         ;; We don't have all the group names.
5192         ((and (or (not gnus-read-active-file)
5193                   (eq gnus-read-active-file 'some))
5194               errors)
5195          (y-or-n-p
5196           (format
5197            "Really use %s possibly unknown group%s: %s? "
5198            (if (= (length errors) 1) "this" "these")
5199            (if (= (length errors) 1) "" "s")
5200            (mapconcat 'identity errors ", "))))
5201         ;; There were no errors.
5202         ((not errors)
5203          t)
5204         ;; There are unknown groups.
5205         (t
5206          (y-or-n-p
5207           (format
5208            "Really post to %s unknown group%s: %s? "
5209            (if (= (length errors) 1) "this" "these")
5210            (if (= (length errors) 1) "" "s")
5211            (mapconcat 'identity errors ", ")))))))
5212    ;; Check continuation headers.
5213    (message-check 'continuation-headers
5214      (goto-char (point-min))
5215      (let ((do-posting t))
5216        (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
5217          (goto-char (match-beginning 0))
5218          (if (y-or-n-p "Fix continuation lines? ")
5219              (insert " ")
5220            (forward-line 1)
5221            (unless (y-or-n-p "Send anyway? ")
5222              (setq do-posting nil))))
5223        do-posting))
5224    ;; Check the Newsgroups & Followup-To headers for syntax errors.
5225    (message-check 'valid-newsgroups
5226      (let ((case-fold-search t)
5227            (headers '("Newsgroups" "Followup-To"))
5228            header error)
5229        (while (and headers (not error))
5230          (when (setq header (mail-fetch-field (car headers)))
5231            (if (or
5232                 (not
5233                  (string-match
5234                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
5235                   header))
5236                 (memq
5237                  nil (mapcar
5238                       (lambda (g)
5239                         (not (string-match "\\.\\'\\|\\.\\." g)))
5240                       (message-tokenize-header header ","))))
5241                (setq error t)))
5242          (unless error
5243            (pop headers)))
5244        (if (not error)
5245            t
5246          (y-or-n-p
5247           (format "The %s header looks odd: \"%s\".  Really post? "
5248                   (car headers) header)))))
5249    (message-check 'repeated-newsgroups
5250      (let ((case-fold-search t)
5251            (headers '("Newsgroups" "Followup-To"))
5252            header error groups group)
5253        (while (and headers
5254                    (not error))
5255          (when (setq header (mail-fetch-field (pop headers)))
5256            (setq groups (message-tokenize-header header ","))
5257            (while (setq group (pop groups))
5258              (when (member group groups)
5259                (setq error group
5260                      groups nil)))))
5261        (if (not error)
5262            t
5263          (y-or-n-p
5264           (format "Group %s is repeated in headers.  Really post? " error)))))
5265    ;; Check the From header.
5266    (message-check 'from
5267      (let* ((case-fold-search t)
5268             (from (message-fetch-field "from"))
5269             ad)
5270        (cond
5271         ((not from)
5272          (message "There is no From line.  Posting is denied.")
5273          nil)
5274         ((or (not (string-match
5275                    "@[^\\.]*\\."
5276                    (setq ad (nth 1 (mail-extract-address-components
5277                                     from))))) ;larsi@ifi
5278              (string-match "\\.\\." ad) ;larsi@ifi..uio
5279              (string-match "@\\." ad)   ;larsi@.ifi.uio
5280              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5281              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5282              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
5283          (message
5284           "Denied posting -- the From looks strange: \"%s\"." from)
5285          nil)
5286         ((let ((addresses (rfc822-addresses from)))
5287            ;; `rfc822-addresses' returns a string if parsing fails.
5288            (while (and (consp addresses)
5289                        (not (eq (string-to-char (car addresses)) ?\()))
5290              (setq addresses (cdr addresses)))
5291            addresses)
5292          (message
5293           "Denied posting -- bad From address: \"%s\"." from)
5294          nil)
5295         (t t))))
5296    ;; Check the Reply-To header.
5297    (message-check 'reply-to
5298      (let* ((case-fold-search t)
5299             (reply-to (message-fetch-field "reply-to"))
5300             ad)
5301        (cond
5302         ((not reply-to)
5303          t)
5304         ((string-match "," reply-to)
5305          (y-or-n-p
5306           (format "Multiple Reply-To addresses: \"%s\". Really post? "
5307                   reply-to)))
5308         ((or (not (string-match
5309                    "@[^\\.]*\\."
5310                    (setq ad (nth 1 (mail-extract-address-components
5311                                     reply-to))))) ;larsi@ifi
5312              (string-match "\\.\\." ad) ;larsi@ifi..uio
5313              (string-match "@\\." ad)   ;larsi@.ifi.uio
5314              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5315              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5316              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5317          (y-or-n-p
5318           (format
5319            "The Reply-To looks strange: \"%s\". Really post? "
5320            reply-to)))
5321         (t t))))))
5322
5323 (defun message-check-news-body-syntax ()
5324   (and
5325    ;; Check for long lines.
5326    (message-check 'long-lines
5327      (goto-char (point-min))
5328      (re-search-forward
5329       (concat "^" (regexp-quote mail-header-separator) "$"))
5330      (forward-line 1)
5331      (while (and
5332              (or (looking-at
5333                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
5334                  (let ((p (point)))
5335                    (end-of-line)
5336                    (< (- (point) p) 80)))
5337              (zerop (forward-line 1))))
5338      (or (bolp)
5339          (eobp)
5340          (y-or-n-p
5341           "You have lines longer than 79 characters.  Really post? ")))
5342    ;; Check whether the article is empty.
5343    (message-check 'empty
5344      (goto-char (point-min))
5345      (re-search-forward
5346       (concat "^" (regexp-quote mail-header-separator) "$"))
5347      (forward-line 1)
5348      (let ((b (point)))
5349        (goto-char (point-max))
5350        (re-search-backward message-signature-separator nil t)
5351        (beginning-of-line)
5352        (or (re-search-backward "[^ \n\t]" b t)
5353            (if (message-gnksa-enable-p 'empty-article)
5354                (y-or-n-p "Empty article.  Really post? ")
5355              (message "Denied posting -- Empty article.")
5356              nil))))
5357    ;; Check for control characters.
5358    (message-check 'control-chars
5359      (if (re-search-forward
5360           (mm-string-to-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5361           nil t)
5362          (y-or-n-p
5363           "The article contains control characters.  Really post? ")
5364        t))
5365    ;; Check excessive size.
5366    (message-check 'size
5367      (if (> (buffer-size) 60000)
5368          (y-or-n-p
5369           (format "The article is %d octets long.  Really post? "
5370                   (buffer-size)))
5371        t))
5372    ;; Check whether any new text has been added.
5373    (message-check 'new-text
5374      (or
5375       (not message-checksum)
5376       (not (eq (message-checksum) message-checksum))
5377       (if (message-gnksa-enable-p 'quoted-text-only)
5378           (y-or-n-p
5379            "It looks like no new text has been added.  Really post? ")
5380         (message "Denied posting -- no new text has been added.")
5381         nil)))
5382    ;; Check the length of the signature.
5383    (message-check 'signature
5384      (let (sig-start sig-end)
5385        (goto-char (point-max))
5386        (if (not (re-search-backward message-signature-separator nil t))
5387            t
5388          (setq sig-start (1+ (point-at-eol)))
5389          (setq sig-end
5390                (if (re-search-forward
5391                     "<#/?\\(multipart\\|part\\|external\\|mml\\)" nil t)
5392                    (- (point-at-bol) 1)
5393                  (point-max)))
5394          (if (>= (count-lines sig-start sig-end) 5)
5395              (if (message-gnksa-enable-p 'signature)
5396                  (y-or-n-p
5397                   (format "Signature is excessively long (%d lines).  Really post? "
5398                           (count-lines sig-start sig-end)))
5399                (message "Denied posting -- Excessive signature.")
5400                nil)
5401            t))))
5402    ;; Ensure that text follows last quoted portion.
5403    (message-check 'quoting-style
5404      (goto-char (point-max))
5405      (let ((no-problem t))
5406        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5407          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5408        (if no-problem
5409            t
5410          (if (message-gnksa-enable-p 'quoted-text-only)
5411              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5412            ;; Ensure that
5413            (goto-char (point-min))
5414            (re-search-forward
5415             (concat "^" (regexp-quote mail-header-separator) "$"))
5416            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5417                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5418              (message "Denied posting -- only quoted text.")
5419              nil)))))))
5420
5421 (defun message-checksum ()
5422   "Return a \"checksum\" for the current buffer."
5423   (let ((sum 0))
5424     (save-excursion
5425       (goto-char (point-min))
5426       (re-search-forward
5427        (concat "^" (regexp-quote mail-header-separator) "$"))
5428       (while (not (eobp))
5429         (when (not (looking-at "[ \t\n]"))
5430           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5431                             (char-after))))
5432         (forward-char 1)))
5433     sum))
5434
5435 (defun message-do-fcc ()
5436   "Process Fcc headers in the current buffer."
5437   (let ((case-fold-search t)
5438         (buf (current-buffer))
5439         list file
5440         (mml-externalize-attachments message-fcc-externalize-attachments))
5441     (save-excursion
5442       (save-restriction
5443         (message-narrow-to-headers)
5444         (setq file (message-fetch-field "fcc" t)))
5445       (when file
5446         (set-buffer (get-buffer-create " *message temp*"))
5447         (erase-buffer)
5448         (insert-buffer-substring buf)
5449         (message-encode-message-body)
5450         (save-restriction
5451           (message-narrow-to-headers)
5452           (while (setq file (message-fetch-field "fcc" t))
5453             (push file list)
5454             (message-remove-header "fcc" nil t))
5455           (let ((mail-parse-charset message-default-charset)
5456                 (rfc2047-header-encoding-alist
5457                  (cons '("Newsgroups" . default)
5458                        rfc2047-header-encoding-alist)))
5459             (mail-encode-encoded-word-buffer)))
5460         (goto-char (point-min))
5461         (when (re-search-forward
5462                (concat "^" (regexp-quote mail-header-separator) "$")
5463                nil t)
5464           (replace-match "" t t ))
5465         ;; Process FCC operations.
5466         (while list
5467           (setq file (pop list))
5468           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5469               ;; Pipe the article to the program in question.
5470               (call-process-region (point-min) (point-max) shell-file-name
5471                                    nil nil nil shell-command-switch
5472                                    (match-string 1 file))
5473             ;; Save the article.
5474             (setq file (expand-file-name file))
5475             (unless (file-exists-p (file-name-directory file))
5476               (make-directory (file-name-directory file) t))
5477             (if (and message-fcc-handler-function
5478                      (not (eq message-fcc-handler-function 'rmail-output)))
5479                 (funcall message-fcc-handler-function file)
5480               ;; FIXME this option, rmail-output (also used if
5481               ;; message-fcc-handler-function is nil) is not
5482               ;; documented anywhere AFAICS.  It should work in Emacs
5483               ;; 23; I suspect it does not work in Emacs 22.
5484               ;; FIXME I don't see the need for the two different cases here.
5485               ;; mail-use-rfc822 makes no difference (in Emacs 23),and
5486               ;; the third argument just controls \"Wrote file\" message.
5487               (if (and (file-readable-p file) (mail-file-babyl-p file))
5488                   (rmail-output file 1 nil t)
5489                 (let ((mail-use-rfc822 t))
5490                   (rmail-output file 1 t t))))))
5491         (kill-buffer (current-buffer))))))
5492
5493 (defun message-output (filename)
5494   "Append this article to Unix/babyl mail file FILENAME."
5495   (if (or (and (file-readable-p filename)
5496                (mail-file-babyl-p filename))
5497           ;; gnus-output-to-mail does the wrong thing with live, mbox
5498           ;; Rmail buffers in Emacs 23.
5499           ;; http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=597255
5500           (let ((buff (find-buffer-visiting filename)))
5501             (and buff (with-current-buffer buff
5502                         (eq major-mode 'rmail-mode)))))
5503       (gnus-output-to-rmail filename t)
5504     (gnus-output-to-mail filename t)))
5505
5506 (defun message-cleanup-headers ()
5507   "Do various automatic cleanups of the headers."
5508   ;; Remove empty lines in the header.
5509   (save-restriction
5510     (message-narrow-to-headers)
5511     ;; Remove blank lines.
5512     (while (re-search-forward "^[ \t]*\n" nil t)
5513       (replace-match "" t t))
5514
5515     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5516     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5517     ;; embedded line breaks.
5518     (goto-char (point-min))
5519     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5520       (save-restriction
5521         (narrow-to-region
5522          (point)
5523          (if (re-search-forward "^[^ \t]" nil t)
5524              (match-beginning 0)
5525            (forward-line 1)
5526            (point)))
5527         (goto-char (point-min))
5528         (while (re-search-forward "\n[ \t]+" nil t)
5529           (replace-match " " t t))     ;No line breaks (too confusing)
5530         (goto-char (point-min))
5531         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5532           (replace-match "," t t))
5533         (goto-char (point-min))
5534         ;; Remove trailing commas.
5535         (when (re-search-forward ",+$" nil t)
5536           (replace-match "" t t))))))
5537
5538 (defun message-make-date (&optional now)
5539   "Make a valid data header.
5540 If NOW, use that time instead."
5541   (let ((system-time-locale "C"))
5542     (format-time-string "%a, %d %b %Y %T %z" now)))
5543
5544 (defun message-insert-expires (days)
5545   "Insert the Expires header.  Expiry in DAYS days."
5546   (interactive "NExpire article in how many days? ")
5547   (save-excursion
5548     (message-position-on-field "Expires" "X-Draft-From")
5549     (insert (message-make-expires-date days))))
5550
5551 (defun message-make-expires-date (days)
5552   "Make date string for the Expires header.  Expiry in DAYS days.
5553
5554 In posting styles use `(\"Expires\" (make-expires-date 30))'."
5555   (let* ((cur (decode-time (current-time)))
5556          (nday (+ days (nth 3 cur))))
5557     (setf (nth 3 cur) nday)
5558     (message-make-date (apply 'encode-time cur))))
5559
5560 (defun message-make-message-id ()
5561   "Make a unique Message-ID."
5562   (concat "<" (message-unique-id)
5563           (let ((psubject (save-excursion (message-fetch-field "subject")))
5564                 (psupersedes
5565                  (save-excursion (message-fetch-field "supersedes"))))
5566             (if (or
5567                  (and message-reply-headers
5568                       (mail-header-references message-reply-headers)
5569                       (mail-header-subject message-reply-headers)
5570                       psubject
5571                       (not (string=
5572                             (message-strip-subject-re
5573                              (mail-header-subject message-reply-headers))
5574                             (message-strip-subject-re psubject))))
5575                  (and psupersedes
5576                       (string-match "_-_@" psupersedes)))
5577                 "_-_" ""))
5578           "@" (message-make-fqdn) ">"))
5579
5580 (defvar message-unique-id-char nil)
5581
5582 ;; If you ever change this function, make sure the new version
5583 ;; cannot generate IDs that the old version could.
5584 ;; You might for example insert a "." somewhere (not next to another dot
5585 ;; or string boundary), or modify the "fsf" string.
5586 (defun message-unique-id ()
5587   ;; Don't use microseconds from (current-time), they may be unsupported.
5588   ;; Instead we use this randomly inited counter.
5589   (setq message-unique-id-char
5590         (% (1+ (or message-unique-id-char
5591                    (logand (random most-positive-fixnum) (1- (lsh 1 20)))))
5592            ;; (current-time) returns 16-bit ints,
5593            ;; and 2^16*25 just fits into 4 digits i base 36.
5594            (* 25 25)))
5595   (let ((tm (current-time)))
5596     (concat
5597      (if (or (eq system-type 'ms-dos)
5598              ;; message-number-base36 doesn't handle bigints.
5599              (floatp (user-uid)))
5600          (let ((user (downcase (user-login-name))))
5601            (while (string-match "[^a-z0-9_]" user)
5602              (aset user (match-beginning 0) ?_))
5603            user)
5604        (message-number-base36 (user-uid) -1))
5605      (message-number-base36 (+ (car tm)
5606                                (lsh (% message-unique-id-char 25) 16)) 4)
5607      (message-number-base36 (+ (nth 1 tm)
5608                                (lsh (/ message-unique-id-char 25) 16)) 4)
5609      ;; Append a given name, because while the generated ID is unique
5610      ;; to this newsreader, other newsreaders might otherwise generate
5611      ;; the same ID via another algorithm.
5612      ".fsf")))
5613
5614 (defun message-number-base36 (num len)
5615   (if (if (< len 0)
5616           (<= num 0)
5617         (= len 0))
5618       ""
5619     (concat (message-number-base36 (/ num 36) (1- len))
5620             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5621                                   (% num 36))))))
5622
5623 (defun message-make-organization ()
5624   "Make an Organization header."
5625   (let* ((organization
5626           (when message-user-organization
5627             (if (functionp message-user-organization)
5628                 (funcall message-user-organization)
5629               message-user-organization))))
5630     (with-temp-buffer
5631       (mm-enable-multibyte)
5632       (cond ((stringp organization)
5633              (insert organization))
5634             ((and (eq t organization)
5635                   message-user-organization-file
5636                   (file-exists-p message-user-organization-file))
5637              (insert-file-contents message-user-organization-file)))
5638       (goto-char (point-min))
5639       (while (re-search-forward "[\t\n]+" nil t)
5640         (replace-match "" t t))
5641       (unless (zerop (buffer-size))
5642         (buffer-string)))))
5643
5644 (defun message-make-lines ()
5645   "Count the number of lines and return numeric string."
5646   (save-excursion
5647     (save-restriction
5648       (widen)
5649       (message-goto-body)
5650       (int-to-string (count-lines (point) (point-max))))))
5651
5652 (defun message-make-references ()
5653   "Return the References header for this message."
5654   (when message-reply-headers
5655     (let ((message-id (mail-header-id message-reply-headers))
5656           (references (mail-header-references message-reply-headers)))
5657       (if (or references message-id)
5658           (concat (or references "") (and references " ")
5659                   (or message-id ""))
5660         nil))))
5661
5662 (defun message-make-in-reply-to ()
5663   "Return the In-Reply-To header for this message."
5664   (when message-reply-headers
5665     (let ((from (mail-header-from message-reply-headers))
5666           (date (mail-header-date message-reply-headers))
5667           (msg-id (mail-header-id message-reply-headers)))
5668       (when from
5669         (let ((name (mail-extract-address-components from)))
5670           (concat
5671            msg-id (if msg-id " (")
5672            (if (car name)
5673                (if (string-match "[^\000-\177]" (car name))
5674                    ;; Quote a string containing non-ASCII characters.
5675                    ;; It will make the RFC2047 encoder cause an error
5676                    ;; if there are special characters.
5677                    (mm-with-multibyte-buffer
5678                      (insert (car name))
5679                      (goto-char (point-min))
5680                      (while (search-forward "\"" nil t)
5681                        (when (prog2
5682                                  (backward-char)
5683                                  (zerop (% (skip-chars-backward "\\\\") 2))
5684                                (goto-char (match-beginning 0)))
5685                          (insert "\\"))
5686                        (forward-char))
5687                      ;; Those quotes will be removed by the RFC2047 encoder.
5688                      (concat "\"" (buffer-string) "\""))
5689                  (car name))
5690              (nth 1 name))
5691            "'s message of \""
5692            (if (or (not date) (string= date ""))
5693                "(unknown date)" date)
5694            "\"" (if msg-id ")")))))))
5695
5696 (defun message-make-distribution ()
5697   "Make a Distribution header."
5698   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5699     (cond ((functionp message-distribution-function)
5700            (funcall message-distribution-function))
5701           (t orig-distribution))))
5702
5703 (defun message-make-expires ()
5704   "Return an Expires header based on `message-expires'."
5705   (let ((current (current-time))
5706         (future (* 1.0 message-expires 60 60 24)))
5707     ;; Add the future to current.
5708     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5709     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5710     (message-make-date current)))
5711
5712 (defun message-make-path ()
5713   "Return uucp path."
5714   (let ((login-name (user-login-name)))
5715     (cond ((null message-user-path)
5716            (concat (system-name) "!" login-name))
5717           ((stringp message-user-path)
5718            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5719            (concat message-user-path "!" login-name))
5720           (t login-name))))
5721
5722 (defun message-make-from (&optional name address)
5723   "Make a From header."
5724   (let* ((style message-from-style)
5725          (login (or address (message-make-address)))
5726          (fullname (or name
5727                        (and (boundp 'user-full-name)
5728                             user-full-name)
5729                        (user-full-name))))
5730     (when (string= fullname "&")
5731       (setq fullname (user-login-name)))
5732     (with-temp-buffer
5733       (mm-enable-multibyte)
5734       (cond
5735        ((or (null style)
5736             (equal fullname ""))
5737         (insert login))
5738        ((or (eq style 'angles)
5739             (and (not (eq style 'parens))
5740                  ;; Use angles if no quoting is needed, or if parens would
5741                  ;; need quoting too.
5742                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5743                      (let ((tmp (concat fullname nil)))
5744                        (while (string-match "([^()]*)" tmp)
5745                          (aset tmp (match-beginning 0) ?-)
5746                          (aset tmp (1- (match-end 0)) ?-))
5747                        (string-match "[\\()]" tmp)))))
5748         (insert fullname)
5749         (goto-char (point-min))
5750         ;; Look for a character that cannot appear unquoted
5751         ;; according to RFC 822.
5752         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5753           ;; Quote fullname, escaping specials.
5754           (goto-char (point-min))
5755           (insert "\"")
5756           (while (re-search-forward "[\"\\]" nil 1)
5757             (replace-match "\\\\\\&" t))
5758           (insert "\""))
5759         (insert " <" login ">"))
5760        (t                               ; 'parens or default
5761         (insert login " (")
5762         (let ((fullname-start (point)))
5763           (insert fullname)
5764           (goto-char fullname-start)
5765           ;; RFC 822 says \ and nonmatching parentheses
5766           ;; must be escaped in comments.
5767           ;; Escape every instance of ()\ ...
5768           (while (re-search-forward "[()\\]" nil 1)
5769             (replace-match "\\\\\\&" t))
5770           ;; ... then undo escaping of matching parentheses,
5771           ;; including matching nested parentheses.
5772           (goto-char fullname-start)
5773           (while (re-search-forward
5774                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5775                   nil 1)
5776             (replace-match "\\1(\\3)" t)
5777             (goto-char fullname-start)))
5778         (insert ")")))
5779       (buffer-string))))
5780
5781 (defun message-make-sender ()
5782   "Return the \"real\" user address.
5783 This function tries to ignore all user modifications, and
5784 give as trustworthy answer as possible."
5785   (concat (user-login-name) "@" (system-name)))
5786
5787 (defun message-make-address ()
5788   "Make the address of the user."
5789   (or (message-user-mail-address)
5790       (concat (user-login-name) "@" (message-make-domain))))
5791
5792 (defun message-user-mail-address ()
5793   "Return the pertinent part of `user-mail-address'."
5794   (when (and user-mail-address
5795              (string-match "@.*\\." user-mail-address))
5796     (if (string-match " " user-mail-address)
5797         (nth 1 (mail-extract-address-components user-mail-address))
5798       user-mail-address)))
5799
5800 (defun message-sendmail-envelope-from ()
5801   "Return the envelope from."
5802   (cond ((eq message-sendmail-envelope-from 'header)
5803          (nth 1 (mail-extract-address-components
5804                  (message-fetch-field "from"))))
5805         ((stringp message-sendmail-envelope-from)
5806          message-sendmail-envelope-from)
5807         (t
5808          (message-make-address))))
5809
5810 (defun message-make-fqdn ()
5811   "Return user's fully qualified domain name."
5812   (let* ((system-name (system-name))
5813          (user-mail (message-user-mail-address))
5814          (user-domain
5815           (if (and user-mail
5816                    (string-match "@\\(.*\\)\\'" user-mail))
5817               (match-string 1 user-mail)))
5818          (case-fold-search t))
5819     (cond
5820      ((and message-user-fqdn
5821            (stringp message-user-fqdn)
5822            (string-match message-valid-fqdn-regexp message-user-fqdn)
5823            (not (string-match message-bogus-system-names message-user-fqdn)))
5824       ;; `message-user-fqdn' seems to be valid
5825       message-user-fqdn)
5826      ((and (string-match message-valid-fqdn-regexp system-name)
5827            (not (string-match message-bogus-system-names system-name)))
5828       ;; `system-name' returned the right result.
5829       system-name)
5830      ;; Try `mail-host-address'.
5831      ((and (boundp 'mail-host-address)
5832            (stringp mail-host-address)
5833            (string-match message-valid-fqdn-regexp mail-host-address)
5834            (not (string-match message-bogus-system-names mail-host-address)))
5835       mail-host-address)
5836      ;; We try `user-mail-address' as a backup.
5837      ((and user-domain
5838            (stringp user-domain)
5839            (string-match message-valid-fqdn-regexp user-domain)
5840            (not (string-match message-bogus-system-names user-domain)))
5841       user-domain)
5842      ;; Default to this bogus thing.
5843      (t
5844       (concat system-name
5845               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5846
5847 (defun message-make-domain ()
5848   "Return the domain name."
5849   (or mail-host-address
5850       (message-make-fqdn)))
5851
5852 (defun message-to-list-only ()
5853   "Send a message to the list only.
5854 Remove all addresses but the list address from To and Cc headers."
5855   (interactive)
5856   (let ((listaddr (message-make-mail-followup-to t)))
5857     (when listaddr
5858       (save-excursion
5859         (message-remove-header "to")
5860         (message-remove-header "cc")
5861         (message-position-on-field "To" "X-Draft-From")
5862         (insert listaddr)))))
5863
5864 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5865   "Return the Mail-Followup-To header.
5866 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5867 subscribed address (and not the additional To and Cc header contents)."
5868   (let* ((case-fold-search t)
5869          (to (message-fetch-field "To"))
5870          (cc (message-fetch-field "cc"))
5871          (msg-recipients (concat to (and to cc ", ") cc))
5872          (recipients
5873           (mapcar 'mail-strip-quoted-names
5874                   (message-tokenize-header msg-recipients)))
5875          (file-regexps
5876           (if message-subscribed-address-file
5877               (let (begin end item re)
5878                 (save-excursion
5879                   (with-temp-buffer
5880                     (insert-file-contents message-subscribed-address-file)
5881                     (while (not (eobp))
5882                       (setq begin (point))
5883                       (forward-line 1)
5884                       (setq end (point))
5885                       (if (bolp) (setq end (1- end)))
5886                       (setq item (regexp-quote (buffer-substring begin end)))
5887                       (if re (setq re (concat re "\\|" item))
5888                         (setq re (concat "\\`\\(" item))))
5889                     (and re (list (concat re "\\)\\'"))))))))
5890          (mft-regexps (apply 'append message-subscribed-regexps
5891                              (mapcar 'regexp-quote
5892                                      message-subscribed-addresses)
5893                              file-regexps
5894                              (mapcar 'funcall
5895                                      message-subscribed-address-functions))))
5896     (save-match-data
5897       (let ((list
5898              (loop for recipient in recipients
5899                when (loop for regexp in mft-regexps
5900                       when (string-match regexp recipient) return t)
5901                return recipient)))
5902         (when list
5903           (if only-show-subscribed
5904               list
5905             msg-recipients))))))
5906
5907 (defun message-idna-to-ascii-rhs-1 (header)
5908   "Interactively potentially IDNA encode domain names in HEADER."
5909   (let ((field (message-fetch-field header))
5910         ace)
5911     (when field
5912       (dolist (rhs
5913                (mm-delete-duplicates
5914                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5915                         (mapcar 'downcase
5916                                 (mapcar
5917                                  (lambda (elem)
5918                                    (or (cadr elem)
5919                                        ""))
5920                                  (mail-extract-address-components field t))))))
5921         ;; Note that `rhs' will be "" if the address does not have
5922         ;; the domain part, i.e., if it is a local user's address.
5923         (setq ace (if (string-match "\\`[[:ascii:]]*\\'" rhs)
5924                       rhs
5925                     (downcase (idna-to-ascii rhs))))
5926         (when (and (not (equal rhs ace))
5927                    (or (not (eq message-use-idna 'ask))
5928                        (y-or-n-p (format "Replace %s with %s in %s:? "
5929                                          rhs ace header))))
5930           (goto-char (point-min))
5931           (while (re-search-forward (concat "^" header ":") nil t)
5932             (message-narrow-to-field)
5933             (while (search-forward (concat "@" rhs) nil t)
5934               (replace-match (concat "@" ace) t t))
5935             (goto-char (point-max))
5936             (widen)))))))
5937
5938 (defun message-idna-to-ascii-rhs ()
5939   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5940 See `message-idna-encode'."
5941   (interactive)
5942   (when message-use-idna
5943     (save-excursion
5944       (save-restriction
5945         ;; `message-narrow-to-head' that recognizes only the first empty
5946         ;; line as the message header separator used to be used here.
5947         ;; However, since there is the "--text follows this line--" line
5948         ;; normally, it failed in narrowing to the headers and potentially
5949         ;; caused the IDNA encoding on lines that look like headers in
5950         ;; the message body.
5951         (message-narrow-to-headers-or-head)
5952         (message-idna-to-ascii-rhs-1 "From")
5953         (message-idna-to-ascii-rhs-1 "To")
5954         (message-idna-to-ascii-rhs-1 "Reply-To")
5955         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5956         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5957         (message-idna-to-ascii-rhs-1 "Cc")))))
5958
5959 (defvar Date)
5960 (defvar Message-ID)
5961 (defvar Organization)
5962 (defvar From)
5963 (defvar Path)
5964 (defvar Subject)
5965 (defvar Newsgroups)
5966 (defvar In-Reply-To)
5967 (defvar References)
5968 (defvar To)
5969 (defvar Distribution)
5970 (defvar Lines)
5971 (defvar User-Agent)
5972 (defvar Expires)
5973
5974 (defun message-generate-headers (headers)
5975   "Prepare article HEADERS.
5976 Headers already prepared in the buffer are not modified."
5977   (setq headers (append headers message-required-headers))
5978   (save-restriction
5979     (message-narrow-to-headers)
5980     (let* ((Date (message-make-date))
5981            (Message-ID (message-make-message-id))
5982            (Organization (message-make-organization))
5983            (From (message-make-from))
5984            (Path (message-make-path))
5985            (Subject nil)
5986            (Newsgroups nil)
5987            (In-Reply-To (message-make-in-reply-to))
5988            (References (message-make-references))
5989            (To nil)
5990            (Distribution (message-make-distribution))
5991            (Lines (message-make-lines))
5992            (User-Agent message-newsreader)
5993            (Expires (message-make-expires))
5994            (case-fold-search t)
5995            (optionalp nil)
5996            header value elem header-string)
5997       ;; First we remove any old generated headers.
5998       (let ((headers message-deletable-headers))
5999         (unless (buffer-modified-p)
6000           (setq headers (delq 'Message-ID (copy-sequence headers))))
6001         (while headers
6002           (goto-char (point-min))
6003           (and (re-search-forward
6004                 (concat "^" (symbol-name (car headers)) ": *") nil t)
6005                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
6006                (message-delete-line))
6007           (pop headers)))
6008       ;; Go through all the required headers and see if they are in the
6009       ;; articles already.  If they are not, or are empty, they are
6010       ;; inserted automatically - except for Subject, Newsgroups and
6011       ;; Distribution.
6012       (while headers
6013         (goto-char (point-min))
6014         (setq elem (pop headers))
6015         (if (consp elem)
6016             (if (eq (car elem) 'optional)
6017                 (setq header (cdr elem)
6018                       optionalp t)
6019               (setq header (car elem)))
6020           (setq header elem))
6021         (setq header-string  (if (stringp header)
6022                                  header
6023                                (symbol-name header)))
6024         (when (or (not (re-search-forward
6025                         (concat "^"
6026                                 (regexp-quote (downcase header-string))
6027                                 ":")
6028                         nil t))
6029                   (progn
6030                     ;; The header was found.  We insert a space after the
6031                     ;; colon, if there is none.
6032                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
6033                     ;; Find out whether the header is empty.
6034                     (looking-at "[ \t]*\n[^ \t]")))
6035           ;; So we find out what value we should insert.
6036           (setq value
6037                 (cond
6038                  ((and (consp elem)
6039                        (eq (car elem) 'optional)
6040                        (not (member header-string message-inserted-headers)))
6041                   ;; This is an optional header.  If the cdr of this
6042                   ;; is something that is nil, then we do not insert
6043                   ;; this header.
6044                   (setq header (cdr elem))
6045                   (or (and (functionp (cdr elem))
6046                            (funcall (cdr elem)))
6047                       (and (boundp (cdr elem))
6048                            (symbol-value (cdr elem)))))
6049                  ((consp elem)
6050                   ;; The element is a cons.  Either the cdr is a
6051                   ;; string to be inserted verbatim, or it is a
6052                   ;; function, and we insert the value returned from
6053                   ;; this function.
6054                   (or (and (stringp (cdr elem))
6055                            (cdr elem))
6056                       (and (functionp (cdr elem))
6057                            (funcall (cdr elem)))))
6058                  ((and (boundp header)
6059                        (symbol-value header))
6060                   ;; The element is a symbol.  We insert the value
6061                   ;; of this symbol, if any.
6062                   (symbol-value header))
6063                  ((not (message-check-element
6064                         (intern (downcase (symbol-name header)))))
6065                   ;; We couldn't generate a value for this header,
6066                   ;; so we just ask the user.
6067                   (read-from-minibuffer
6068                    (format "Empty header for %s; enter value: " header)))))
6069           ;; Finally insert the header.
6070           (when (and value
6071                      (not (equal value "")))
6072             (save-excursion
6073               (if (bolp)
6074                   (progn
6075                     ;; This header didn't exist, so we insert it.
6076                     (goto-char (point-max))
6077                     (let ((formatter
6078                            (cdr (assq header message-header-format-alist))))
6079                       (if formatter
6080                           (funcall formatter header value)
6081                         (insert header-string ": " value))
6082                       (push header-string message-inserted-headers)
6083                       (goto-char (message-fill-field))
6084                       ;; We check whether the value was ended by a
6085                       ;; newline.  If not, we insert one.
6086                       (unless (bolp)
6087                         (insert "\n"))
6088                       (forward-line -1)))
6089                 ;; The value of this header was empty, so we clear
6090                 ;; totally and insert the new value.
6091                 (delete-region (point) (point-at-eol))
6092                 ;; If the header is optional, and the header was
6093                 ;; empty, we can't insert it anyway.
6094                 (unless optionalp
6095                   (push header-string message-inserted-headers)
6096                   (insert value)
6097                   (message-fill-field)))
6098               ;; Add the deletable property to the headers that require it.
6099               (and (memq header message-deletable-headers)
6100                    (progn (beginning-of-line) (looking-at "[^:]+: "))
6101                    (add-text-properties
6102                     (point) (match-end 0)
6103                     '(message-deletable t face italic) (current-buffer)))))))
6104       ;; Insert new Sender if the From is strange.
6105       (let ((from (message-fetch-field "from"))
6106             (sender (message-fetch-field "sender"))
6107             (secure-sender (message-make-sender)))
6108         (when (and from
6109                    (not (message-check-element 'sender))
6110                    (not (string=
6111                          (downcase
6112                           (cadr (mail-extract-address-components from)))
6113                          (downcase secure-sender)))
6114                    (or (null sender)
6115                        (not
6116                         (string=
6117                          (downcase
6118                           (cadr (mail-extract-address-components sender)))
6119                          (downcase secure-sender)))))
6120           (goto-char (point-min))
6121           ;; Rename any old Sender headers to Original-Sender.
6122           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
6123             (beginning-of-line)
6124             (insert "Original-")
6125             (beginning-of-line))
6126           (when (or (message-news-p)
6127                     (string-match "@.+\\.." secure-sender))
6128             (insert "Sender: " secure-sender "\n"))))
6129       ;; Check for IDNA
6130       (message-idna-to-ascii-rhs))))
6131
6132 (defun message-insert-courtesy-copy (message)
6133   "Insert a courtesy message in mail copies of combined messages."
6134   (let (newsgroups)
6135     (save-excursion
6136       (save-restriction
6137         (message-narrow-to-headers)
6138         (when (setq newsgroups (message-fetch-field "newsgroups"))
6139           (goto-char (point-max))
6140           (insert "Posted-To: " newsgroups "\n")))
6141       (forward-line 1)
6142       (when message
6143         (cond
6144          ((string-match "%s" message)
6145           (insert (format message newsgroups)))
6146          (t
6147           (insert message)))))))
6148
6149 ;;;
6150 ;;; Setting up a message buffer
6151 ;;;
6152
6153 (defun message-skip-to-next-address ()
6154   (let ((end (save-excursion
6155                (message-next-header)
6156                (point)))
6157         quoted char)
6158     (when (looking-at ",")
6159       (forward-char 1))
6160     (while (and (not (= (point) end))
6161                 (or (not (eq char ?,))
6162                     quoted))
6163       (skip-chars-forward "^,\"" end)
6164       (when (eq (setq char (following-char)) ?\")
6165         (setq quoted (not quoted)))
6166       (unless (= (point) end)
6167         (forward-char 1)))
6168     (skip-chars-forward " \t\n")))
6169
6170 (defun message-split-line ()
6171   "Split current line, moving portion beyond point vertically down.
6172 If the current line has `message-yank-prefix', insert it on the new line."
6173   (interactive "*")
6174   (condition-case nil
6175       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
6176     (error
6177      (split-line))))
6178
6179 (defun message-insert-header (header value)
6180   (insert (capitalize (symbol-name header))
6181           ": "
6182           (if (consp value) (car value) value)))
6183
6184 (defun message-field-name ()
6185   (save-excursion
6186     (goto-char (point-min))
6187     (when (looking-at "\\([^:]+\\):")
6188       (intern (capitalize (match-string 1))))))
6189
6190 (defun message-fill-field ()
6191   (save-excursion
6192     (save-restriction
6193       (message-narrow-to-field)
6194       (let ((field-name (message-field-name)))
6195         (funcall (or (cadr (assq field-name message-field-fillers))
6196                      'message-fill-field-general)))
6197       (point-max))))
6198
6199 (defun message-fill-field-address ()
6200   (let (end last)
6201     (while (not end)
6202       (message-skip-to-next-address)
6203       (cond ((bolp)
6204              (end-of-line 0)
6205              (setq end 1))
6206             ((eobp)
6207              (setq end 0)))
6208       (when (and (> (current-column) 78)
6209                  last)
6210         (save-excursion
6211           (goto-char last)
6212           (delete-char (- (skip-chars-backward " \t")))
6213           (insert "\n\t")))
6214       (setq last (point)))
6215     (forward-line end)))
6216
6217 (defun message-fill-field-general ()
6218   (let ((begin (point))
6219         (fill-column 78)
6220         (fill-prefix "\t"))
6221     (while (and (search-forward "\n" nil t)
6222                 (not (eobp)))
6223       (replace-match " " t t))
6224     (fill-region-as-paragraph begin (point-max))
6225     ;; Tapdance around looong Message-IDs.
6226     (forward-line -1)
6227     (when (looking-at "[ \t]*$")
6228       (message-delete-line))
6229     (goto-char begin)
6230     (search-forward ":" nil t)
6231     (when (looking-at "\n[ \t]+")
6232       (replace-match " " t t))
6233     (goto-char (point-max))))
6234
6235 (defun message-shorten-1 (list cut surplus)
6236   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
6237   (setcdr (nthcdr (- cut 2) list)
6238           (nthcdr (+ (- cut 2) surplus 1) list)))
6239
6240 (defun message-shorten-references (header references)
6241   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
6242 When sending via news, also check that the REFERENCES are less
6243 than 988 characters long, and if they are not, trim them until
6244 they are."
6245   ;; 21 is the number suggested by USAGE.
6246   (let ((maxcount 21)
6247         (count 0)
6248         (cut 2)
6249         refs)
6250     (with-temp-buffer
6251       (insert references)
6252       (goto-char (point-min))
6253       ;; Cons a list of valid references.  GNKSA says we must not include MIDs
6254       ;; with whitespace or missing brackets (7.a "Does not propagate broken
6255       ;; Message-IDs in original References").
6256       (while (re-search-forward "<[^ <]+@[^ <]+>" nil t)
6257         (push (match-string 0) refs))
6258       (setq refs (nreverse refs)
6259             count (length refs)))
6260
6261     ;; If the list has more than MAXCOUNT elements, trim it by
6262     ;; removing the CUTth element and the required number of
6263     ;; elements that follow.
6264     (when (> count maxcount)
6265       (let ((surplus (- count maxcount)))
6266         (message-shorten-1 refs cut surplus)
6267         (decf count surplus)))
6268
6269     ;; When sending via news, make sure the total folded length will
6270     ;; be less than 998 characters.  This is to cater to broken INN
6271     ;; 2.3 which counts the total number of characters in a header
6272     ;; rather than the physical line length of each line, as it should.
6273     ;;
6274     ;; This hack should be removed when it's believed than INN 2.3 is
6275     ;; no longer widely used.
6276     ;;
6277     ;; At this point the headers have not been generated, thus we use
6278     ;; message-this-is-news directly.
6279     (when message-this-is-news
6280       (while (< 998
6281                 (with-temp-buffer
6282                   (message-insert-header
6283                    header (mapconcat #'identity refs " "))
6284                   (buffer-size)))
6285         (message-shorten-1 refs cut 1)))
6286     ;; Finally, collect the references back into a string and insert
6287     ;; it into the buffer.
6288     (message-insert-header header (mapconcat #'identity refs " "))))
6289
6290 (defun message-position-point ()
6291   "Move point to where the user probably wants to find it."
6292   (message-narrow-to-headers)
6293   (cond
6294    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
6295     (search-backward ":" )
6296     (widen)
6297     (forward-char 1)
6298     (if (eq (char-after) ? )
6299         (forward-char 1)
6300       (insert " ")))
6301    (t
6302     (goto-char (point-max))
6303     (widen)
6304     (forward-line 1)
6305     (unless (looking-at "$")
6306       (forward-line 2)))
6307    (sit-for 0)))
6308
6309 (defcustom message-beginning-of-line t
6310   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
6311  goes to beginning of header values."
6312   :version "22.1"
6313   :group 'message-buffers
6314   :link '(custom-manual "(message)Movement")
6315   :type 'boolean)
6316
6317 (defun message-beginning-of-line (&optional n)
6318   "Move point to beginning of header value or to beginning of line.
6319 The prefix argument N is passed directly to `beginning-of-line'.
6320
6321 This command is identical to `beginning-of-line' if point is
6322 outside the message header or if the option `message-beginning-of-line'
6323 is nil.
6324
6325 If point is in the message header and on a (non-continued) header
6326 line, move point to the beginning of the header value or the beginning of line,
6327 whichever is closer.  If point is already at beginning of line, move point to
6328 beginning of header value.  Therefore, repeated calls will toggle point
6329 between beginning of field and beginning of line."
6330   (interactive "p")
6331   (let ((zrs 'zmacs-region-stays))
6332     (when (and (featurep 'xemacs) (interactive-p) (boundp zrs))
6333       (set zrs t)))
6334   (if (and message-beginning-of-line
6335            (message-point-in-header-p))
6336       (let* ((here (point))
6337              (bol (progn (beginning-of-line n) (point)))
6338              (eol (point-at-eol))
6339              (eoh (re-search-forward ": *" eol t)))
6340         (goto-char
6341          (if (and eoh (or (< eoh here) (= bol here)))
6342              eoh bol)))
6343     (beginning-of-line n)))
6344
6345 (defun message-buffer-name (type &optional to group)
6346   "Return a new (unique) buffer name based on TYPE and TO."
6347   (cond
6348    ;; Generate a new buffer name The Message Way.
6349    ((memq message-generate-new-buffers '(unique t))
6350     (generate-new-buffer-name
6351      (concat "*" type
6352              (if to
6353                  (concat " to "
6354                          (or (car (mail-extract-address-components to))
6355                              to) "")
6356                "")
6357              (if (and group (not (string= group ""))) (concat " on " group) "")
6358              "*")))
6359    ;; Check whether `message-generate-new-buffers' is a function,
6360    ;; and if so, call it.
6361    ((functionp message-generate-new-buffers)
6362     (funcall message-generate-new-buffers type to group))
6363    ((eq message-generate-new-buffers 'unsent)
6364     (generate-new-buffer-name
6365      (concat "*unsent " type
6366              (if to
6367                  (concat " to "
6368                          (or (car (mail-extract-address-components to))
6369                              to) "")
6370                "")
6371              (if (and group (not (string= group ""))) (concat " on " group) "")
6372              "*")))
6373    ;; Search for the existing message buffer with the specified name.
6374    (t
6375     (let* ((new (if (eq message-generate-new-buffers 'standard)
6376                     (generate-new-buffer-name (concat "*" type " message*"))
6377                   (let ((message-generate-new-buffers 'unique))
6378                     (message-buffer-name type to group))))
6379            (regexp (concat "\\`"
6380                            (regexp-quote
6381                             (if (string-match "<[0-9]+>\\'" new)
6382                                 (substring new 0 (match-beginning 0))
6383                               new))
6384                            "\\(?:<\\([0-9]+\\)>\\)?\\'"))
6385            (case-fold-search nil))
6386       (or (cdar
6387            (last
6388             (sort
6389              (delq nil
6390                    (mapcar
6391                     (lambda (b)
6392                       (when (and (string-match regexp (setq b (buffer-name b)))
6393                                  (eq (with-current-buffer b major-mode)
6394                                      'message-mode))
6395                         (cons (string-to-number (or (match-string 1 b) "1"))
6396                               b)))
6397                     (buffer-list)))
6398              'car-less-than-car)))
6399           new)))))
6400
6401 (defun message-pop-to-buffer (name &optional switch-function)
6402   "Pop to buffer NAME, and warn if it already exists and is modified."
6403   (let ((buffer (get-buffer name)))
6404     (if (and buffer
6405              (buffer-name buffer))
6406         (let ((window (get-buffer-window buffer 0)))
6407           (if window
6408               ;; Raise the frame already displaying the message buffer.
6409               (progn
6410                 (gnus-select-frame-set-input-focus (window-frame window))
6411                 (select-window window))
6412             (funcall (or switch-function #'pop-to-buffer) buffer)
6413             (set-buffer buffer))
6414           (when (and (buffer-modified-p)
6415                      (not (prog1
6416                               (y-or-n-p
6417                                "Message already being composed; erase? ")
6418                             (message nil))))
6419             (error "Message being composed")))
6420       (funcall (or switch-function
6421                    (if (fboundp #'pop-to-buffer-same-window)
6422                        #'pop-to-buffer-same-window
6423                      #'pop-to-buffer))
6424                name)
6425       (set-buffer name))
6426     (erase-buffer)
6427     (message-mode)))
6428
6429 (defun message-do-send-housekeeping ()
6430   "Kill old message buffers."
6431   ;; We might have sent this buffer already.  Delete it from the
6432   ;; list of buffers.
6433   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6434   (while (and message-max-buffers
6435               message-buffer-list
6436               (>= (length message-buffer-list) message-max-buffers))
6437     ;; Kill the oldest buffer -- unless it has been changed.
6438     (let ((buffer (pop message-buffer-list)))
6439       (when (and (buffer-name buffer)
6440                  (not (buffer-modified-p buffer)))
6441         (kill-buffer buffer))))
6442   ;; Rename the buffer.
6443   (if message-send-rename-function
6444       (funcall message-send-rename-function)
6445     (message-default-send-rename-function))
6446   ;; Push the current buffer onto the list.
6447   (when message-max-buffers
6448     (setq message-buffer-list
6449           (nconc message-buffer-list (list (current-buffer))))))
6450
6451 (defun message-default-send-rename-function ()
6452   ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6453   (when (string-match
6454          "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6455          (buffer-name))
6456     (let ((name (match-string 2 (buffer-name)))
6457           to group)
6458       (if (not (or (null name)
6459                    (string-equal name "mail")
6460                    (string-equal name "posting")))
6461           (setq name (concat "*sent " name "*"))
6462         (message-narrow-to-headers)
6463         (setq to (message-fetch-field "to"))
6464         (setq group (message-fetch-field "newsgroups"))
6465         (widen)
6466         (setq name
6467               (cond
6468                (to (concat "*sent mail to "
6469                            (or (car (mail-extract-address-components to))
6470                                to) "*"))
6471                ((and group (not (string= group "")))
6472                 (concat "*sent posting on " group "*"))
6473                (t "*sent mail*"))))
6474       (unless (string-equal name (buffer-name))
6475         (rename-buffer name t)))))
6476
6477 (defun message-mail-user-agent ()
6478   (let ((mua (cond
6479               ((not message-mail-user-agent) nil)
6480               ((eq message-mail-user-agent t) mail-user-agent)
6481               (t message-mail-user-agent))))
6482     (if (memq mua '(message-user-agent gnus-user-agent))
6483         nil
6484       mua)))
6485
6486 ;; YANK-ACTION, if non-nil, can be a buffer or a yank action of the
6487 ;; form (FUNCTION . ARGS).
6488 (defun message-setup (headers &optional yank-action actions
6489                               continue switch-function return-action)
6490   (let ((mua (message-mail-user-agent))
6491         subject to field)
6492     (if (not (and message-this-is-mail mua))
6493         (message-setup-1 headers yank-action actions return-action)
6494       (setq headers (copy-sequence headers))
6495       (setq field (assq 'Subject headers))
6496       (when field
6497         (setq subject (cdr field))
6498         (setq headers (delq field headers)))
6499       (setq field (assq 'To headers))
6500       (when field
6501         (setq to (cdr field))
6502         (setq headers (delq field headers)))
6503       (let ((mail-user-agent mua))
6504         (compose-mail to subject
6505                       (mapcar (lambda (item)
6506                                 (cons
6507                                  (format "%s" (car item))
6508                                  (cdr item)))
6509                               headers)
6510                       continue switch-function
6511                       (if (bufferp yank-action)
6512                           (list 'insert-buffer yank-action)
6513                         yank-action)
6514                       actions)))))
6515
6516 (defun message-headers-to-generate (headers included-headers excluded-headers)
6517   "Return a list that includes all headers from HEADERS.
6518 If INCLUDED-HEADERS is a list, just include those headers.  If it is
6519 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6520 are not included."
6521   (let ((result nil)
6522         header-name)
6523     (dolist (header headers)
6524       (setq header-name (cond
6525                          ((and (consp header)
6526                                (eq (car header) 'optional))
6527                           ;; On the form (optional . Header)
6528                           (cdr header))
6529                          ((consp header)
6530                           ;; On the form (Header . function)
6531                           (car header))
6532                          (t
6533                           ;; Just a Header.
6534                           header)))
6535       (when (and (not (memq header-name excluded-headers))
6536                  (or (eq included-headers t)
6537                      (memq header-name included-headers)))
6538         (push header result)))
6539     (nreverse result)))
6540
6541 (defun message-setup-1 (headers &optional yank-action actions return-action)
6542   (dolist (action actions)
6543     (condition-case nil
6544         (add-to-list 'message-send-actions
6545                      `(apply ',(car action) ',(cdr action)))))
6546   (setq message-return-action return-action)
6547   (setq message-reply-buffer
6548         (if (and (consp yank-action)
6549                  (eq (car yank-action) 'insert-buffer))
6550             (nth 1 yank-action)
6551           yank-action))
6552   (goto-char (point-min))
6553   ;; Insert all the headers.
6554   (mail-header-format
6555    (let ((h headers)
6556          (alist message-header-format-alist))
6557      (while h
6558        (unless (assq (caar h) message-header-format-alist)
6559          (push (list (caar h)) alist))
6560        (pop h))
6561      alist)
6562    headers)
6563   (delete-region (point) (progn (forward-line -1) (point)))
6564   (when message-default-headers
6565     (insert
6566      (if (functionp message-default-headers)
6567          (funcall message-default-headers)
6568        message-default-headers))
6569     (or (bolp) (insert ?\n)))
6570   (insert (concat mail-header-separator "\n"))
6571   (forward-line -1)
6572   ;; If a crash happens while replying, the auto-save file would *not* have a
6573   ;; `References:' header if `message-generate-headers-first' was nil.
6574   ;; Therefore, always generate it first.
6575   (let ((message-generate-headers-first
6576          (if (eq message-generate-headers-first t)
6577              t
6578            (append message-generate-headers-first '(References)))))
6579     (when (message-news-p)
6580       (when message-default-news-headers
6581         (insert message-default-news-headers)
6582         (or (bolp) (insert ?\n)))
6583       (message-generate-headers
6584        (message-headers-to-generate
6585         (append message-required-news-headers
6586                 message-required-headers)
6587         message-generate-headers-first
6588         '(Lines Subject))))
6589     (when (message-mail-p)
6590       (when message-default-mail-headers
6591         (insert message-default-mail-headers)
6592         (or (bolp) (insert ?\n)))
6593       (message-generate-headers
6594        (message-headers-to-generate
6595         (append message-required-mail-headers
6596                 message-required-headers)
6597         message-generate-headers-first
6598         '(Lines Subject)))))
6599   (run-hooks 'message-signature-setup-hook)
6600   (message-insert-signature)
6601   (save-restriction
6602     (message-narrow-to-headers)
6603     (run-hooks 'message-header-setup-hook))
6604   (setq buffer-undo-list nil)
6605   (when message-generate-hashcash
6606     ;; Generate hashcash headers for recipients already known
6607     (mail-add-payment-async))
6608   ;; Gnus posting styles are applied via buffer-local `message-setup-hook'
6609   ;; values.
6610   (run-hooks 'message-setup-hook)
6611   ;; Do this last to give it precedence over posting styles, etc.
6612   (when (message-mail-p)
6613     (save-restriction
6614       (message-narrow-to-headers)
6615       (if message-alternative-emails
6616           (message-use-alternative-email-as-from))))
6617   (message-position-point)
6618   ;; Allow correct handling of `message-checksum' in `message-yank-original':
6619   (set-buffer-modified-p nil)
6620   (undo-boundary)
6621   ;; rmail-start-mail expects message-mail to return t (Bug#9392)
6622   t)
6623
6624 (defun message-set-auto-save-file-name ()
6625   "Associate the message buffer with a file in the drafts directory."
6626   (when message-auto-save-directory
6627     (unless (file-directory-p
6628              (directory-file-name message-auto-save-directory))
6629       (make-directory message-auto-save-directory t))
6630     (if (gnus-alive-p)
6631         (setq message-draft-article
6632               (nndraft-request-associate-buffer "drafts"))
6633
6634       ;; If Gnus were alive, draft messages would be saved in the drafts folder.
6635       ;; But Gnus is not alive, so arrange to save the draft message in a
6636       ;; regular file in message-auto-save-directory.  Append a unique
6637       ;; time-based suffix to the filename to allow multiple drafts to be saved
6638       ;; simultaneously without overwriting each other (which mimics the
6639       ;; functionality of the Gnus drafts folder).
6640       (setq buffer-file-name (expand-file-name
6641                               (concat
6642                               (if (memq system-type
6643                                         '(ms-dos windows-nt cygwin))
6644                                   "message"
6645                                 "*message*")
6646                                (format-time-string "-%Y%m%d-%H%M%S"))
6647                               message-auto-save-directory))
6648       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6649     (clear-visited-file-modtime)
6650     (setq buffer-file-coding-system message-draft-coding-system)))
6651
6652 (defun message-disassociate-draft ()
6653   "Disassociate the message buffer from the drafts directory."
6654   (when message-draft-article
6655     (nndraft-request-expire-articles
6656      (list message-draft-article) "drafts" nil t)))
6657
6658 (defun message-insert-headers ()
6659   "Generate the headers for the article."
6660   (interactive)
6661   (save-excursion
6662     (save-restriction
6663       (message-narrow-to-headers)
6664       (when (message-news-p)
6665         (message-generate-headers
6666          (delq 'Lines
6667                (delq 'Subject
6668                      (copy-sequence message-required-news-headers)))))
6669       (when (message-mail-p)
6670         (message-generate-headers
6671          (delq 'Lines
6672                (delq 'Subject
6673                      (copy-sequence message-required-mail-headers))))))))
6674
6675 \f
6676
6677 ;;;
6678 ;;; Commands for interfacing with message
6679 ;;;
6680
6681 ;;;###autoload
6682 (defun message-mail (&optional to subject other-headers continue
6683                                switch-function yank-action send-actions
6684                                return-action &rest ignored)
6685   "Start editing a mail message to be sent.
6686 OTHER-HEADERS is an alist of header/value pairs.  CONTINUE says whether
6687 to continue editing a message already being composed.  SWITCH-FUNCTION
6688 is a function used to switch to and display the mail buffer."
6689   (interactive)
6690   (let ((message-this-is-mail t))
6691     (unless (message-mail-user-agent)
6692       (message-pop-to-buffer
6693        ;; Search for the existing message buffer if `continue' is non-nil.
6694        (let ((message-generate-new-buffers
6695               (when (or (not continue)
6696                         (eq message-generate-new-buffers 'standard)
6697                         (functionp message-generate-new-buffers))
6698                 message-generate-new-buffers)))
6699          (message-buffer-name "mail" to))
6700        switch-function))
6701     (message-setup
6702      (nconc
6703       `((To . ,(or to "")) (Subject . ,(or subject "")))
6704       ;; C-h f compose-mail says that headers should be specified as
6705       ;; (string . value); however all the rest of message expects
6706       ;; headers to be symbols, not strings (eg message-header-format-alist).
6707       ;; http://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
6708       ;; We need to convert any string input, eg from rmail-start-mail.
6709       (dolist (h other-headers other-headers)
6710         (if (stringp (car h)) (setcar h (intern (capitalize (car h)))))))
6711      yank-action send-actions continue switch-function
6712      return-action)))
6713
6714 ;;;###autoload
6715 (defun message-news (&optional newsgroups subject)
6716   "Start editing a news article to be sent."
6717   (interactive)
6718   (let ((message-this-is-news t))
6719     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6720     (message-setup `((Newsgroups . ,(or newsgroups ""))
6721                      (Subject . ,(or subject ""))))))
6722
6723 (defun message-alter-recipients-discard-bogus-full-name (addrcell)
6724   "Discard mail address in full names.
6725 When the full name in reply headers contains the mail
6726 address (e.g. \"foo@bar <foo@bar>\"), discard full name.
6727 ADDRCELL is a cons cell where the car is the mail address and the
6728 cdr is the complete address (full name and mail address)."
6729   (if (string-match (concat (regexp-quote (car addrcell)) ".*"
6730                             (regexp-quote (car addrcell)))
6731                     (cdr addrcell))
6732       (cons (car addrcell) (car addrcell))
6733     addrcell))
6734
6735 (defcustom message-alter-recipients-function nil
6736   "Function called to allow alteration of reply header structures.
6737 It is called in `message-get-reply-headers' for each recipient.
6738 The function is called with one parameter, a cons cell ..."
6739   :type '(choice (const :tag "None" nil)
6740                  (const :tag "Discard bogus full name"
6741                         message-alter-recipients-discard-bogus-full-name)
6742                  function)
6743   :version "23.1" ;; No Gnus
6744   :group 'message-headers)
6745
6746 (defun message-get-reply-headers (wide &optional to-address address-headers)
6747   (let (follow-to mct never-mct to cc author mft recipients extra)
6748     ;; Find all relevant headers we need.
6749     (save-restriction
6750       (message-narrow-to-headers-or-head)
6751       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6752       ;; message-header-synonyms.
6753       (setq to (or (message-fetch-field "to")
6754                    (and (loop for synonym in message-header-synonyms
6755                               when (memq 'Original-To synonym)
6756                               return t)
6757                         (message-fetch-field "original-to")))
6758             cc (message-fetch-field "cc")
6759             extra (when message-extra-wide-headers
6760                     (mapconcat 'identity
6761                                (mapcar 'message-fetch-field
6762                                        message-extra-wide-headers)
6763                                ", "))
6764             mct (message-fetch-field "mail-copies-to")
6765             author (or (message-fetch-field "mail-reply-to")
6766                        (message-fetch-field "reply-to"))
6767             mft (and message-use-mail-followup-to
6768                      (message-fetch-field "mail-followup-to")))
6769       ;; Make sure this message goes to the author if this is a wide
6770       ;; reply, since Reply-To address may be a list address a mailing
6771       ;; list server added.
6772       (when (and wide author)
6773         (setq cc (concat author ", " cc)))
6774       (when (or wide (not author))
6775         (setq author (or (message-fetch-field "from") ""))))
6776
6777     ;; Handle special values of Mail-Copies-To.
6778     (when mct
6779       (cond ((or (equal (downcase mct) "never")
6780                  (equal (downcase mct) "nobody"))
6781              (setq never-mct t)
6782              (setq mct nil))
6783             ((or (equal (downcase mct) "always")
6784                  (equal (downcase mct) "poster"))
6785              (setq mct author))))
6786
6787     (save-match-data
6788       ;; Build (textual) list of new recipient addresses.
6789       (cond
6790        (to-address
6791         (setq recipients (concat ", " to-address))
6792         ;; If the author explicitly asked for a copy, we don't deny it to them.
6793         (if mct (setq recipients (concat recipients ", " mct))))
6794        ((not wide)
6795         (setq recipients (concat ", " author)))
6796        (address-headers
6797         (dolist (header address-headers)
6798           (let ((value (message-fetch-field header)))
6799             (when value
6800               (setq recipients (concat recipients ", " value))))))
6801        ((and mft
6802              (string-match "[^ \t,]" mft)
6803              (or (not (eq message-use-mail-followup-to 'ask))
6804                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6805 You should normally obey the Mail-Followup-To: header.  In this
6806 article, it has the value of
6807
6808 " mft "
6809
6810 which directs your response to " (if (string-match "," mft)
6811                                      "the specified addresses"
6812                                    "that address only") ".
6813
6814 Most commonly, Mail-Followup-To is used by a mailing list poster to
6815 express that responses should be sent to just the list, and not the
6816 poster as well.
6817
6818 If a message is posted to several mailing lists, Mail-Followup-To may
6819 also be used to direct the following discussion to one list only,
6820 because discussions that are spread over several lists tend to be
6821 fragmented and very difficult to follow.
6822
6823 Also, some source/announcement lists are not intended for discussion;
6824 responses here are directed to other addresses.
6825
6826 You may customize the variable `message-use-mail-followup-to', if you
6827 want to get rid of this query permanently.")))
6828         (setq recipients (concat ", " mft)))
6829        (t
6830         (setq recipients (if never-mct "" (concat ", " author)))
6831         (if to (setq recipients (concat recipients ", " to)))
6832         (if cc (setq recipients (concat recipients ", " cc)))
6833         (if extra (setq recipients (concat recipients ", " extra)))
6834         (if mct (setq recipients (concat recipients ", " mct)))))
6835       (if (>= (length recipients) 2)
6836           ;; Strip the leading ", ".
6837           (setq recipients (substring recipients 2)))
6838       ;; Squeeze whitespace.
6839       (while (string-match "[ \t][ \t]+" recipients)
6840         (setq recipients (replace-match " " t t recipients)))
6841       ;; Remove addresses that match `mail-dont-reply-to-names'.
6842       (let ((mail-dont-reply-to-names (message-dont-reply-to-names)))
6843         (setq recipients (mail-dont-reply-to recipients)))
6844       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6845       (if (string-equal recipients "")
6846           (setq recipients author))
6847       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6848       (setq recipients
6849             (mapcar
6850              (lambda (addr)
6851                (if message-alter-recipients-function
6852                    (funcall message-alter-recipients-function
6853                             (cons (downcase (mail-strip-quoted-names addr))
6854                                   addr))
6855                  (cons (downcase (mail-strip-quoted-names addr)) addr)))
6856              (message-tokenize-header recipients)))
6857       ;; Remove all duplicates.
6858       (let ((s recipients))
6859         (while s
6860           (let ((address (car (pop s))))
6861             (while (assoc address s)
6862               (setq recipients (delq (assoc address s) recipients)
6863                     s (delq (assoc address s) s))))))
6864
6865       ;; Remove hierarchical lists that are contained within each other,
6866       ;; if message-hierarchical-addresses is defined.
6867       (when message-hierarchical-addresses
6868         (let ((plain-addrs (mapcar 'car recipients))
6869               subaddrs recip)
6870           (while plain-addrs
6871             (setq subaddrs (assoc (car plain-addrs)
6872                                   message-hierarchical-addresses)
6873                   plain-addrs (cdr plain-addrs))
6874             (when subaddrs
6875               (setq subaddrs (cdr subaddrs))
6876               (while subaddrs
6877                 (setq recip (assoc (car subaddrs) recipients)
6878                       subaddrs (cdr subaddrs))
6879                 (if recip
6880                     (setq recipients (delq recip recipients))))))))
6881
6882       (setq recipients (message-prune-recipients recipients))
6883
6884       ;; Build the header alist.  Allow the user to be asked whether
6885       ;; or not to reply to all recipients in a wide reply.
6886       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6887       (when (and recipients
6888                  (or (not message-wide-reply-confirm-recipients)
6889                      (y-or-n-p "Reply to all recipients? ")))
6890         (setq recipients (mapconcat
6891                           (lambda (addr) (cdr addr)) recipients ", "))
6892         (if (string-match "^ +" recipients)
6893             (setq recipients (substring recipients (match-end 0))))
6894         (push (cons 'Cc recipients) follow-to)))
6895     follow-to))
6896
6897 (defun message-prune-recipients (recipients)
6898   (dolist (rule message-prune-recipient-rules)
6899     (let ((match (car rule))
6900           dup-match
6901           address)
6902       (dolist (recipient recipients)
6903         (setq address (car recipient))
6904         (when (string-match match address)
6905           (setq dup-match (replace-match (cadr rule) nil nil address))
6906           (dolist (recipient recipients)
6907             ;; Don't delete the address that triggered this.
6908             (when (and (not (eq address (car recipient)))
6909                        (string-match dup-match (car recipient)))
6910               (setq recipients (delq recipient recipients))))))))
6911   recipients)
6912
6913 (defcustom message-simplify-subject-functions
6914   '(message-strip-list-identifiers
6915     message-strip-subject-re
6916     message-strip-subject-trailing-was
6917     message-strip-subject-encoded-words)
6918   "List of functions taking a string argument that simplify subjects.
6919 The functions are applied when replying to a message.
6920
6921 Useful functions to put in this list include:
6922 `message-strip-list-identifiers', `message-strip-subject-re',
6923 `message-strip-subject-trailing-was', and
6924 `message-strip-subject-encoded-words'."
6925   :version "22.1" ;; Gnus 5.10.9
6926   :group 'message-various
6927   :type '(repeat function))
6928
6929 (defun message-simplify-subject (subject &optional functions)
6930   "Return simplified SUBJECT."
6931   (unless functions
6932     ;; Simplify fully:
6933     (setq functions message-simplify-subject-functions))
6934   (when (and (memq 'message-strip-list-identifiers functions)
6935              gnus-list-identifiers)
6936     (setq subject (message-strip-list-identifiers subject)))
6937   (when (memq 'message-strip-subject-re functions)
6938     (setq subject (concat "Re: " (message-strip-subject-re subject))))
6939   (when (and (memq 'message-strip-subject-trailing-was functions)
6940              message-subject-trailing-was-query)
6941     (setq subject (message-strip-subject-trailing-was subject)))
6942   (when (memq 'message-strip-subject-encoded-words functions)
6943     (setq subject (message-strip-subject-encoded-words subject)))
6944   subject)
6945
6946 ;;;###autoload
6947 (defun message-reply (&optional to-address wide switch-function)
6948   "Start editing a reply to the article in the current buffer."
6949   (interactive)
6950   (require 'gnus-sum)                   ; for gnus-list-identifiers
6951   (let ((cur (current-buffer))
6952         from subject date
6953         references message-id follow-to
6954         (inhibit-point-motion-hooks t)
6955         (message-this-is-mail t)
6956         gnus-warning)
6957     (save-restriction
6958       (message-narrow-to-head-1)
6959       ;; Allow customizations to have their say.
6960       (if (not wide)
6961           ;; This is a regular reply.
6962           (when (functionp message-reply-to-function)
6963             (save-excursion
6964               (setq follow-to (funcall message-reply-to-function))))
6965         ;; This is a followup.
6966         (when (functionp message-wide-reply-to-function)
6967           (save-excursion
6968             (setq follow-to
6969                   (funcall message-wide-reply-to-function)))))
6970       (setq message-id (message-fetch-field "message-id" t)
6971             references (message-fetch-field "references")
6972             date (message-fetch-field "date")
6973             from (or (message-fetch-field "from") "nobody")
6974             subject (or (message-fetch-field "subject") "none"))
6975
6976       ;; Strip list identifiers, "Re: ", and "was:"
6977       (setq subject (message-simplify-subject subject))
6978
6979       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6980                  (string-match "<[^>]+>" gnus-warning))
6981         (setq message-id (match-string 0 gnus-warning)))
6982
6983       (unless follow-to
6984         (setq follow-to (message-get-reply-headers wide to-address))))
6985
6986     (let ((headers
6987            `((Subject . ,subject)
6988              ,@follow-to)))
6989       (unless (message-mail-user-agent)
6990         (message-pop-to-buffer
6991          (message-buffer-name
6992           (if wide "wide reply" "reply") from
6993           (if wide to-address nil))
6994          switch-function))
6995       (setq message-reply-headers
6996             (vector 0 (cdr (assq 'Subject headers))
6997                     from date message-id references 0 0 ""))
6998       (message-setup headers cur))))
6999
7000 ;;;###autoload
7001 (defun message-wide-reply (&optional to-address)
7002   "Make a \"wide\" reply to the message in the current buffer."
7003   (interactive)
7004   (message-reply to-address t))
7005
7006 ;;;###autoload
7007 (defun message-followup (&optional to-newsgroups)
7008   "Follow up to the message in the current buffer.
7009 If TO-NEWSGROUPS, use that as the new Newsgroups line."
7010   (interactive)
7011   (require 'gnus-sum)                   ; for gnus-list-identifiers
7012   (let ((cur (current-buffer))
7013         from subject date reply-to mrt mct
7014         references message-id follow-to
7015         (inhibit-point-motion-hooks t)
7016         (message-this-is-news t)
7017         followup-to distribution newsgroups gnus-warning posted-to)
7018     (save-restriction
7019       (narrow-to-region
7020        (goto-char (point-min))
7021        (if (search-forward "\n\n" nil t)
7022            (1- (point))
7023          (point-max)))
7024       (when (functionp message-followup-to-function)
7025         (setq follow-to
7026               (funcall message-followup-to-function)))
7027       (setq from (message-fetch-field "from")
7028             date (message-fetch-field "date")
7029             subject (or (message-fetch-field "subject") "none")
7030             references (message-fetch-field "references")
7031             message-id (message-fetch-field "message-id" t)
7032             followup-to (message-fetch-field "followup-to")
7033             newsgroups (message-fetch-field "newsgroups")
7034             posted-to (message-fetch-field "posted-to")
7035             reply-to (message-fetch-field "reply-to")
7036             mrt (message-fetch-field "mail-reply-to")
7037             distribution (message-fetch-field "distribution")
7038             mct (message-fetch-field "mail-copies-to"))
7039       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
7040                  (string-match "<[^>]+>" gnus-warning))
7041         (setq message-id (match-string 0 gnus-warning)))
7042       ;; Remove bogus distribution.
7043       (when (and (stringp distribution)
7044                  (let ((case-fold-search t))
7045                    (string-match "world" distribution)))
7046         (setq distribution nil))
7047       ;; Strip list identifiers, "Re: ", and "was:"
7048       (setq subject (message-simplify-subject subject))
7049       (widen))
7050
7051     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
7052
7053     (setq message-reply-headers
7054           (vector 0 subject from date message-id references 0 0 ""))
7055
7056     (message-setup
7057      `((Subject . ,subject)
7058        ,@(cond
7059           (to-newsgroups
7060            (list (cons 'Newsgroups to-newsgroups)))
7061           (follow-to follow-to)
7062           ((and followup-to message-use-followup-to)
7063            (list
7064             (cond
7065              ((equal (downcase followup-to) "poster")
7066               (if (or (eq message-use-followup-to 'use)
7067                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
7068 You should normally obey the Followup-To: header.
7069
7070 `Followup-To: poster' sends your response via e-mail instead of news.
7071
7072 A typical situation where `Followup-To: poster' is used is when the poster
7073 does not read the newsgroup, so he wouldn't see any replies sent to it.
7074
7075 You may customize the variable `message-use-followup-to', if you
7076 want to get rid of this query permanently."))
7077                   (progn
7078                     (setq message-this-is-news nil)
7079                     (cons 'To (or mrt reply-to from "")))
7080                 (cons 'Newsgroups newsgroups)))
7081              (t
7082               (if (or (equal followup-to newsgroups)
7083                       (not (eq message-use-followup-to 'ask))
7084                       (message-y-or-n-p
7085                        (concat "Obey Followup-To: " followup-to "? ") t "\
7086 You should normally obey the Followup-To: header.
7087
7088         `Followup-To: " followup-to "'
7089 directs your response to " (if (string-match "," followup-to)
7090                                "the specified newsgroups"
7091                              "that newsgroup only") ".
7092
7093 If a message is posted to several newsgroups, Followup-To is often
7094 used to direct the following discussion to one newsgroup only,
7095 because discussions that are spread over several newsgroup tend to
7096 be fragmented and very difficult to follow.
7097
7098 Also, some source/announcement newsgroups are not intended for discussion;
7099 responses here are directed to other newsgroups.
7100
7101 You may customize the variable `message-use-followup-to', if you
7102 want to get rid of this query permanently."))
7103                   (cons 'Newsgroups followup-to)
7104                 (cons 'Newsgroups newsgroups))))))
7105           (posted-to
7106            `((Newsgroups . ,posted-to)))
7107           (t
7108            `((Newsgroups . ,newsgroups))))
7109        ,@(and distribution (list (cons 'Distribution distribution)))
7110        ,@(when (and mct
7111                     (not (or (equal (downcase mct) "never")
7112                              (equal (downcase mct) "nobody"))))
7113            (list (cons 'Cc (if (or (equal (downcase mct) "always")
7114                                    (equal (downcase mct) "poster"))
7115                                (or mrt reply-to from "")
7116                              mct)))))
7117
7118      cur)))
7119
7120 (defun message-is-yours-p ()
7121   "Non-nil means current article is yours.
7122 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
7123 are yours except those that have Cancel-Lock header not belonging to you.
7124 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
7125 regexp to match all of yours addresses."
7126   ;; Canlock-logic as suggested by Per Abrahamsen
7127   ;; <abraham@dina.kvl.dk>
7128   ;;
7129   ;; IF article has cancel-lock THEN
7130   ;;   IF we can verify it THEN
7131   ;;     issue cancel
7132   ;;   ELSE
7133   ;;     error: cancellock: article is not yours
7134   ;; ELSE
7135   ;;   Use old rules, comparing sender...
7136   (save-excursion
7137     (save-restriction
7138       (message-narrow-to-head-1)
7139       (if (and (message-fetch-field "Cancel-Lock")
7140                (message-gnksa-enable-p 'canlock-verify))
7141           (if (null (canlock-verify))
7142               t
7143             (error "Failed to verify Cancel-lock: This article is not yours"))
7144         (let (sender from)
7145           (or
7146            (message-gnksa-enable-p 'cancel-messages)
7147            (and (setq sender (message-fetch-field "sender"))
7148                 (string-equal (downcase sender)
7149                               (downcase (message-make-sender))))
7150            ;; Email address in From field equals to our address
7151            (and (setq from (message-fetch-field "from"))
7152                 (string-equal
7153                  (downcase (car (mail-header-parse-address from)))
7154                  (downcase (car (mail-header-parse-address
7155                                  (message-make-from))))))
7156            ;; Email address in From field matches
7157            ;; 'message-alternative-emails' regexp
7158            (and from
7159                 message-alternative-emails
7160                 (string-match
7161                  message-alternative-emails
7162                  (car (mail-header-parse-address from))))))))))
7163
7164 ;;;###autoload
7165 (defun message-cancel-news (&optional arg)
7166   "Cancel an article you posted.
7167 If ARG, allow editing of the cancellation message."
7168   (interactive "P")
7169   (unless (message-news-p)
7170     (error "This is not a news article; canceling is impossible"))
7171   (let (from newsgroups message-id distribution buf)
7172     (save-excursion
7173       ;; Get header info from original article.
7174       (save-restriction
7175         (message-narrow-to-head-1)
7176         (setq from (message-fetch-field "from")
7177               newsgroups (message-fetch-field "newsgroups")
7178               message-id (message-fetch-field "message-id" t)
7179               distribution (message-fetch-field "distribution")))
7180       ;; Make sure that this article was written by the user.
7181       (unless (message-is-yours-p)
7182         (error "This article is not yours"))
7183       (when (yes-or-no-p "Do you really want to cancel this article? ")
7184         ;; Make control message.
7185         (if arg
7186             (message-news)
7187           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
7188         (erase-buffer)
7189         (insert "Newsgroups: " newsgroups "\n"
7190                 "From: " from "\n"
7191                 "Subject: cmsg cancel " message-id "\n"
7192                 "Control: cancel " message-id "\n"
7193                 (if distribution
7194                     (concat "Distribution: " distribution "\n")
7195                   "")
7196                 mail-header-separator "\n"
7197                 message-cancel-message)
7198         (run-hooks 'message-cancel-hook)
7199         (unless arg
7200           (message "Canceling your article...")
7201           (if (let ((message-syntax-checks
7202                      'dont-check-for-anything-just-trust-me))
7203                 (funcall message-send-news-function))
7204               (message "Canceling your article...done"))
7205           (kill-buffer buf))))))
7206
7207 ;;;###autoload
7208 (defun message-supersede ()
7209   "Start composing a message to supersede the current message.
7210 This is done simply by taking the old article and adding a Supersedes
7211 header line with the old Message-ID."
7212   (interactive)
7213   (let ((cur (current-buffer)))
7214     ;; Check whether the user owns the article that is to be superseded.
7215     (unless (message-is-yours-p)
7216       (error "This article is not yours"))
7217     ;; Get a normal message buffer.
7218     (message-pop-to-buffer (message-buffer-name "supersede"))
7219     (insert-buffer-substring cur)
7220     (mime-to-mml)
7221     (message-narrow-to-head-1)
7222     ;; Remove unwanted headers.
7223     (when message-ignored-supersedes-headers
7224       (message-remove-header message-ignored-supersedes-headers t))
7225     (goto-char (point-min))
7226     (if (not (re-search-forward "^Message-ID: " nil t))
7227         (error "No Message-ID in this article")
7228       (replace-match "Supersedes: " t t))
7229     (goto-char (point-max))
7230     (insert mail-header-separator)
7231     (widen)
7232     (forward-line 1)))
7233
7234 ;;;###autoload
7235 (defun message-recover ()
7236   "Reread contents of current buffer from its last auto-save file."
7237   (interactive)
7238   (let ((file-name (make-auto-save-file-name)))
7239     (cond ((save-window-excursion
7240              (with-output-to-temp-buffer "*Directory*"
7241                (with-current-buffer standard-output
7242                  (fundamental-mode))    ; for Emacs 20.4+
7243                (buffer-disable-undo standard-output)
7244                (let ((default-directory "/"))
7245                  (call-process
7246                   "ls" nil standard-output nil "-l" file-name)))
7247              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
7248            (let ((buffer-read-only nil))
7249              (erase-buffer)
7250              (insert-file-contents file-name nil)))
7251           (t (error "message-recover cancelled")))))
7252
7253 ;;; Washing Subject:
7254
7255 (defun message-wash-subject (subject)
7256   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
7257 Previous forwarders, repliers, etc. may add it."
7258   (with-temp-buffer
7259     (insert subject)
7260     (goto-char (point-min))
7261     ;; strip Re/Fwd stuff off the beginning
7262     (while (re-search-forward
7263             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
7264       (replace-match ""))
7265
7266     ;; and gnus-style forwards [foo@bar.com] subject
7267     (goto-char (point-min))
7268     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
7269       (replace-match ""))
7270
7271     ;; and off the end
7272     (goto-char (point-max))
7273     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
7274       (replace-match ""))
7275
7276     ;; and finally, any whitespace that was left-over
7277     (goto-char (point-min))
7278     (while (re-search-forward "^[ \t]+" nil t)
7279       (replace-match ""))
7280     (goto-char (point-max))
7281     (while (re-search-backward "[ \t]+$" nil t)
7282       (replace-match ""))
7283
7284     (buffer-string)))
7285
7286 ;;; Forwarding messages.
7287
7288 (defvar message-forward-decoded-p nil
7289   "Non-nil means the original message is decoded.")
7290
7291 (defun message-forward-subject-name-subject (subject)
7292   "Generate a SUBJECT for a forwarded message.
7293 The form is: [Source] Subject, where if the original message was mail,
7294 Source is the name of the sender, and if the original message was
7295 news, Source is the list of newsgroups is was posted to."
7296   (let* ((group (message-fetch-field "newsgroups"))
7297          (from (message-fetch-field "from"))
7298          (prefix
7299           (if group
7300               (gnus-group-decoded-name group)
7301             (or (and from (or
7302                            (car (gnus-extract-address-components from))
7303                            (cadr (gnus-extract-address-components from))))
7304                 "(nowhere)"))))
7305     (concat "["
7306             (if message-forward-decoded-p
7307                 prefix
7308               (mail-decode-encoded-word-string prefix))
7309             "] " subject)))
7310
7311 (defun message-forward-subject-author-subject (subject)
7312   "Generate a SUBJECT for a forwarded message.
7313 The form is: [Source] Subject, where if the original message was mail,
7314 Source is the sender, and if the original message was news, Source is
7315 the list of newsgroups is was posted to."
7316   (let* ((group (message-fetch-field "newsgroups"))
7317          (prefix
7318           (if group
7319               (gnus-group-decoded-name group)
7320             (or (message-fetch-field "from")
7321                 "(nowhere)"))))
7322     (concat "["
7323             (if message-forward-decoded-p
7324                 prefix
7325               (mail-decode-encoded-word-string prefix))
7326             "] " subject)))
7327
7328 (defun message-forward-subject-fwd (subject)
7329   "Generate a SUBJECT for a forwarded message.
7330 The form is: Fwd: Subject, where Subject is the original subject of
7331 the message."
7332   (if (string-match "^Fwd: " subject)
7333       subject
7334     (concat "Fwd: " subject)))
7335
7336 (defun message-make-forward-subject ()
7337   "Return a Subject header suitable for the message in the current buffer."
7338   (save-excursion
7339     (save-restriction
7340       (message-narrow-to-head-1)
7341       (let ((funcs message-make-forward-subject-function)
7342             (subject (message-fetch-field "Subject")))
7343         (setq subject
7344               (if subject
7345                   (if message-forward-decoded-p
7346                       subject
7347                     (mail-decode-encoded-word-string subject))
7348                 ""))
7349         (when message-wash-forwarded-subjects
7350           (setq subject (message-wash-subject subject)))
7351         ;; Make sure funcs is a list.
7352         (and funcs
7353              (not (listp funcs))
7354              (setq funcs (list funcs)))
7355         ;; Apply funcs in order, passing subject generated by previous
7356         ;; func to the next one.
7357         (dolist (func funcs)
7358           (when (functionp func)
7359             (setq subject (funcall func subject))))
7360         subject))))
7361
7362 (defvar gnus-article-decoded-p)
7363
7364
7365 ;;;###autoload
7366 (defun message-forward (&optional news digest)
7367   "Forward the current message via mail.
7368 Optional NEWS will use news to forward instead of mail.
7369 Optional DIGEST will use digest to forward."
7370   (interactive "P")
7371   (let* ((cur (current-buffer))
7372          (message-forward-decoded-p
7373           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
7374               gnus-article-decoded-p ;; In an article buffer.
7375             message-forward-decoded-p))
7376          (subject (message-make-forward-subject)))
7377     (if news
7378         (message-news nil subject)
7379       (message-mail nil subject))
7380     (message-forward-make-body cur digest)))
7381
7382 (defun message-forward-make-body-plain (forward-buffer)
7383   (insert
7384    "\n-------------------- Start of forwarded message --------------------\n")
7385   (let ((b (point))
7386         (contents (with-current-buffer forward-buffer (buffer-string)))
7387         e)
7388     (unless (featurep 'xemacs)
7389       (unless (mm-multibyte-string-p contents)
7390         (error "Attempt to insert unibyte string from the buffer \"%s\"\
7391  to the multibyte buffer \"%s\""
7392                (if (bufferp forward-buffer)
7393                    (buffer-name forward-buffer)
7394                  forward-buffer)
7395                (buffer-name))))
7396     (insert (mm-with-multibyte-buffer
7397               (insert contents)
7398               (mime-to-mml)
7399               (goto-char (point-min))
7400               (when (looking-at "From ")
7401                 (replace-match "X-From-Line: "))
7402               (buffer-string)))
7403     (unless (bolp) (insert "\n"))
7404     (setq e (point))
7405     (insert
7406      "-------------------- End of forwarded message --------------------\n")
7407     (message-remove-ignored-headers b e)))
7408
7409 (defun message-remove-ignored-headers (b e)
7410   (when message-forward-ignored-headers
7411     (save-restriction
7412       (narrow-to-region b e)
7413       (goto-char b)
7414       (narrow-to-region (point)
7415                         (or (search-forward "\n\n" nil t) (point)))
7416       (let ((ignored (if (stringp message-forward-ignored-headers)
7417                          (list message-forward-ignored-headers)
7418                        message-forward-ignored-headers)))
7419         (dolist (elem ignored)
7420           (message-remove-header elem t))))))
7421
7422 (defun message-forward-make-body-mime (forward-buffer &optional beg end)
7423   (let ((b (point)))
7424     (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7425     (save-restriction
7426       (narrow-to-region (point) (point))
7427       (insert-buffer-substring forward-buffer beg end)
7428       (mml-quote-region (point-min) (point-max))
7429       (goto-char (point-min))
7430       (when (looking-at "From ")
7431         (replace-match "X-From-Line: "))
7432       (goto-char (point-max)))
7433     (insert "<#/part>\n")
7434     ;; Consider there is no illegible text.
7435     (add-text-properties
7436      b (point)
7437      `(no-illegible-text t rear-nonsticky t start-open t))))
7438
7439 (defun message-forward-make-body-mml (forward-buffer)
7440   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7441   (let ((b (point)) e)
7442     (if (not message-forward-decoded-p)
7443         (let ((contents (with-current-buffer forward-buffer (buffer-string))))
7444           (unless (featurep 'xemacs)
7445             (unless (mm-multibyte-string-p contents)
7446               (error "Attempt to insert unibyte string from the buffer \"%s\"\
7447  to the multibyte buffer \"%s\""
7448                      (if (bufferp forward-buffer)
7449                          (buffer-name forward-buffer)
7450                        forward-buffer)
7451                      (buffer-name))))
7452           (insert (mm-with-multibyte-buffer
7453                     (insert contents)
7454                     (mime-to-mml)
7455                     (goto-char (point-min))
7456                     (when (looking-at "From ")
7457                       (replace-match "X-From-Line: "))
7458                     (buffer-string))))
7459       (save-restriction
7460         (narrow-to-region (point) (point))
7461         (mml-insert-buffer forward-buffer)
7462         (goto-char (point-min))
7463         (when (looking-at "From ")
7464           (replace-match "X-From-Line: "))
7465         (goto-char (point-max))))
7466     (setq e (point))
7467     (insert "<#/mml>\n")
7468     (when (and (not message-forward-decoded-p)
7469                message-forward-ignored-headers)
7470       (message-remove-ignored-headers b e))))
7471
7472 (defun message-forward-make-body-digest-plain (forward-buffer)
7473   (insert
7474    "\n-------------------- Start of forwarded message --------------------\n")
7475   (mml-insert-buffer forward-buffer)
7476   (insert
7477    "\n-------------------- End of forwarded message --------------------\n"))
7478
7479 (defun message-forward-make-body-digest-mime (forward-buffer)
7480   (insert "\n<#multipart type=digest>\n")
7481   (let ((b (point)) e)
7482     (insert-buffer-substring forward-buffer)
7483     (setq e (point))
7484     (insert "<#/multipart>\n")
7485     (save-restriction
7486       (narrow-to-region b e)
7487       (goto-char b)
7488       (narrow-to-region (point)
7489                         (or (search-forward "\n\n" nil t) (point)))
7490       (delete-region (point-min) (point-max)))))
7491
7492 (defun message-forward-make-body-digest (forward-buffer)
7493   (if message-forward-as-mime
7494       (message-forward-make-body-digest-mime forward-buffer)
7495     (message-forward-make-body-digest-plain forward-buffer)))
7496
7497 (autoload 'mm-uu-dissect-text-parts "mm-uu")
7498 (autoload 'mm-uu-dissect "mm-uu")
7499
7500 (defun message-signed-or-encrypted-p (&optional dont-emulate-mime handles)
7501   "Say whether the current buffer contains signed or encrypted message.
7502 If DONT-EMULATE-MIME is nil, this function does the MIME emulation on
7503 messages that don't conform to PGP/MIME described in RFC2015.  HANDLES
7504 is for the internal use."
7505   (unless handles
7506     (let ((mm-decrypt-option 'never)
7507           (mm-verify-option 'never))
7508       (if (setq handles (mm-dissect-buffer nil t))
7509           (unless dont-emulate-mime
7510             (mm-uu-dissect-text-parts handles))
7511         (unless dont-emulate-mime
7512           (setq handles (mm-uu-dissect))))))
7513   ;; Check text/plain message in which there is a signed or encrypted
7514   ;; body that has been encoded by B or Q.
7515   (unless (or handles dont-emulate-mime)
7516     (let ((cur (current-buffer))
7517           (mm-decrypt-option 'never)
7518           (mm-verify-option 'never))
7519       (with-temp-buffer
7520         (insert-buffer-substring cur)
7521         (when (setq handles (mm-dissect-buffer t t))
7522           (if (and (bufferp (car handles))
7523                    (equal (mm-handle-media-type handles) "text/plain"))
7524               (progn
7525                 (erase-buffer)
7526                 (insert-buffer-substring (car handles))
7527                 (mm-decode-content-transfer-encoding
7528                  (mm-handle-encoding handles))
7529                 (mm-destroy-parts handles)
7530                 (setq handles (mm-uu-dissect)))
7531             (mm-destroy-parts handles)
7532             (setq handles nil))))))
7533   (when handles
7534     (prog1
7535         (catch 'found
7536           (dolist (handle (if (stringp (car handles))
7537                               (if (member (car handles)
7538                                           '("multipart/signed"
7539                                             "multipart/encrypted"))
7540                                   (throw 'found t)
7541                                 (cdr handles))
7542                             (list handles)))
7543             (if (stringp (car handle))
7544                 (when (message-signed-or-encrypted-p dont-emulate-mime handle)
7545                   (throw 'found t))
7546               (when (and (bufferp (car handle))
7547                          (equal (mm-handle-media-type handle)
7548                                 "message/rfc822"))
7549                 (with-current-buffer (mm-handle-buffer handle)
7550                   (when (message-signed-or-encrypted-p dont-emulate-mime)
7551                     (throw 'found t)))))))
7552       (mm-destroy-parts handles))))
7553
7554 ;;;###autoload
7555 (defun message-forward-make-body (forward-buffer &optional digest)
7556   ;; Put point where we want it before inserting the forwarded
7557   ;; message.
7558   (if message-forward-before-signature
7559       (message-goto-body)
7560     (goto-char (point-max)))
7561   (if digest
7562       (message-forward-make-body-digest forward-buffer)
7563     (if message-forward-as-mime
7564         (if (and message-forward-show-mml
7565                  (not (and (eq message-forward-show-mml 'best)
7566                            ;; Use the raw form in the body if it contains
7567                            ;; signed or encrypted message so as not to be
7568                            ;; destroyed by re-encoding.
7569                            (with-current-buffer forward-buffer
7570                              (condition-case nil
7571                                  (message-signed-or-encrypted-p)
7572                                (error t))))))
7573             (message-forward-make-body-mml forward-buffer)
7574           (message-forward-make-body-mime forward-buffer))
7575       (message-forward-make-body-plain forward-buffer)))
7576   (message-position-point))
7577
7578 (declare-function rmail-toggle-header "rmail" (&optional arg))
7579
7580 ;;;###autoload
7581 (defun message-forward-rmail-make-body (forward-buffer)
7582   (save-window-excursion
7583     (set-buffer forward-buffer)
7584     (if (rmail-msg-is-pruned)
7585         (if (fboundp 'rmail-msg-restore-non-pruned-header)
7586             (rmail-msg-restore-non-pruned-header) ; Emacs 22
7587           (rmail-toggle-header 0))))              ; Emacs 23
7588   (message-forward-make-body forward-buffer))
7589
7590 ;; Fixme: Should have defcustom.
7591 ;;;###autoload
7592 (defun message-insinuate-rmail ()
7593   "Let RMAIL use message to forward."
7594   (interactive)
7595   (setq rmail-enable-mime-composing t)
7596   (setq rmail-insert-mime-forwarded-message-function
7597         'message-forward-rmail-make-body))
7598
7599 (defvar message-inhibit-body-encoding nil)
7600
7601 ;;;###autoload
7602 (defun message-resend (address)
7603   "Resend the current article to ADDRESS."
7604   (interactive
7605    (list (message-read-from-minibuffer "Resend message to: ")))
7606   (message "Resending message to %s..." address)
7607   (save-excursion
7608     (let ((cur (current-buffer))
7609           gcc beg)
7610       ;; We first set up a normal mail buffer.
7611       (unless (message-mail-user-agent)
7612         (set-buffer (get-buffer-create " *message resend*"))
7613         (let ((inhibit-read-only t))
7614           (erase-buffer)))
7615       (let ((message-this-is-mail t)
7616             message-generate-hashcash
7617             message-setup-hook)
7618         (message-setup `((To . ,address))))
7619       ;; Insert our usual headers.
7620       (message-generate-headers '(From Date To Message-ID))
7621       (message-narrow-to-headers)
7622       (when (setq gcc (mail-fetch-field "gcc" nil t))
7623         (message-remove-header "gcc"))
7624       ;; Remove X-Draft-From header etc.
7625       (message-remove-header message-ignored-mail-headers t)
7626       ;; Rename them all to "Resent-*".
7627       (goto-char (point-min))
7628       (while (re-search-forward "^[A-Za-z]" nil t)
7629         (forward-char -1)
7630         (insert "Resent-"))
7631       (widen)
7632       (forward-line)
7633       (let ((inhibit-read-only t))
7634         (delete-region (point) (point-max)))
7635       (setq beg (point))
7636       ;; Insert the message to be resent.
7637       (insert-buffer-substring cur)
7638       (goto-char (point-min))
7639       (search-forward "\n\n")
7640       (forward-char -1)
7641       (save-restriction
7642         (narrow-to-region beg (point))
7643         (message-remove-header message-ignored-resent-headers t)
7644         (goto-char (point-max)))
7645       (insert mail-header-separator)
7646       ;; Rename all old ("Also-")Resent headers.
7647       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7648         (beginning-of-line)
7649         (insert "Also-"))
7650       ;; Quote any "From " lines at the beginning.
7651       (goto-char beg)
7652       (when (looking-at "From ")
7653         (replace-match "X-From-Line: "))
7654       ;; Send it.
7655       (let ((message-inhibit-body-encoding
7656              ;; Don't do any further encoding if it looks like the
7657              ;; message has already been encoded.
7658              (let ((case-fold-search t))
7659                (re-search-forward "^mime-version:" nil t)))
7660             (message-inhibit-ecomplete t)
7661             message-required-mail-headers
7662             message-generate-hashcash
7663             rfc2047-encode-encoded-words)
7664         (message-send-mail))
7665       (when gcc
7666         (message-goto-eoh)
7667         (insert "Gcc: " gcc "\n"))
7668       (run-hooks 'message-sent-hook)
7669       (kill-buffer (current-buffer)))
7670     (message "Resending message to %s...done" address)))
7671
7672 ;;;###autoload
7673 (defun message-bounce ()
7674   "Re-mail the current message.
7675 This only makes sense if the current message is a bounce message that
7676 contains some mail you have written which has been bounced back to
7677 you."
7678   (interactive)
7679   (let ((handles (mm-dissect-buffer t))
7680         boundary)
7681     (message-pop-to-buffer (message-buffer-name "bounce"))
7682     (if (stringp (car handles))
7683         ;; This is a MIME bounce.
7684         (mm-insert-part (car (last handles)))
7685       ;; This is a non-MIME bounce, so we try to remove things
7686       ;; manually.
7687       (mm-insert-part handles)
7688       (undo-boundary)
7689       (goto-char (point-min))
7690       (re-search-forward "\n\n+" nil t)
7691       (setq boundary (point))
7692       ;; We remove everything before the bounced mail.
7693       (if (or (re-search-forward message-unsent-separator nil t)
7694               (progn
7695                 (search-forward "\n\n" nil 'move)
7696                 (re-search-backward "^Return-Path:.*\n" boundary t)))
7697           (progn
7698             (forward-line 1)
7699             (delete-region (point-min)
7700                            (if (re-search-forward "^[^ \n\t]+:" nil t)
7701                                (match-beginning 0)
7702                              (point))))
7703         (goto-char boundary)
7704         (when (re-search-backward "^.?From .*\n" nil t)
7705           (delete-region (match-beginning 0) (match-end 0)))))
7706     (mime-to-mml)
7707     (save-restriction
7708       (message-narrow-to-head-1)
7709       (message-remove-header message-ignored-bounced-headers t)
7710       (goto-char (point-max))
7711       (insert mail-header-separator))
7712     (message-position-point)))
7713
7714 ;;;
7715 ;;; Interactive entry points for new message buffers.
7716 ;;;
7717
7718 ;;;###autoload
7719 (defun message-mail-other-window (&optional to subject)
7720   "Like `message-mail' command, but display mail buffer in another window."
7721   (interactive)
7722   (unless (message-mail-user-agent)
7723     (message-pop-to-buffer (message-buffer-name "mail" to)
7724                            'switch-to-buffer-other-window))
7725   (let ((message-this-is-mail t))
7726     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7727                    nil nil nil 'switch-to-buffer-other-window)))
7728
7729 ;;;###autoload
7730 (defun message-mail-other-frame (&optional to subject)
7731   "Like `message-mail' command, but display mail buffer in another frame."
7732   (interactive)
7733   (unless (message-mail-user-agent)
7734     (message-pop-to-buffer (message-buffer-name "mail" to)
7735                            'switch-to-buffer-other-frame))
7736   (let ((message-this-is-mail t))
7737     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7738                    nil nil nil 'switch-to-buffer-other-frame)))
7739
7740 ;;;###autoload
7741 (defun message-news-other-window (&optional newsgroups subject)
7742   "Start editing a news article to be sent."
7743   (interactive)
7744   (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)
7745                          'switch-to-buffer-other-window)
7746   (let ((message-this-is-news t))
7747     (message-setup `((Newsgroups . ,(or newsgroups ""))
7748                      (Subject . ,(or subject ""))))))
7749
7750 ;;;###autoload
7751 (defun message-news-other-frame (&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-frame)
7756   (let ((message-this-is-news t))
7757     (message-setup `((Newsgroups . ,(or newsgroups ""))
7758                      (Subject . ,(or subject ""))))))
7759
7760 ;;; underline.el
7761
7762 ;; This code should be moved to underline.el (from which it is stolen).
7763
7764 ;;;###autoload
7765 (defun message-bold-region (start end)
7766   "Bold all nonblank characters in the region.
7767 Works by overstriking characters.
7768 Called from program, takes two arguments START and END
7769 which specify the range to operate on."
7770   (interactive "r")
7771   (save-excursion
7772     (let ((end1 (make-marker)))
7773       (move-marker end1 (max start end))
7774       (goto-char (min start end))
7775       (while (< (point) end1)
7776         (or (looking-at "[_\^@- ]")
7777             (insert (char-after) "\b"))
7778         (forward-char 1)))))
7779
7780 ;;;###autoload
7781 (defun message-unbold-region (start end)
7782   "Remove all boldness (overstruck characters) in the region.
7783 Called from program, takes two arguments START and END
7784 which specify the range to operate on."
7785   (interactive "r")
7786   (save-excursion
7787     (let ((end1 (make-marker)))
7788       (move-marker end1 (max start end))
7789       (goto-char (min start end))
7790       (while (search-forward "\b" end1 t)
7791         (if (eq (char-after) (char-after (- (point) 2)))
7792             (delete-char -2))))))
7793
7794 (defun message-exchange-point-and-mark ()
7795   "Exchange point and mark, but don't activate region if it was inactive."
7796   (goto-char (prog1 (mark t)
7797                (set-marker (mark-marker) (point)))))
7798
7799 (defalias 'message-make-overlay 'make-overlay)
7800 (defalias 'message-delete-overlay 'delete-overlay)
7801 (defalias 'message-overlay-put 'overlay-put)
7802 (defun message-kill-all-overlays ()
7803   (if (featurep 'xemacs)
7804       (map-extents (lambda (extent ignore) (delete-extent extent)))
7805     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7806
7807 ;; Support for toolbar
7808 (defvar tool-bar-mode)
7809
7810 ;; Note: The :set function in the `message-tool-bar*' variables will only
7811 ;; affect _new_ message buffers.  We might add a function that walks thru all
7812 ;; message-mode buffers and force the update.
7813 (defun message-tool-bar-update (&optional symbol value)
7814   "Update message mode toolbar.
7815 Setter function for custom variables."
7816   (setq-default message-tool-bar-map nil)
7817   (when symbol
7818     ;; When used as ":set" function:
7819     (set-default symbol value)))
7820
7821 (defcustom message-tool-bar (if (eq gmm-tool-bar-style 'gnome)
7822                                 'message-tool-bar-gnome
7823                               'message-tool-bar-retro)
7824   "Specifies the message mode tool bar.
7825
7826 It can be either a list or a symbol referring to a list.  See
7827 `gmm-tool-bar-from-list' for the format of the list.  The
7828 default key map is `message-mode-map'.
7829
7830 Pre-defined symbols include `message-tool-bar-gnome' and
7831 `message-tool-bar-retro'."
7832   :type '(repeat gmm-tool-bar-list-item)
7833   :type '(choice (const :tag "GNOME style" message-tool-bar-gnome)
7834                  (const :tag "Retro look"  message-tool-bar-retro)
7835                  (repeat :tag "User defined list" gmm-tool-bar-item)
7836                  (symbol))
7837   :version "23.1" ;; No Gnus
7838   :initialize 'custom-initialize-default
7839   :set 'message-tool-bar-update
7840   :group 'message)
7841
7842 (defcustom message-tool-bar-gnome
7843   '((ispell-message "spell" nil
7844                     :vert-only t
7845                     :visible (or (not (boundp 'flyspell-mode))
7846                                  (not flyspell-mode)))
7847     (flyspell-buffer "spell" t
7848                      :vert-only t
7849                      :visible (and (boundp 'flyspell-mode)
7850                                    flyspell-mode)
7851                      :help "Flyspell whole buffer")
7852     (message-send-and-exit "mail/send" t :label "Send")
7853     (message-dont-send "mail/save-draft")
7854     (mml-attach-file "attach" mml-mode-map :vert-only t)
7855     (mml-preview "mail/preview" mml-mode-map)
7856     (mml-secure-message-sign-encrypt "lock" mml-mode-map :visible nil)
7857     (message-insert-importance-high "important" nil :visible nil)
7858     (message-insert-importance-low "unimportant" nil :visible nil)
7859     (message-insert-disposition-notification-to "receipt" nil :visible nil))
7860   "List of items for the message tool bar (GNOME style).
7861
7862 See `gmm-tool-bar-from-list' for details on the format of the list."
7863   :type '(repeat gmm-tool-bar-item)
7864   :version "23.1" ;; No Gnus
7865   :initialize 'custom-initialize-default
7866   :set 'message-tool-bar-update
7867   :group 'message)
7868
7869 (defcustom message-tool-bar-retro
7870   '(;; Old Emacs 21 icon for consistency.
7871     (message-send-and-exit "gnus/mail-send")
7872     (message-kill-buffer "close")
7873     (message-dont-send "cancel")
7874     (mml-attach-file "attach" mml-mode-map)
7875     (ispell-message "spell")
7876     (mml-preview "preview" mml-mode-map)
7877     (message-insert-importance-high "gnus/important")
7878     (message-insert-importance-low "gnus/unimportant")
7879     (message-insert-disposition-notification-to "gnus/receipt"))
7880   "List of items for the message tool bar (retro style).
7881
7882 See `gmm-tool-bar-from-list' for details on the format of the list."
7883   :type '(repeat gmm-tool-bar-item)
7884   :version "23.1" ;; No Gnus
7885   :initialize 'custom-initialize-default
7886   :set 'message-tool-bar-update
7887   :group 'message)
7888
7889 (defcustom message-tool-bar-zap-list
7890   '(new-file open-file dired kill-buffer write-file
7891              print-buffer customize help)
7892   "List of icon items from the global tool bar.
7893 These items are not displayed on the message mode tool bar.
7894
7895 See `gmm-tool-bar-from-list' for the format of the list."
7896   :type 'gmm-tool-bar-zap-list
7897   :version "23.1" ;; No Gnus
7898   :initialize 'custom-initialize-default
7899   :set 'message-tool-bar-update
7900   :group 'message)
7901
7902 (defvar image-load-path)
7903
7904 (defun message-make-tool-bar (&optional force)
7905   "Make a message mode tool bar from `message-tool-bar-list'.
7906 When FORCE, rebuild the tool bar."
7907   (when (and (not (featurep 'xemacs))
7908              (boundp 'tool-bar-mode)
7909              tool-bar-mode
7910              (or (not message-tool-bar-map) force))
7911     (setq message-tool-bar-map
7912           (let* ((load-path
7913                   (gmm-image-load-path-for-library "message"
7914                                                    "mail/save-draft.xpm"
7915                                                    nil t))
7916                  (image-load-path (cons (car load-path)
7917                                         (when (boundp 'image-load-path)
7918                                           image-load-path))))
7919             (gmm-tool-bar-from-list message-tool-bar
7920                                     message-tool-bar-zap-list
7921                                     'message-mode-map))))
7922   message-tool-bar-map)
7923
7924 ;;; Group name completion.
7925
7926 (defcustom message-newgroups-header-regexp
7927   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7928   "Regexp that match headers that lists groups."
7929   :group 'message
7930   :type 'regexp)
7931
7932 (defcustom message-completion-alist
7933   (list (cons message-newgroups-header-regexp 'message-expand-group)
7934         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7935         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7936           . message-expand-name)
7937         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7938           . message-expand-name))
7939   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7940   :version "22.1"
7941   :group 'message
7942   :type '(alist :key-type regexp :value-type function))
7943
7944 (defcustom message-expand-name-databases
7945   '(bbdb eudc)
7946   "List of databases to try for name completion (`message-expand-name').
7947 Each element is a symbol and can be `bbdb' or `eudc'."
7948   :group 'message
7949   :type '(set (const bbdb) (const eudc)))
7950
7951 (defcustom message-tab-body-function nil
7952   "*Function to execute when `message-tab' (TAB) is executed in the body.
7953 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7954   :version "22.1"
7955   :group 'message
7956   :link '(custom-manual "(message)Various Commands")
7957   :type '(choice (const nil)
7958                  function))
7959
7960 (declare-function mail-abbrev-in-expansion-header-p "mailabbrev" ())
7961
7962 (defun message-tab ()
7963   "Complete names according to `message-completion-alist'.
7964 Execute function specified by `message-tab-body-function' when not in
7965 those headers."
7966   (interactive)
7967   (cond
7968    ((if (and (boundp 'completion-fail-discreetly)
7969              (fboundp 'completion-at-point))
7970         (let ((completion-fail-discreetly t)) (completion-at-point))
7971       (funcall (or (message-completion-function) #'ignore)))
7972     ;; Completion was performed; nothing else to do.
7973     nil)
7974    (message-tab-body-function (funcall message-tab-body-function))
7975    (t (funcall (or (lookup-key text-mode-map "\t")
7976                    (lookup-key global-map "\t")
7977                    'indent-relative)))))
7978
7979 (defvar mail-abbrev-mode-regexp)
7980
7981 (defun message-completion-function ()
7982   (let ((alist message-completion-alist))
7983     (while (and alist
7984                 (let ((mail-abbrev-mode-regexp (caar alist)))
7985                   (not (mail-abbrev-in-expansion-header-p))))
7986       (setq alist (cdr alist)))
7987     (when (cdar alist)
7988       (lexical-let ((fun (cdar alist)))
7989         ;; Even if completion fails, return a non-nil value, so as to avoid
7990         ;; falling back to message-tab-body-function.
7991         (lambda () (funcall fun) 'completion-attempted)))))
7992
7993 (eval-and-compile
7994   (condition-case nil
7995       (with-temp-buffer
7996         (let ((standard-output (current-buffer)))
7997           (eval '(display-completion-list nil "")))
7998         (defalias 'message-display-completion-list 'display-completion-list))
7999     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
8000      (defun message-display-completion-list (completions &optional ignore)
8001        "Display the list of completions, COMPLETIONS, using `standard-output'."
8002        (display-completion-list completions)))))
8003
8004 (defun message-expand-group ()
8005   "Expand the group name under point."
8006   (let ((b (save-excursion
8007              (save-restriction
8008                (narrow-to-region
8009                 (save-excursion
8010                   (beginning-of-line)
8011                   (skip-chars-forward "^:")
8012                   (1+ (point)))
8013                 (point))
8014                (skip-chars-backward "^, \t\n") (point))))
8015         (completion-ignore-case t)
8016         (e (progn (skip-chars-forward "^,\t\n ") (point)))
8017         group collection)
8018     (when (and (boundp 'gnus-active-hashtb)
8019                gnus-active-hashtb)
8020       (mapatoms
8021        (lambda (symbol)
8022          (setq group (symbol-name symbol))
8023          (push (if (string-match "[^\000-\177]" group)
8024                    (gnus-group-decoded-name group)
8025                  group)
8026                collection))
8027        gnus-active-hashtb))
8028     (message-completion-in-region e b collection)))
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         (gmm-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: utf-8
8479 ;; End:
8480
8481 ;;; message.el ends here