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