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