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