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