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