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