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