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