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