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