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