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