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