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