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