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