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