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