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