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