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