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