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