Merge from emacs--devo--0
[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               (if errbuf (pop-to-buffer errbuf))
4519               (error "Sending...failed with exit value %d" cpr)))
4520           (when message-interactive
4521             (with-current-buffer errbuf
4522               (goto-char (point-min))
4523               (while (re-search-forward "\n+ *" nil t)
4524                 (replace-match "; "))
4525               (if (not (zerop (buffer-size)))
4526                   (error "Sending...failed to %s"
4527                          (buffer-string))))))
4528       (when (bufferp errbuf)
4529         (kill-buffer errbuf)))))
4530
4531 (defun message-send-mail-with-qmail ()
4532   "Pass the prepared message buffer to qmail-inject.
4533 Refer to the documentation for the variable `message-send-mail-function'
4534 to find out how to use this."
4535   ;; replace the header delimiter with a blank line
4536   (goto-char (point-min))
4537   (re-search-forward
4538    (concat "^" (regexp-quote mail-header-separator) "\n"))
4539   (replace-match "\n")
4540   (run-hooks 'message-send-mail-hook)
4541   ;; send the message
4542   (case
4543       (let ((coding-system-for-write message-send-coding-system))
4544         (apply
4545          'call-process-region (point-min) (point-max)
4546          message-qmail-inject-program nil nil nil
4547          ;; qmail-inject's default behavior is to look for addresses on the
4548          ;; command line; if there're none, it scans the headers.
4549          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
4550          ;;
4551          ;; in general, ALL of qmail-inject's defaults are perfect for simply
4552          ;; reading a formatted (i. e., at least a To: or Resent-To header)
4553          ;; message from stdin.
4554          ;;
4555          ;; qmail also has the advantage of not having been raped by
4556          ;; various vendors, so we don't have to allow for that, either --
4557          ;; compare this with message-send-mail-with-sendmail and weep
4558          ;; for sendmail's lost innocence.
4559          ;;
4560          ;; all this is way cool coz it lets us keep the arguments entirely
4561          ;; free for -inject-arguments -- a big win for the user and for us
4562          ;; since we don't have to play that double-guessing game and the user
4563          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
4564          (if (functionp message-qmail-inject-args)
4565              (funcall message-qmail-inject-args)
4566            message-qmail-inject-args)))
4567     ;; qmail-inject doesn't say anything on it's stdout/stderr,
4568     ;; we have to look at the retval instead
4569     (0 nil)
4570     (100 (error "qmail-inject reported permanent failure"))
4571     (111 (error "qmail-inject reported transient failure"))
4572     ;; should never happen
4573     (t   (error "qmail-inject reported unknown failure"))))
4574
4575 (defun message-send-mail-with-mh ()
4576   "Send the prepared message buffer with mh."
4577   (let ((mh-previous-window-config nil)
4578         (name (mh-new-draft-name)))
4579     (setq buffer-file-name name)
4580     ;; MH wants to generate these headers itself.
4581     (when message-mh-deletable-headers
4582       (let ((headers message-mh-deletable-headers))
4583         (while headers
4584           (goto-char (point-min))
4585           (and (re-search-forward
4586                 (concat "^" (symbol-name (car headers)) ": *") nil t)
4587                (message-delete-line))
4588           (pop headers))))
4589     (run-hooks 'message-send-mail-hook)
4590     ;; Pass it on to mh.
4591     (mh-send-letter)))
4592
4593 (defun message-smtpmail-send-it ()
4594   "Send the prepared message buffer with `smtpmail-send-it'.
4595 This only differs from `smtpmail-send-it' that this command evaluates
4596 `message-send-mail-hook' just before sending a message.  It is useful
4597 if your ISP requires the POP-before-SMTP authentication.  See the Gnus
4598 manual for details."
4599   (run-hooks 'message-send-mail-hook)
4600   (smtpmail-send-it))
4601
4602 (defun message-send-mail-with-mailclient ()
4603   "Send the prepared message buffer with `mailclient-send-it'.
4604 This only differs from `smtpmail-send-it' that this command evaluates
4605 `message-send-mail-hook' just before sending a message."
4606   (run-hooks 'message-send-mail-hook)
4607   (mailclient-send-it))
4608
4609 (defun message-canlock-generate ()
4610   "Return a string that is non-trivial to guess.
4611 Do not use this for anything important, it is cryptographically weak."
4612   (require 'sha1)
4613   (let (sha1-maximum-internal-length)
4614     (sha1 (concat (message-unique-id)
4615                   (format "%x%x%x" (random) (random t) (random))
4616                   (prin1-to-string (recent-keys))
4617                   (prin1-to-string (garbage-collect))))))
4618
4619 (defun message-canlock-password ()
4620   "The password used by message for cancel locks.
4621 This is the value of `canlock-password', if that option is non-nil.
4622 Otherwise, generate and save a value for `canlock-password' first."
4623   (unless canlock-password
4624     (customize-save-variable 'canlock-password (message-canlock-generate))
4625     (setq canlock-password-for-verify canlock-password))
4626   canlock-password)
4627
4628 (defun message-insert-canlock ()
4629   (when message-insert-canlock
4630     (message-canlock-password)
4631     (canlock-insert-header)))
4632
4633 (defun message-send-news (&optional arg)
4634   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
4635          (case-fold-search nil)
4636          (method (if (functionp message-post-method)
4637                      (funcall message-post-method arg)
4638                    message-post-method))
4639          (newsgroups-field (save-restriction
4640                             (message-narrow-to-headers-or-head)
4641                             (message-fetch-field "Newsgroups")))
4642          (followup-field (save-restriction
4643                            (message-narrow-to-headers-or-head)
4644                            (message-fetch-field "Followup-To")))
4645          ;; BUG: We really need to get the charset for each name in the
4646          ;; Newsgroups and Followup-To lines to allow crossposting
4647          ;; between group namess with incompatible character sets.
4648          ;; -- Per Abrahamsen <abraham@dina.kvl.dk> 2001-10-08.
4649          (group-field-charset
4650           (gnus-group-name-charset method newsgroups-field))
4651          (followup-field-charset
4652           (gnus-group-name-charset method (or followup-field "")))
4653          (rfc2047-header-encoding-alist
4654           (append (when group-field-charset
4655                     (list (cons "Newsgroups" group-field-charset)))
4656                   (when followup-field-charset
4657                     (list (cons "Followup-To" followup-field-charset)))
4658                   rfc2047-header-encoding-alist))
4659          (messbuf (current-buffer))
4660          (message-syntax-checks
4661           (if (and arg
4662                    (listp message-syntax-checks))
4663               (cons '(existing-newsgroups . disabled)
4664                     message-syntax-checks)
4665             message-syntax-checks))
4666          (message-this-is-news t)
4667          (message-posting-charset
4668           (gnus-setup-posting-charset newsgroups-field))
4669          result)
4670     (if (not (message-check-news-body-syntax))
4671         nil
4672       (save-restriction
4673         (message-narrow-to-headers)
4674         ;; Insert some headers.
4675         (message-generate-headers message-required-news-headers)
4676         (message-insert-canlock)
4677         ;; Let the user do all of the above.
4678         (run-hooks 'message-header-hook))
4679       ;; Note: This check will be disabled by the ".*" default value for
4680       ;; gnus-group-name-charset-group-alist. -- Pa 2001-10-07.
4681       (when (and group-field-charset
4682                  (listp message-syntax-checks))
4683         (setq message-syntax-checks
4684               (cons '(valid-newsgroups . disabled)
4685                     message-syntax-checks)))
4686       (message-cleanup-headers)
4687       (if (not (let ((message-post-method method))
4688                  (message-check-news-syntax)))
4689           nil
4690         (unwind-protect
4691             (with-current-buffer tembuf
4692               (buffer-disable-undo)
4693               (erase-buffer)
4694               ;; Avoid copying text props (except hard newlines).
4695               (insert
4696                (with-current-buffer messbuf
4697                  (mml-buffer-substring-no-properties-except-hard-newlines
4698                   (point-min) (point-max))))
4699               (message-encode-message-body)
4700               ;; Remove some headers.
4701               (save-restriction
4702                 (message-narrow-to-headers)
4703                 ;; We (re)generate the Lines header.
4704                 (when (memq 'Lines message-required-mail-headers)
4705                   (message-generate-headers '(Lines)))
4706                 ;; Remove some headers.
4707                 (message-remove-header message-ignored-news-headers t)
4708                 (let ((mail-parse-charset message-default-charset))
4709                   (mail-encode-encoded-word-buffer)))
4710               (goto-char (point-max))
4711               ;; require one newline at the end.
4712               (or (= (preceding-char) ?\n)
4713                   (insert ?\n))
4714               (let ((case-fold-search t))
4715                 ;; Remove the delimiter.
4716                 (goto-char (point-min))
4717                 (re-search-forward
4718                  (concat "^" (regexp-quote mail-header-separator) "\n"))
4719                 (replace-match "\n")
4720                 (backward-char 1))
4721               (run-hooks 'message-send-news-hook)
4722               (gnus-open-server method)
4723               (message "Sending news via %s..." (gnus-server-string method))
4724               (setq result (let ((mail-header-separator ""))
4725                              (gnus-request-post method))))
4726           (kill-buffer tembuf))
4727         (set-buffer messbuf)
4728         (if result
4729             (push 'news message-sent-message-via)
4730           (message "Couldn't send message via news: %s"
4731                    (nnheader-get-report (car method)))
4732           nil)))))
4733
4734 ;;;
4735 ;;; Header generation & syntax checking.
4736 ;;;
4737
4738 (defun message-check-element (type)
4739   "Return non-nil if this TYPE is not to be checked."
4740   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
4741       t
4742     (let ((able (assq type message-syntax-checks)))
4743       (and (consp able)
4744            (eq (cdr able) 'disabled)))))
4745
4746 (defun message-check-news-syntax ()
4747   "Check the syntax of the message."
4748   (save-excursion
4749     (save-restriction
4750       (widen)
4751       ;; We narrow to the headers and check them first.
4752       (save-excursion
4753         (save-restriction
4754           (message-narrow-to-headers)
4755           (message-check-news-header-syntax))))))
4756
4757 (defun message-check-news-header-syntax ()
4758   (and
4759    ;; Check Newsgroups header.
4760    (message-check 'newsgroups
4761      (let ((group (message-fetch-field "newsgroups")))
4762        (or
4763         (and group
4764              (not (string-match "\\`[ \t]*\\'" group)))
4765         (ignore
4766          (message
4767           "The newsgroups field is empty or missing.  Posting is denied.")))))
4768    ;; Check the Subject header.
4769    (message-check 'subject
4770      (let* ((case-fold-search t)
4771             (subject (message-fetch-field "subject")))
4772        (or
4773         (and subject
4774              (not (string-match "\\`[ \t]*\\'" subject)))
4775         (ignore
4776          (message
4777           "The subject field is empty or missing.  Posting is denied.")))))
4778    ;; Check for commands in Subject.
4779    (message-check 'subject-cmsg
4780      (if (string-match "^cmsg " (message-fetch-field "subject"))
4781          (y-or-n-p
4782           "The control code \"cmsg\" is in the subject.  Really post? ")
4783        t))
4784    ;; Check long header lines.
4785    (message-check 'long-header-lines
4786      (let ((start (point))
4787            (header nil)
4788            (length 0)
4789            found)
4790        (while (and (not found)
4791                    (re-search-forward "^\\([^ \t:]+\\): " nil t))
4792          (if (> (- (point) (match-beginning 0)) 998)
4793              (setq found t
4794                    length (- (point) (match-beginning 0)))
4795            (setq header (match-string-no-properties 1)))
4796          (setq start (match-beginning 0))
4797          (forward-line 1))
4798        (if found
4799            (y-or-n-p (format "Your %s header is too long (%d).  Really post? "
4800                              header length))
4801          t)))
4802    ;; Check for multiple identical headers.
4803    (message-check 'multiple-headers
4804      (let (found)
4805        (while (and (not found)
4806                    (re-search-forward "^[^ \t:]+: " nil t))
4807          (save-excursion
4808            (or (re-search-forward
4809                 (concat "^"
4810                         (regexp-quote
4811                          (setq found
4812                                (buffer-substring
4813                                 (match-beginning 0) (- (match-end 0) 2))))
4814                         ":")
4815                 nil t)
4816                (setq found nil))))
4817        (if found
4818            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
4819          t)))
4820    ;; Check for Version and Sendsys.
4821    (message-check 'sendsys
4822      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
4823          (y-or-n-p
4824           (format "The article contains a %s command.  Really post? "
4825                   (buffer-substring (match-beginning 0)
4826                                     (1- (match-end 0)))))
4827        t))
4828    ;; See whether we can shorten Followup-To.
4829    (message-check 'shorten-followup-to
4830      (let ((newsgroups (message-fetch-field "newsgroups"))
4831            (followup-to (message-fetch-field "followup-to"))
4832            to)
4833        (when (and newsgroups
4834                   (string-match "," newsgroups)
4835                   (not followup-to)
4836                   (not
4837                    (zerop
4838                     (length
4839                      (setq to (completing-read
4840                                "Followups to (default no Followup-To header): "
4841                                (mapcar #'list
4842                                        (cons "poster"
4843                                              (message-tokenize-header
4844                                               newsgroups)))))))))
4845          (goto-char (point-min))
4846          (insert "Followup-To: " to "\n"))
4847        t))
4848    ;; Check "Shoot me".
4849    (message-check 'shoot
4850      (if (re-search-forward
4851           "Message-ID.*.i-did-not-set--mail-host-address--so-tickle-me" nil t)
4852          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
4853        t))
4854    ;; Check for Approved.
4855    (message-check 'approved
4856      (if (re-search-forward "^Approved:" nil t)
4857          (y-or-n-p "The article contains an Approved header.  Really post? ")
4858        t))
4859    ;; Check the Message-ID header.
4860    (message-check 'message-id
4861      (let* ((case-fold-search t)
4862             (message-id (message-fetch-field "message-id" t)))
4863        (or (not message-id)
4864            ;; Is there an @ in the ID?
4865            (and (string-match "@" message-id)
4866                 ;; Is there a dot in the ID?
4867                 (string-match "@[^.]*\\." message-id)
4868                 ;; Does the ID end with a dot?
4869                 (not (string-match "\\.>" message-id)))
4870            (y-or-n-p
4871             (format "The Message-ID looks strange: \"%s\".  Really post? "
4872                     message-id)))))
4873    ;; Check the Newsgroups & Followup-To headers.
4874    (message-check 'existing-newsgroups
4875      (let* ((case-fold-search t)
4876             (newsgroups (message-fetch-field "newsgroups"))
4877             (followup-to (message-fetch-field "followup-to"))
4878             (groups (message-tokenize-header
4879                      (if followup-to
4880                          (concat newsgroups "," followup-to)
4881                        newsgroups)))
4882             (post-method (if (functionp message-post-method)
4883                              (funcall message-post-method)
4884                            message-post-method))
4885             ;; KLUDGE to handle nnvirtual groups.  Doing this right
4886             ;; would probably involve a new nnoo function.
4887             ;; -- Per Abrahamsen <abraham@dina.kvl.dk>, 2001-10-17.
4888             (method (if (and (consp post-method)
4889                              (eq (car post-method) 'nnvirtual)
4890                              gnus-message-group-art)
4891                         (let ((group (car (nnvirtual-find-group-art
4892                                            (car gnus-message-group-art)
4893                                            (cdr gnus-message-group-art)))))
4894                           (gnus-find-method-for-group group))
4895                       post-method))
4896             (known-groups
4897              (mapcar (lambda (n)
4898                        (gnus-group-name-decode
4899                         (gnus-group-real-name n)
4900                         (gnus-group-name-charset method n)))
4901                      (gnus-groups-from-server method)))
4902             errors)
4903        (while groups
4904          (when (and (not (equal (car groups) "poster"))
4905                     (not (member (car groups) known-groups))
4906                     (not (member (car groups) errors)))
4907            (push (car groups) errors))
4908          (pop groups))
4909        (cond
4910         ;; Gnus is not running.
4911         ((or (not (and (boundp 'gnus-active-hashtb)
4912                        gnus-active-hashtb))
4913              (not (boundp 'gnus-read-active-file)))
4914          t)
4915         ;; We don't have all the group names.
4916         ((and (or (not gnus-read-active-file)
4917                   (eq gnus-read-active-file 'some))
4918               errors)
4919          (y-or-n-p
4920           (format
4921            "Really use %s possibly unknown group%s: %s? "
4922            (if (= (length errors) 1) "this" "these")
4923            (if (= (length errors) 1) "" "s")
4924            (mapconcat 'identity errors ", "))))
4925         ;; There were no errors.
4926         ((not errors)
4927          t)
4928         ;; There are unknown groups.
4929         (t
4930          (y-or-n-p
4931           (format
4932            "Really post to %s unknown group%s: %s? "
4933            (if (= (length errors) 1) "this" "these")
4934            (if (= (length errors) 1) "" "s")
4935            (mapconcat 'identity errors ", ")))))))
4936    ;; Check continuation headers.
4937    (message-check 'continuation-headers
4938      (goto-char (point-min))
4939      (let ((do-posting t))
4940        (while (re-search-forward "^[^ \t\n][^ \t\n:]*[ \t\n]" nil t)
4941          (goto-char (match-beginning 0))
4942          (if (y-or-n-p "Fix continuation lines? ")
4943              (insert " ")
4944            (forward-line 1)
4945            (unless (y-or-n-p "Send anyway? ")
4946              (setq do-posting nil))))
4947        do-posting))
4948    ;; Check the Newsgroups & Followup-To headers for syntax errors.
4949    (message-check 'valid-newsgroups
4950      (let ((case-fold-search t)
4951            (headers '("Newsgroups" "Followup-To"))
4952            header error)
4953        (while (and headers (not error))
4954          (when (setq header (mail-fetch-field (car headers)))
4955            (if (or
4956                 (not
4957                  (string-match
4958                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
4959                   header))
4960                 (memq
4961                  nil (mapcar
4962                       (lambda (g)
4963                         (not (string-match "\\.\\'\\|\\.\\." g)))
4964                       (message-tokenize-header header ","))))
4965                (setq error t)))
4966          (unless error
4967            (pop headers)))
4968        (if (not error)
4969            t
4970          (y-or-n-p
4971           (format "The %s header looks odd: \"%s\".  Really post? "
4972                   (car headers) header)))))
4973    (message-check 'repeated-newsgroups
4974      (let ((case-fold-search t)
4975            (headers '("Newsgroups" "Followup-To"))
4976            header error groups group)
4977        (while (and headers
4978                    (not error))
4979          (when (setq header (mail-fetch-field (pop headers)))
4980            (setq groups (message-tokenize-header header ","))
4981            (while (setq group (pop groups))
4982              (when (member group groups)
4983                (setq error group
4984                      groups nil)))))
4985        (if (not error)
4986            t
4987          (y-or-n-p
4988           (format "Group %s is repeated in headers.  Really post? " error)))))
4989    ;; Check the From header.
4990    (message-check 'from
4991      (let* ((case-fold-search t)
4992             (from (message-fetch-field "from"))
4993             ad)
4994        (cond
4995         ((not from)
4996          (message "There is no From line.  Posting is denied.")
4997          nil)
4998         ((or (not (string-match
4999                    "@[^\\.]*\\."
5000                    (setq ad (nth 1 (mail-extract-address-components
5001                                     from))))) ;larsi@ifi
5002              (string-match "\\.\\." ad) ;larsi@ifi..uio
5003              (string-match "@\\." ad)   ;larsi@.ifi.uio
5004              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5005              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5006              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
5007          (message
5008           "Denied posting -- the From looks strange: \"%s\"." from)
5009          nil)
5010         ((let ((addresses (rfc822-addresses from)))
5011            (while (and addresses
5012                        (not (eq (string-to-char (car addresses)) ?\()))
5013              (setq addresses (cdr addresses)))
5014            addresses)
5015          (message
5016           "Denied posting -- bad From address: \"%s\"." from)
5017          nil)
5018         (t t))))
5019    ;; Check the Reply-To header.
5020    (message-check 'reply-to
5021      (let* ((case-fold-search t)
5022             (reply-to (message-fetch-field "reply-to"))
5023             ad)
5024        (cond
5025         ((not reply-to)
5026          t)
5027         ((string-match "," reply-to)
5028          (y-or-n-p
5029           (format "Multiple Reply-To addresses: \"%s\". Really post? "
5030                   reply-to)))
5031         ((or (not (string-match
5032                    "@[^\\.]*\\."
5033                    (setq ad (nth 1 (mail-extract-address-components
5034                                     reply-to))))) ;larsi@ifi
5035              (string-match "\\.\\." ad) ;larsi@ifi..uio
5036              (string-match "@\\." ad)   ;larsi@.ifi.uio
5037              (string-match "\\.$" ad)   ;larsi@ifi.uio.
5038              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
5039              (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
5040          (y-or-n-p
5041           (format
5042            "The Reply-To looks strange: \"%s\". Really post? "
5043            reply-to)))
5044         (t t))))))
5045
5046 (defun message-check-news-body-syntax ()
5047   (and
5048    ;; Check for long lines.
5049    (message-check 'long-lines
5050      (goto-char (point-min))
5051      (re-search-forward
5052       (concat "^" (regexp-quote mail-header-separator) "$"))
5053      (forward-line 1)
5054      (while (and
5055              (or (looking-at
5056                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
5057                  (let ((p (point)))
5058                    (end-of-line)
5059                    (< (- (point) p) 80)))
5060              (zerop (forward-line 1))))
5061      (or (bolp)
5062          (eobp)
5063          (y-or-n-p
5064           "You have lines longer than 79 characters.  Really post? ")))
5065    ;; Check whether the article is empty.
5066    (message-check 'empty
5067      (goto-char (point-min))
5068      (re-search-forward
5069       (concat "^" (regexp-quote mail-header-separator) "$"))
5070      (forward-line 1)
5071      (let ((b (point)))
5072        (goto-char (point-max))
5073        (re-search-backward message-signature-separator nil t)
5074        (beginning-of-line)
5075        (or (re-search-backward "[^ \n\t]" b t)
5076            (if (message-gnksa-enable-p 'empty-article)
5077                (y-or-n-p "Empty article.  Really post? ")
5078              (message "Denied posting -- Empty article.")
5079              nil))))
5080    ;; Check for control characters.
5081    (message-check 'control-chars
5082      (if (re-search-forward
5083           (mm-string-to-multibyte "[\000-\007\013\015-\032\034-\037\200-\237]")
5084           nil t)
5085          (y-or-n-p
5086           "The article contains control characters.  Really post? ")
5087        t))
5088    ;; Check excessive size.
5089    (message-check 'size
5090      (if (> (buffer-size) 60000)
5091          (y-or-n-p
5092           (format "The article is %d octets long.  Really post? "
5093                   (buffer-size)))
5094        t))
5095    ;; Check whether any new text has been added.
5096    (message-check 'new-text
5097      (or
5098       (not message-checksum)
5099       (not (eq (message-checksum) message-checksum))
5100       (if (message-gnksa-enable-p 'quoted-text-only)
5101           (y-or-n-p
5102            "It looks like no new text has been added.  Really post? ")
5103         (message "Denied posting -- no new text has been added.")
5104         nil)))
5105    ;; Check the length of the signature.
5106    (message-check 'signature
5107      (goto-char (point-max))
5108      (if (not (re-search-backward message-signature-separator nil t))
5109          t
5110        (if (>= (count-lines (1+ (point-at-eol)) (point-max)) 5)
5111            (if (message-gnksa-enable-p 'signature)
5112                (y-or-n-p
5113                 (format "Signature is excessively long (%d lines).  Really post? "
5114                         (count-lines (1+ (point-at-eol)) (point-max))))
5115              (message "Denied posting -- Excessive signature.")
5116              nil)
5117          t)))
5118    ;; Ensure that text follows last quoted portion.
5119    (message-check 'quoting-style
5120      (goto-char (point-max))
5121      (let ((no-problem t))
5122        (when (search-backward-regexp "^>[^\n]*\n" nil t)
5123          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
5124        (if no-problem
5125            t
5126          (if (message-gnksa-enable-p 'quoted-text-only)
5127              (y-or-n-p "Your text should follow quoted text.  Really post? ")
5128            ;; Ensure that
5129            (goto-char (point-min))
5130            (re-search-forward
5131             (concat "^" (regexp-quote mail-header-separator) "$"))
5132            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
5133                (y-or-n-p "Your text should follow quoted text.  Really post? ")
5134              (message "Denied posting -- only quoted text.")
5135              nil)))))))
5136
5137 (defun message-checksum ()
5138   "Return a \"checksum\" for the current buffer."
5139   (let ((sum 0))
5140     (save-excursion
5141       (goto-char (point-min))
5142       (re-search-forward
5143        (concat "^" (regexp-quote mail-header-separator) "$"))
5144       (while (not (eobp))
5145         (when (not (looking-at "[ \t\n]"))
5146           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
5147                             (char-after))))
5148         (forward-char 1)))
5149     sum))
5150
5151 (defun message-do-fcc ()
5152   "Process Fcc headers in the current buffer."
5153   (let ((case-fold-search t)
5154         (buf (current-buffer))
5155         list file
5156         (mml-externalize-attachments message-fcc-externalize-attachments))
5157     (save-excursion
5158       (save-restriction
5159         (message-narrow-to-headers)
5160         (setq file (message-fetch-field "fcc" t)))
5161       (when file
5162         (set-buffer (get-buffer-create " *message temp*"))
5163         (erase-buffer)
5164         (insert-buffer-substring buf)
5165         (message-encode-message-body)
5166         (save-restriction
5167           (message-narrow-to-headers)
5168           (while (setq file (message-fetch-field "fcc" t))
5169             (push file list)
5170             (message-remove-header "fcc" nil t))
5171           (let ((mail-parse-charset message-default-charset)
5172                 (rfc2047-header-encoding-alist
5173                  (cons '("Newsgroups" . default)
5174                        rfc2047-header-encoding-alist)))
5175             (mail-encode-encoded-word-buffer)))
5176         (goto-char (point-min))
5177         (when (re-search-forward
5178                (concat "^" (regexp-quote mail-header-separator) "$")
5179                nil t)
5180           (replace-match "" t t ))
5181         ;; Process FCC operations.
5182         (while list
5183           (setq file (pop list))
5184           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
5185               ;; Pipe the article to the program in question.
5186               (call-process-region (point-min) (point-max) shell-file-name
5187                                    nil nil nil shell-command-switch
5188                                    (match-string 1 file))
5189             ;; Save the article.
5190             (setq file (expand-file-name file))
5191             (unless (file-exists-p (file-name-directory file))
5192               (make-directory (file-name-directory file) t))
5193             (if (and message-fcc-handler-function
5194                      (not (eq message-fcc-handler-function 'rmail-output)))
5195                 (funcall message-fcc-handler-function file)
5196               (if (and (file-readable-p file) (mail-file-babyl-p file))
5197                   (rmail-output file 1 nil t)
5198                 (let ((mail-use-rfc822 t))
5199                   (rmail-output file 1 t t))))))
5200         (kill-buffer (current-buffer))))))
5201
5202 (defun message-output (filename)
5203   "Append this article to Unix/babyl mail file FILENAME."
5204   (if (and (file-readable-p filename)
5205            (mail-file-babyl-p filename))
5206       (gnus-output-to-rmail filename t)
5207     (gnus-output-to-mail filename t)))
5208
5209 (defun message-cleanup-headers ()
5210   "Do various automatic cleanups of the headers."
5211   ;; Remove empty lines in the header.
5212   (save-restriction
5213     (message-narrow-to-headers)
5214     ;; Remove blank lines.
5215     (while (re-search-forward "^[ \t]*\n" nil t)
5216       (replace-match "" t t))
5217
5218     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
5219     ;; spaces to comma and eliminate spaces around commas.  Eliminate
5220     ;; embedded line breaks.
5221     (goto-char (point-min))
5222     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
5223       (save-restriction
5224         (narrow-to-region
5225          (point)
5226          (if (re-search-forward "^[^ \t]" nil t)
5227              (match-beginning 0)
5228            (forward-line 1)
5229            (point)))
5230         (goto-char (point-min))
5231         (while (re-search-forward "\n[ \t]+" nil t)
5232           (replace-match " " t t))     ;No line breaks (too confusing)
5233         (goto-char (point-min))
5234         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
5235           (replace-match "," t t))
5236         (goto-char (point-min))
5237         ;; Remove trailing commas.
5238         (when (re-search-forward ",+$" nil t)
5239           (replace-match "" t t))))))
5240
5241 (defun message-make-date (&optional now)
5242   "Make a valid data header.
5243 If NOW, use that time instead."
5244   (let ((system-time-locale "C"))
5245     (format-time-string "%a, %d %b %Y %T %z" now)))
5246
5247 (defun message-insert-expires (days)
5248   "Insert the Expires header.  Expiry in DAYS days."
5249   (interactive "NExpire article in how many days? ")
5250   (save-excursion
5251     (message-position-on-field "Expires" "X-Draft-From")
5252     (insert (message-make-expires-date days))))
5253
5254 (defun message-make-expires-date (days)
5255   "Make date string for the Expires header.  Expiry in DAYS days.
5256
5257 In posting styles use `(\"Expires\" (make-expires-date 30))'."
5258   (let* ((cur (decode-time (current-time)))
5259          (nday (+ days (nth 3 cur))))
5260     (setf (nth 3 cur) nday)
5261     (message-make-date (apply 'encode-time cur))))
5262
5263 (defun message-make-message-id ()
5264   "Make a unique Message-ID."
5265   (concat "<" (message-unique-id)
5266           (let ((psubject (save-excursion (message-fetch-field "subject")))
5267                 (psupersedes
5268                  (save-excursion (message-fetch-field "supersedes"))))
5269             (if (or
5270                  (and message-reply-headers
5271                       (mail-header-references message-reply-headers)
5272                       (mail-header-subject message-reply-headers)
5273                       psubject
5274                       (not (string=
5275                             (message-strip-subject-re
5276                              (mail-header-subject message-reply-headers))
5277                             (message-strip-subject-re psubject))))
5278                  (and psupersedes
5279                       (string-match "_-_@" psupersedes)))
5280                 "_-_" ""))
5281           "@" (message-make-fqdn) ">"))
5282
5283 (defvar message-unique-id-char nil)
5284
5285 ;; If you ever change this function, make sure the new version
5286 ;; cannot generate IDs that the old version could.
5287 ;; You might for example insert a "." somewhere (not next to another dot
5288 ;; or string boundary), or modify the "fsf" string.
5289 (defun message-unique-id ()
5290   ;; Don't use microseconds from (current-time), they may be unsupported.
5291   ;; Instead we use this randomly inited counter.
5292   (setq message-unique-id-char
5293         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
5294            ;; (current-time) returns 16-bit ints,
5295            ;; and 2^16*25 just fits into 4 digits i base 36.
5296            (* 25 25)))
5297   (let ((tm (current-time)))
5298     (concat
5299      (if (or (memq system-type '(ms-dos emx vax-vms))
5300              ;; message-number-base36 doesn't handle bigints.
5301              (floatp (user-uid)))
5302          (let ((user (downcase (user-login-name))))
5303            (while (string-match "[^a-z0-9_]" user)
5304              (aset user (match-beginning 0) ?_))
5305            user)
5306        (message-number-base36 (user-uid) -1))
5307      (message-number-base36 (+ (car tm)
5308                                (lsh (% message-unique-id-char 25) 16)) 4)
5309      (message-number-base36 (+ (nth 1 tm)
5310                                (lsh (/ message-unique-id-char 25) 16)) 4)
5311      ;; Append a given name, because while the generated ID is unique
5312      ;; to this newsreader, other newsreaders might otherwise generate
5313      ;; the same ID via another algorithm.
5314      ".fsf")))
5315
5316 (defun message-number-base36 (num len)
5317   (if (if (< len 0)
5318           (<= num 0)
5319         (= len 0))
5320       ""
5321     (concat (message-number-base36 (/ num 36) (1- len))
5322             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
5323                                   (% num 36))))))
5324
5325 (defun message-make-organization ()
5326   "Make an Organization header."
5327   (let* ((organization
5328           (when message-user-organization
5329             (if (functionp message-user-organization)
5330                 (funcall message-user-organization)
5331               message-user-organization))))
5332     (with-temp-buffer
5333       (mm-enable-multibyte)
5334       (cond ((stringp organization)
5335              (insert organization))
5336             ((and (eq t organization)
5337                   message-user-organization-file
5338                   (file-exists-p message-user-organization-file))
5339              (insert-file-contents message-user-organization-file)))
5340       (goto-char (point-min))
5341       (while (re-search-forward "[\t\n]+" nil t)
5342         (replace-match "" t t))
5343       (unless (zerop (buffer-size))
5344         (buffer-string)))))
5345
5346 (defun message-make-lines ()
5347   "Count the number of lines and return numeric string."
5348   (save-excursion
5349     (save-restriction
5350       (widen)
5351       (message-goto-body)
5352       (int-to-string (count-lines (point) (point-max))))))
5353
5354 (defun message-make-references ()
5355   "Return the References header for this message."
5356   (when message-reply-headers
5357     (let ((message-id (mail-header-message-id message-reply-headers))
5358           (references (mail-header-references message-reply-headers)))
5359       (if (or references message-id)
5360           (concat (or references "") (and references " ")
5361                   (or message-id ""))
5362         nil))))
5363
5364 (defun message-make-in-reply-to ()
5365   "Return the In-Reply-To header for this message."
5366   (when message-reply-headers
5367     (let ((from (mail-header-from message-reply-headers))
5368           (date (mail-header-date message-reply-headers))
5369           (msg-id (mail-header-message-id message-reply-headers)))
5370       (when from
5371         (let ((name (mail-extract-address-components from)))
5372           (concat
5373            msg-id (if msg-id " (")
5374            (if (car name)
5375                (if (string-match "[^\000-\177]" (car name))
5376                    ;; Quote a string containing non-ASCII characters.
5377                    ;; It will make the RFC2047 encoder cause an error
5378                    ;; if there are special characters.
5379                    (mm-with-multibyte-buffer
5380                      (insert (car name))
5381                      (goto-char (point-min))
5382                      (while (search-forward "\"" nil t)
5383                        (when (prog2
5384                                  (backward-char)
5385                                  (zerop (% (skip-chars-backward "\\\\") 2))
5386                                (goto-char (match-beginning 0)))
5387                          (insert "\\"))
5388                        (forward-char))
5389                      ;; Those quotes will be removed by the RFC2047 encoder.
5390                      (concat "\"" (buffer-string) "\""))
5391                  (car name))
5392              (nth 1 name))
5393            "'s message of \""
5394            (if (or (not date) (string= date ""))
5395                "(unknown date)" date)
5396            "\"" (if msg-id ")")))))))
5397
5398 (defun message-make-distribution ()
5399   "Make a Distribution header."
5400   (let ((orig-distribution (message-fetch-reply-field "distribution")))
5401     (cond ((functionp message-distribution-function)
5402            (funcall message-distribution-function))
5403           (t orig-distribution))))
5404
5405 (defun message-make-expires ()
5406   "Return an Expires header based on `message-expires'."
5407   (let ((current (current-time))
5408         (future (* 1.0 message-expires 60 60 24)))
5409     ;; Add the future to current.
5410     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
5411     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
5412     (message-make-date current)))
5413
5414 (defun message-make-path ()
5415   "Return uucp path."
5416   (let ((login-name (user-login-name)))
5417     (cond ((null message-user-path)
5418            (concat (system-name) "!" login-name))
5419           ((stringp message-user-path)
5420            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
5421            (concat message-user-path "!" login-name))
5422           (t login-name))))
5423
5424 (defun message-make-from (&optional name address)
5425   "Make a From header."
5426   (let* ((style message-from-style)
5427          (login (or address (message-make-address)))
5428          (fullname (or name
5429                        (and (boundp 'user-full-name)
5430                             user-full-name)
5431                        (user-full-name))))
5432     (when (string= fullname "&")
5433       (setq fullname (user-login-name)))
5434     (with-temp-buffer
5435       (mm-enable-multibyte)
5436       (cond
5437        ((or (null style)
5438             (equal fullname ""))
5439         (insert login))
5440        ((or (eq style 'angles)
5441             (and (not (eq style 'parens))
5442                  ;; Use angles if no quoting is needed, or if parens would
5443                  ;; need quoting too.
5444                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
5445                      (let ((tmp (concat fullname nil)))
5446                        (while (string-match "([^()]*)" tmp)
5447                          (aset tmp (match-beginning 0) ?-)
5448                          (aset tmp (1- (match-end 0)) ?-))
5449                        (string-match "[\\()]" tmp)))))
5450         (insert fullname)
5451         (goto-char (point-min))
5452         ;; Look for a character that cannot appear unquoted
5453         ;; according to RFC 822.
5454         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
5455           ;; Quote fullname, escaping specials.
5456           (goto-char (point-min))
5457           (insert "\"")
5458           (while (re-search-forward "[\"\\]" nil 1)
5459             (replace-match "\\\\\\&" t))
5460           (insert "\""))
5461         (insert " <" login ">"))
5462        (t                               ; 'parens or default
5463         (insert login " (")
5464         (let ((fullname-start (point)))
5465           (insert fullname)
5466           (goto-char fullname-start)
5467           ;; RFC 822 says \ and nonmatching parentheses
5468           ;; must be escaped in comments.
5469           ;; Escape every instance of ()\ ...
5470           (while (re-search-forward "[()\\]" nil 1)
5471             (replace-match "\\\\\\&" t))
5472           ;; ... then undo escaping of matching parentheses,
5473           ;; including matching nested parentheses.
5474           (goto-char fullname-start)
5475           (while (re-search-forward
5476                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
5477                   nil 1)
5478             (replace-match "\\1(\\3)" t)
5479             (goto-char fullname-start)))
5480         (insert ")")))
5481       (buffer-string))))
5482
5483 (defun message-make-sender ()
5484   "Return the \"real\" user address.
5485 This function tries to ignore all user modifications, and
5486 give as trustworthy answer as possible."
5487   (concat (user-login-name) "@" (system-name)))
5488
5489 (defun message-make-address ()
5490   "Make the address of the user."
5491   (or (message-user-mail-address)
5492       (concat (user-login-name) "@" (message-make-domain))))
5493
5494 (defun message-user-mail-address ()
5495   "Return the pertinent part of `user-mail-address'."
5496   (when (and user-mail-address
5497              (string-match "@.*\\." user-mail-address))
5498     (if (string-match " " user-mail-address)
5499         (nth 1 (mail-extract-address-components user-mail-address))
5500       user-mail-address)))
5501
5502 (defun message-sendmail-envelope-from ()
5503   "Return the envelope from."
5504   (cond ((eq message-sendmail-envelope-from 'header)
5505          (nth 1 (mail-extract-address-components
5506                  (message-fetch-field "from"))))
5507         ((stringp message-sendmail-envelope-from)
5508          message-sendmail-envelope-from)
5509         (t
5510          (message-make-address))))
5511
5512 (defun message-make-fqdn ()
5513   "Return user's fully qualified domain name."
5514   (let* ((system-name (system-name))
5515          (user-mail (message-user-mail-address))
5516          (user-domain
5517           (if (and user-mail
5518                    (string-match "@\\(.*\\)\\'" user-mail))
5519               (match-string 1 user-mail)))
5520          (case-fold-search t))
5521     (cond
5522      ((and message-user-fqdn
5523            (stringp message-user-fqdn)
5524            (string-match message-valid-fqdn-regexp message-user-fqdn)
5525            (not (string-match message-bogus-system-names message-user-fqdn)))
5526       ;; `message-user-fqdn' seems to be valid
5527       message-user-fqdn)
5528      ((and (string-match message-valid-fqdn-regexp system-name)
5529            (not (string-match message-bogus-system-names system-name)))
5530       ;; `system-name' returned the right result.
5531       system-name)
5532      ;; Try `mail-host-address'.
5533      ((and (boundp 'mail-host-address)
5534            (stringp mail-host-address)
5535            (string-match message-valid-fqdn-regexp mail-host-address)
5536            (not (string-match message-bogus-system-names mail-host-address)))
5537       mail-host-address)
5538      ;; We try `user-mail-address' as a backup.
5539      ((and user-domain
5540            (stringp user-domain)
5541            (string-match message-valid-fqdn-regexp user-domain)
5542            (not (string-match message-bogus-system-names user-domain)))
5543       user-domain)
5544      ;; Default to this bogus thing.
5545      (t
5546       (concat system-name
5547               ".i-did-not-set--mail-host-address--so-tickle-me")))))
5548
5549 (defun message-make-host-name ()
5550   "Return the name of the host."
5551   (let ((fqdn (message-make-fqdn)))
5552     (string-match "^[^.]+\\." fqdn)
5553     (substring fqdn 0 (1- (match-end 0)))))
5554
5555 (defun message-make-domain ()
5556   "Return the domain name."
5557   (or mail-host-address
5558       (message-make-fqdn)))
5559
5560 (defun message-to-list-only ()
5561   "Send a message to the list only.
5562 Remove all addresses but the list address from To and Cc headers."
5563   (interactive)
5564   (let ((listaddr (message-make-mail-followup-to t)))
5565     (when listaddr
5566       (save-excursion
5567         (message-remove-header "to")
5568         (message-remove-header "cc")
5569         (message-position-on-field "To" "X-Draft-From")
5570         (insert listaddr)))))
5571
5572 (defun message-make-mail-followup-to (&optional only-show-subscribed)
5573   "Return the Mail-Followup-To header.
5574 If passed the optional argument ONLY-SHOW-SUBSCRIBED only return the
5575 subscribed address (and not the additional To and Cc header contents)."
5576   (let* ((case-fold-search t)
5577          (to (message-fetch-field "To"))
5578          (cc (message-fetch-field "cc"))
5579          (msg-recipients (concat to (and to cc ", ") cc))
5580          (recipients
5581           (mapcar 'mail-strip-quoted-names
5582                   (message-tokenize-header msg-recipients)))
5583          (file-regexps
5584           (if message-subscribed-address-file
5585               (let (begin end item re)
5586                 (save-excursion
5587                   (with-temp-buffer
5588                     (insert-file-contents message-subscribed-address-file)
5589                     (while (not (eobp))
5590                       (setq begin (point))
5591                       (forward-line 1)
5592                       (setq end (point))
5593                       (if (bolp) (setq end (1- end)))
5594                       (setq item (regexp-quote (buffer-substring begin end)))
5595                       (if re (setq re (concat re "\\|" item))
5596                         (setq re (concat "\\`\\(" item))))
5597                     (and re (list (concat re "\\)\\'"))))))))
5598          (mft-regexps (apply 'append message-subscribed-regexps
5599                              (mapcar 'regexp-quote
5600                                      message-subscribed-addresses)
5601                              file-regexps
5602                              (mapcar 'funcall
5603                                      message-subscribed-address-functions))))
5604     (save-match-data
5605       (let ((list
5606              (loop for recipient in recipients
5607                when (loop for regexp in mft-regexps
5608                       when (string-match regexp recipient) return t)
5609                return recipient)))
5610         (when list
5611           (if only-show-subscribed
5612               list
5613             msg-recipients))))))
5614
5615 (defun message-idna-to-ascii-rhs-1 (header)
5616   "Interactively potentially IDNA encode domain names in HEADER."
5617   (let ((field (message-fetch-field header))
5618         rhs ace  address)
5619     (when field
5620       (dolist (rhs
5621                (mm-delete-duplicates
5622                 (mapcar (lambda (rhs) (or (cadr (split-string rhs "@")) ""))
5623                         (mapcar 'downcase
5624                                 (mapcar
5625                                  'car (mail-header-parse-addresses field))))))
5626         (setq ace (if (string-match "\\`[[:ascii:]]+\\'" rhs)
5627                       rhs
5628                     (downcase (idna-to-ascii rhs))))
5629         (when (and (not (equal rhs ace))
5630                    (or (not (eq message-use-idna 'ask))
5631                        (y-or-n-p (format "Replace %s with %s in %s:? "
5632                                          rhs ace header))))
5633           (goto-char (point-min))
5634           (while (re-search-forward (concat "^" header ":") nil t)
5635             (message-narrow-to-field)
5636             (while (search-forward (concat "@" rhs) nil t)
5637               (replace-match (concat "@" ace) t t))
5638             (goto-char (point-max))
5639             (widen)))))))
5640
5641 (defun message-idna-to-ascii-rhs ()
5642   "Possibly IDNA encode non-ASCII domain names in From:, To: and Cc: headers.
5643 See `message-idna-encode'."
5644   (interactive)
5645   (when message-use-idna
5646     (save-excursion
5647       (save-restriction
5648         (message-narrow-to-head)
5649         (message-idna-to-ascii-rhs-1 "From")
5650         (message-idna-to-ascii-rhs-1 "To")
5651         (message-idna-to-ascii-rhs-1 "Reply-To")
5652         (message-idna-to-ascii-rhs-1 "Mail-Reply-To")
5653         (message-idna-to-ascii-rhs-1 "Mail-Followup-To")
5654         (message-idna-to-ascii-rhs-1 "Cc")))))
5655
5656 (defun message-generate-headers (headers)
5657   "Prepare article HEADERS.
5658 Headers already prepared in the buffer are not modified."
5659   (setq headers (append headers message-required-headers))
5660   (save-restriction
5661     (message-narrow-to-headers)
5662     (let* ((Date (message-make-date))
5663            (Message-ID (message-make-message-id))
5664            (Organization (message-make-organization))
5665            (From (message-make-from))
5666            (Path (message-make-path))
5667            (Subject nil)
5668            (Newsgroups nil)
5669            (In-Reply-To (message-make-in-reply-to))
5670            (References (message-make-references))
5671            (To nil)
5672            (Distribution (message-make-distribution))
5673            (Lines (message-make-lines))
5674            (User-Agent message-newsreader)
5675            (Expires (message-make-expires))
5676            (case-fold-search t)
5677            (optionalp nil)
5678            header value elem header-string)
5679       ;; First we remove any old generated headers.
5680       (let ((headers message-deletable-headers))
5681         (unless (buffer-modified-p)
5682           (setq headers (delq 'Message-ID (copy-sequence headers))))
5683         (while headers
5684           (goto-char (point-min))
5685           (and (re-search-forward
5686                 (concat "^" (symbol-name (car headers)) ": *") nil t)
5687                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
5688                (message-delete-line))
5689           (pop headers)))
5690       ;; Go through all the required headers and see if they are in the
5691       ;; articles already.  If they are not, or are empty, they are
5692       ;; inserted automatically - except for Subject, Newsgroups and
5693       ;; Distribution.
5694       (while headers
5695         (goto-char (point-min))
5696         (setq elem (pop headers))
5697         (if (consp elem)
5698             (if (eq (car elem) 'optional)
5699                 (setq header (cdr elem)
5700                       optionalp t)
5701               (setq header (car elem)))
5702           (setq header elem))
5703         (setq header-string  (if (stringp header)
5704                                  header
5705                                (symbol-name header)))
5706         (when (or (not (re-search-forward
5707                         (concat "^"
5708                                 (regexp-quote (downcase header-string))
5709                                 ":")
5710                         nil t))
5711                   (progn
5712                     ;; The header was found.  We insert a space after the
5713                     ;; colon, if there is none.
5714                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
5715                     ;; Find out whether the header is empty.
5716                     (looking-at "[ \t]*\n[^ \t]")))
5717           ;; So we find out what value we should insert.
5718           (setq value
5719                 (cond
5720                  ((and (consp elem)
5721                        (eq (car elem) 'optional)
5722                        (not (member header-string message-inserted-headers)))
5723                   ;; This is an optional header.  If the cdr of this
5724                   ;; is something that is nil, then we do not insert
5725                   ;; this header.
5726                   (setq header (cdr elem))
5727                   (or (and (functionp (cdr elem))
5728                            (funcall (cdr elem)))
5729                       (and (boundp (cdr elem))
5730                            (symbol-value (cdr elem)))))
5731                  ((consp elem)
5732                   ;; The element is a cons.  Either the cdr is a
5733                   ;; string to be inserted verbatim, or it is a
5734                   ;; function, and we insert the value returned from
5735                   ;; this function.
5736                   (or (and (stringp (cdr elem))
5737                            (cdr elem))
5738                       (and (functionp (cdr elem))
5739                            (funcall (cdr elem)))))
5740                  ((and (boundp header)
5741                        (symbol-value header))
5742                   ;; The element is a symbol.  We insert the value
5743                   ;; of this symbol, if any.
5744                   (symbol-value header))
5745                  ((not (message-check-element
5746                         (intern (downcase (symbol-name header)))))
5747                   ;; We couldn't generate a value for this header,
5748                   ;; so we just ask the user.
5749                   (read-from-minibuffer
5750                    (format "Empty header for %s; enter value: " header)))))
5751           ;; Finally insert the header.
5752           (when (and value
5753                      (not (equal value "")))
5754             (save-excursion
5755               (if (bolp)
5756                   (progn
5757                     ;; This header didn't exist, so we insert it.
5758                     (goto-char (point-max))
5759                     (let ((formatter
5760                            (cdr (assq header message-header-format-alist))))
5761                       (if formatter
5762                           (funcall formatter header value)
5763                         (insert header-string ": " value))
5764                       (goto-char (message-fill-field))
5765                       ;; We check whether the value was ended by a
5766                       ;; newline.  If not, we insert one.
5767                       (unless (bolp)
5768                         (insert "\n"))
5769                       (forward-line -1)))
5770                 ;; The value of this header was empty, so we clear
5771                 ;; totally and insert the new value.
5772                 (delete-region (point) (point-at-eol))
5773                 ;; If the header is optional, and the header was
5774                 ;; empty, we can't insert it anyway.
5775                 (unless optionalp
5776                   (push header-string message-inserted-headers)
5777                   (insert value)
5778                   (message-fill-field)))
5779               ;; Add the deletable property to the headers that require it.
5780               (and (memq header message-deletable-headers)
5781                    (progn (beginning-of-line) (looking-at "[^:]+: "))
5782                    (add-text-properties
5783                     (point) (match-end 0)
5784                     '(message-deletable t face italic) (current-buffer)))))))
5785       ;; Insert new Sender if the From is strange.
5786       (let ((from (message-fetch-field "from"))
5787             (sender (message-fetch-field "sender"))
5788             (secure-sender (message-make-sender)))
5789         (when (and from
5790                    (not (message-check-element 'sender))
5791                    (not (string=
5792                          (downcase
5793                           (cadr (mail-extract-address-components from)))
5794                          (downcase secure-sender)))
5795                    (or (null sender)
5796                        (not
5797                         (string=
5798                          (downcase
5799                           (cadr (mail-extract-address-components sender)))
5800                          (downcase secure-sender)))))
5801           (goto-char (point-min))
5802           ;; Rename any old Sender headers to Original-Sender.
5803           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
5804             (beginning-of-line)
5805             (insert "Original-")
5806             (beginning-of-line))
5807           (when (or (message-news-p)
5808                     (string-match "@.+\\.." secure-sender))
5809             (insert "Sender: " secure-sender "\n"))))
5810       ;; Check for IDNA
5811       (message-idna-to-ascii-rhs))))
5812
5813 (defun message-insert-courtesy-copy ()
5814   "Insert a courtesy message in mail copies of combined messages."
5815   (let (newsgroups)
5816     (save-excursion
5817       (save-restriction
5818         (message-narrow-to-headers)
5819         (when (setq newsgroups (message-fetch-field "newsgroups"))
5820           (goto-char (point-max))
5821           (insert "Posted-To: " newsgroups "\n")))
5822       (forward-line 1)
5823       (when message-courtesy-message
5824         (cond
5825          ((string-match "%s" message-courtesy-message)
5826           (insert (format message-courtesy-message newsgroups)))
5827          (t
5828           (insert message-courtesy-message)))))))
5829
5830 ;;;
5831 ;;; Setting up a message buffer
5832 ;;;
5833
5834 (defun message-skip-to-next-address ()
5835   (let ((end (save-excursion
5836                (message-next-header)
5837                (point)))
5838         quoted char)
5839     (when (looking-at ",")
5840       (forward-char 1))
5841     (while (and (not (= (point) end))
5842                 (or (not (eq char ?,))
5843                     quoted))
5844       (skip-chars-forward "^,\"" (point-max))
5845       (when (eq (setq char (following-char)) ?\")
5846         (setq quoted (not quoted)))
5847       (unless (= (point) end)
5848         (forward-char 1)))
5849     (skip-chars-forward " \t\n")))
5850
5851 (defun message-fill-address (header value)
5852   (insert (capitalize (symbol-name header))
5853           ": "
5854           (if (consp value) (car value) value)
5855           "\n")
5856   (message-fill-field-address))
5857
5858 (defun message-split-line ()
5859   "Split current line, moving portion beyond point vertically down.
5860 If the current line has `message-yank-prefix', insert it on the new line."
5861   (interactive "*")
5862   (condition-case nil
5863       (split-line message-yank-prefix) ;; Emacs 22.1+ supports arg.
5864     (error
5865      (split-line))))
5866
5867 (defun message-insert-header (header value)
5868   (insert (capitalize (symbol-name header))
5869           ": "
5870           (if (consp value) (car value) value)))
5871
5872 (defun message-field-name ()
5873   (save-excursion
5874     (goto-char (point-min))
5875     (when (looking-at "\\([^:]+\\):")
5876       (intern (capitalize (match-string 1))))))
5877
5878 (defun message-fill-field ()
5879   (save-excursion
5880     (save-restriction
5881       (message-narrow-to-field)
5882       (let ((field-name (message-field-name)))
5883         (funcall (or (cadr (assq field-name message-field-fillers))
5884                      'message-fill-field-general)))
5885       (point-max))))
5886
5887 (defun message-fill-field-address ()
5888   (while (not (eobp))
5889     (message-skip-to-next-address)
5890     (let (last)
5891       (if (and (> (current-column) 78)
5892                last)
5893           (progn
5894             (save-excursion
5895               (goto-char last)
5896               (insert "\n\t"))
5897             (setq last (1+ (point))))
5898         (setq last (1+ (point)))))))
5899
5900 (defun message-fill-field-general ()
5901   (let ((begin (point))
5902         (fill-column 78)
5903         (fill-prefix "\t"))
5904     (while (and (search-forward "\n" nil t)
5905                 (not (eobp)))
5906       (replace-match " " t t))
5907     (fill-region-as-paragraph begin (point-max))
5908     ;; Tapdance around looong Message-IDs.
5909     (forward-line -1)
5910     (when (looking-at "[ \t]*$")
5911       (message-delete-line))
5912     (goto-char begin)
5913     (search-forward ":" nil t)
5914     (when (looking-at "\n[ \t]+")
5915       (replace-match " " t t))
5916     (goto-char (point-max))))
5917
5918 (defun message-shorten-1 (list cut surplus)
5919   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
5920   (setcdr (nthcdr (- cut 2) list)
5921           (nthcdr (+ (- cut 2) surplus 1) list)))
5922
5923 (defun message-shorten-references (header references)
5924   "Trim REFERENCES to be 21 Message-ID long or less, and fold them.
5925 When sending via news, also check that the REFERENCES are less
5926 than 988 characters long, and if they are not, trim them until
5927 they are."
5928   (let ((maxcount 21)
5929         (count 0)
5930         (cut 2)
5931         refs)
5932     (with-temp-buffer
5933       (insert references)
5934       (goto-char (point-min))
5935       ;; Cons a list of valid references.  GNKSA says we must not include MIDs
5936       ;; with whitespace or missing brackets (7.a "Does not propagate broken
5937       ;; Message-IDs in original References").
5938       (while (re-search-forward "<[^ <]+@[^ <]+>" nil t)
5939         (push (match-string 0) refs))
5940       (setq refs (nreverse refs)
5941             count (length refs)))
5942
5943     ;; If the list has more than MAXCOUNT elements, trim it by
5944     ;; removing the CUTth element and the required number of
5945     ;; elements that follow.
5946     (when (> count maxcount)
5947       (let ((surplus (- count maxcount)))
5948         (message-shorten-1 refs cut surplus)
5949         (decf count surplus)))
5950
5951     ;; When sending via news, make sure the total folded length will
5952     ;; be less than 998 characters.  This is to cater to broken INN
5953     ;; 2.3 which counts the total number of characters in a header
5954     ;; rather than the physical line length of each line, as it should.
5955     ;;
5956     ;; This hack should be removed when it's believed than INN 2.3 is
5957     ;; no longer widely used.
5958     ;;
5959     ;; At this point the headers have not been generated, thus we use
5960     ;; message-this-is-news directly.
5961     (when message-this-is-news
5962       (while (< 998
5963                 (with-temp-buffer
5964                   (message-insert-header
5965                    header (mapconcat #'identity refs " "))
5966                   (buffer-size)))
5967         (message-shorten-1 refs cut 1)))
5968     ;; Finally, collect the references back into a string and insert
5969     ;; it into the buffer.
5970     (message-insert-header header (mapconcat #'identity refs " "))))
5971
5972 (defun message-position-point ()
5973   "Move point to where the user probably wants to find it."
5974   (message-narrow-to-headers)
5975   (cond
5976    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
5977     (search-backward ":" )
5978     (widen)
5979     (forward-char 1)
5980     (if (eq (char-after) ? )
5981         (forward-char 1)
5982       (insert " ")))
5983    (t
5984     (goto-char (point-max))
5985     (widen)
5986     (forward-line 1)
5987     (unless (looking-at "$")
5988       (forward-line 2)))
5989    (sit-for 0)))
5990
5991 (defcustom message-beginning-of-line t
5992   "Whether \\<message-mode-map>\\[message-beginning-of-line]\
5993  goes to beginning of header values."
5994   :version "22.1"
5995   :group 'message-buffers
5996   :link '(custom-manual "(message)Movement")
5997   :type 'boolean)
5998
5999 (defun message-beginning-of-line (&optional n)
6000   "Move point to beginning of header value or to beginning of line.
6001 The prefix argument N is passed directly to `beginning-of-line'.
6002
6003 This command is identical to `beginning-of-line' if point is
6004 outside the message header or if the option `message-beginning-of-line'
6005 is nil.
6006
6007 If point is in the message header and on a (non-continued) header
6008 line, move point to the beginning of the header value or the beginning of line,
6009 whichever is closer.  If point is already at beginning of line, move point to
6010 beginning of header value.  Therefore, repeated calls will toggle point
6011 between beginning of field and beginning of line."
6012   (interactive "p")
6013   (let ((zrs 'zmacs-region-stays))
6014     (when (and (featurep 'xemacs) (interactive-p) (boundp zrs))
6015       (set zrs t)))
6016   (if (and message-beginning-of-line
6017            (message-point-in-header-p))
6018       (let* ((here (point))
6019              (bol (progn (beginning-of-line n) (point)))
6020              (eol (point-at-eol))
6021              (eoh (re-search-forward ": *" eol t)))
6022         (goto-char
6023          (if (and eoh (or (< eoh here) (= bol here)))
6024              eoh bol)))
6025     (beginning-of-line n)))
6026
6027 (defun message-buffer-name (type &optional to group)
6028   "Return a new (unique) buffer name based on TYPE and TO."
6029   (cond
6030    ;; Generate a new buffer name The Message Way.
6031    ((memq message-generate-new-buffers '(unique t))
6032     (generate-new-buffer-name
6033      (concat "*" type
6034              (if to
6035                  (concat " to "
6036                          (or (car (mail-extract-address-components to))
6037                              to) "")
6038                "")
6039              (if (and group (not (string= group ""))) (concat " on " group) "")
6040              "*")))
6041    ;; Check whether `message-generate-new-buffers' is a function,
6042    ;; and if so, call it.
6043    ((functionp message-generate-new-buffers)
6044     (funcall message-generate-new-buffers type to group))
6045    ((eq message-generate-new-buffers 'unsent)
6046     (generate-new-buffer-name
6047      (concat "*unsent " type
6048              (if to
6049                  (concat " to "
6050                          (or (car (mail-extract-address-components to))
6051                              to) "")
6052                "")
6053              (if (and group (not (string= group ""))) (concat " on " group) "")
6054              "*")))
6055    ;; Search for the existing message buffer with the specified name.
6056    (t
6057     (let* ((new (if (eq message-generate-new-buffers 'standard)
6058                     (generate-new-buffer-name (concat "*" type " message*"))
6059                   (let ((message-generate-new-buffers 'unique))
6060                     (message-buffer-name type to group))))
6061            (regexp (concat "\\`"
6062                            (regexp-quote
6063                             (if (string-match "<[0-9]+>\\'" new)
6064                                 (substring new 0 (match-beginning 0))
6065                               new))
6066                            "\\(?:<\\([0-9]+\\)>\\)?\\'"))
6067            (case-fold-search nil))
6068       (or (cdar
6069            (last
6070             (sort
6071              (delq nil
6072                    (mapcar
6073                     (lambda (b)
6074                       (when (and (string-match regexp (setq b (buffer-name b)))
6075                                  (eq (with-current-buffer b major-mode)
6076                                      'message-mode))
6077                         (cons (string-to-number (or (match-string 1 b) "1"))
6078                               b)))
6079                     (buffer-list)))
6080              'car-less-than-car)))
6081           new)))))
6082
6083 (defun message-pop-to-buffer (name &optional switch-function)
6084   "Pop to buffer NAME, and warn if it already exists and is modified."
6085   (let ((buffer (get-buffer name)))
6086     (if (and buffer
6087              (buffer-name buffer))
6088         (let ((window (get-buffer-window buffer 0)))
6089           (if window
6090               ;; Raise the frame already displaying the message buffer.
6091               (progn
6092                 (gnus-select-frame-set-input-focus (window-frame window))
6093                 (select-window window))
6094             (funcall (or switch-function 'pop-to-buffer) buffer)
6095             (set-buffer buffer))
6096           (when (and (buffer-modified-p)
6097                      (not (prog1
6098                               (y-or-n-p
6099                                "Message already being composed; erase? ")
6100                             (message nil))))
6101             (error "Message being composed")))
6102       (funcall (or switch-function 'pop-to-buffer) name)
6103       (set-buffer name))
6104     (erase-buffer)
6105     (message-mode)))
6106
6107 (defun message-do-send-housekeeping ()
6108   "Kill old message buffers."
6109   ;; We might have sent this buffer already.  Delete it from the
6110   ;; list of buffers.
6111   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
6112   (while (and message-max-buffers
6113               message-buffer-list
6114               (>= (length message-buffer-list) message-max-buffers))
6115     ;; Kill the oldest buffer -- unless it has been changed.
6116     (let ((buffer (pop message-buffer-list)))
6117       (when (and (buffer-name buffer)
6118                  (not (buffer-modified-p buffer)))
6119         (kill-buffer buffer))))
6120   ;; Rename the buffer.
6121   (if message-send-rename-function
6122       (funcall message-send-rename-function)
6123     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
6124     (when (string-match
6125            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
6126            (buffer-name))
6127       (let ((name (match-string 2 (buffer-name)))
6128             to group)
6129         (if (not (or (null name)
6130                      (string-equal name "mail")
6131                      (string-equal name "posting")))
6132             (setq name (concat "*sent " name "*"))
6133           (message-narrow-to-headers)
6134           (setq to (message-fetch-field "to"))
6135           (setq group (message-fetch-field "newsgroups"))
6136           (widen)
6137           (setq name
6138                 (cond
6139                  (to (concat "*sent mail to "
6140                              (or (car (mail-extract-address-components to))
6141                                  to) "*"))
6142                  ((and group (not (string= group "")))
6143                   (concat "*sent posting on " group "*"))
6144                  (t "*sent mail*"))))
6145         (unless (string-equal name (buffer-name))
6146           (rename-buffer name t)))))
6147   ;; Push the current buffer onto the list.
6148   (when message-max-buffers
6149     (setq message-buffer-list
6150           (nconc message-buffer-list (list (current-buffer))))))
6151
6152 (defun message-mail-user-agent ()
6153   (let ((mua (cond
6154               ((not message-mail-user-agent) nil)
6155               ((eq message-mail-user-agent t) mail-user-agent)
6156               (t message-mail-user-agent))))
6157     (if (memq mua '(message-user-agent gnus-user-agent))
6158         nil
6159       mua)))
6160
6161 (defun message-setup (headers &optional replybuffer actions
6162                               continue switch-function)
6163   (let ((mua (message-mail-user-agent))
6164         subject to field yank-action)
6165     (if (not (and message-this-is-mail mua))
6166         (message-setup-1 headers replybuffer actions)
6167       (if replybuffer
6168           (setq yank-action (list 'insert-buffer replybuffer)))
6169       (setq headers (copy-sequence headers))
6170       (setq field (assq 'Subject headers))
6171       (when field
6172         (setq subject (cdr field))
6173         (setq headers (delq field headers)))
6174       (setq field (assq 'To headers))
6175       (when field
6176         (setq to (cdr field))
6177         (setq headers (delq field headers)))
6178       (let ((mail-user-agent mua))
6179         (compose-mail to subject
6180                       (mapcar (lambda (item)
6181                                 (cons
6182                                  (format "%s" (car item))
6183                                  (cdr item)))
6184                               headers)
6185                       continue switch-function yank-action actions)))))
6186
6187 (defun message-headers-to-generate (headers included-headers excluded-headers)
6188   "Return a list that includes all headers from HEADERS.
6189 If INCLUDED-HEADERS is a list, just include those headers.  If it is
6190 t, include all headers.  In any case, headers from EXCLUDED-HEADERS
6191 are not included."
6192   (let ((result nil)
6193         header-name)
6194     (dolist (header headers)
6195       (setq header-name (cond
6196                          ((and (consp header)
6197                                (eq (car header) 'optional))
6198                           ;; On the form (optional . Header)
6199                           (cdr header))
6200                          ((consp header)
6201                           ;; On the form (Header . function)
6202                           (car header))
6203                          (t
6204                           ;; Just a Header.
6205                           header)))
6206       (when (and (not (memq header-name excluded-headers))
6207                  (or (eq included-headers t)
6208                      (memq header-name included-headers)))
6209         (push header result)))
6210     (nreverse result)))
6211
6212 (defun message-setup-1 (headers &optional replybuffer actions)
6213   (dolist (action actions)
6214     (condition-case nil
6215         (add-to-list 'message-send-actions
6216                      `(apply ',(car action) ',(cdr action)))))
6217   (setq message-reply-buffer replybuffer)
6218   (goto-char (point-min))
6219   ;; Insert all the headers.
6220   (mail-header-format
6221    (let ((h headers)
6222          (alist message-header-format-alist))
6223      (while h
6224        (unless (assq (caar h) message-header-format-alist)
6225          (push (list (caar h)) alist))
6226        (pop h))
6227      alist)
6228    headers)
6229   (delete-region (point) (progn (forward-line -1) (point)))
6230   (when message-default-headers
6231     (insert message-default-headers)
6232     (or (bolp) (insert ?\n)))
6233   (insert mail-header-separator "\n")
6234   (forward-line -1)
6235   (when (message-news-p)
6236     (when message-default-news-headers
6237       (insert message-default-news-headers)
6238       (or (bolp) (insert ?\n)))
6239     (when message-generate-headers-first
6240       (message-generate-headers
6241        (message-headers-to-generate
6242         (append message-required-news-headers
6243                 message-required-headers)
6244         message-generate-headers-first
6245         '(Lines Subject)))))
6246   (when (message-mail-p)
6247     (when message-default-mail-headers
6248       (insert message-default-mail-headers)
6249       (or (bolp) (insert ?\n)))
6250     (when message-generate-headers-first
6251       (message-generate-headers
6252        (message-headers-to-generate
6253         (append message-required-mail-headers
6254                 message-required-headers)
6255         message-generate-headers-first
6256         '(Lines Subject)))))
6257   (run-hooks 'message-signature-setup-hook)
6258   (message-insert-signature)
6259   (save-restriction
6260     (message-narrow-to-headers)
6261     (run-hooks 'message-header-setup-hook))
6262   (setq buffer-undo-list nil)
6263   (when message-generate-hashcash
6264     ;; Generate hashcash headers for recipients already known
6265     (mail-add-payment-async))
6266   ;; Gnus posting styles are applied via buffer-local `message-setup-hook'
6267   ;; values.
6268   (run-hooks 'message-setup-hook)
6269   ;; Do this last to give it precedence over posting styles, etc.
6270   (when (message-mail-p)
6271     (save-restriction
6272       (message-narrow-to-headers)
6273       (if message-alternative-emails
6274           (message-use-alternative-email-as-from))))
6275   (message-position-point)
6276   ;; Allow correct handling of `message-checksum' in `message-yank-original':
6277   (set-buffer-modified-p nil)
6278   (undo-boundary))
6279
6280 (defun message-set-auto-save-file-name ()
6281   "Associate the message buffer with a file in the drafts directory."
6282   (when message-auto-save-directory
6283     (unless (file-directory-p
6284              (directory-file-name message-auto-save-directory))
6285       (make-directory message-auto-save-directory t))
6286     (if (gnus-alive-p)
6287         (setq message-draft-article
6288               (nndraft-request-associate-buffer "drafts"))
6289       (setq buffer-file-name (expand-file-name
6290                               (if (memq system-type
6291                                         '(ms-dos ms-windows windows-nt
6292                                                  cygwin cygwin32 win32 w32
6293                                                  mswindows))
6294                                   "message"
6295                                 "*message*")
6296                               message-auto-save-directory))
6297       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
6298     (clear-visited-file-modtime)
6299     (setq buffer-file-coding-system message-draft-coding-system)))
6300
6301 (defun message-disassociate-draft ()
6302   "Disassociate the message buffer from the drafts directory."
6303   (when message-draft-article
6304     (nndraft-request-expire-articles
6305      (list message-draft-article) "drafts" nil t)))
6306
6307 (defun message-insert-headers ()
6308   "Generate the headers for the article."
6309   (interactive)
6310   (save-excursion
6311     (save-restriction
6312       (message-narrow-to-headers)
6313       (when (message-news-p)
6314         (message-generate-headers
6315          (delq 'Lines
6316                (delq 'Subject
6317                      (copy-sequence message-required-news-headers)))))
6318       (when (message-mail-p)
6319         (message-generate-headers
6320          (delq 'Lines
6321                (delq 'Subject
6322                      (copy-sequence message-required-mail-headers))))))))
6323
6324 \f
6325
6326 ;;;
6327 ;;; Commands for interfacing with message
6328 ;;;
6329
6330 ;;;###autoload
6331 (defun message-mail (&optional to subject
6332                                other-headers continue switch-function
6333                                yank-action send-actions)
6334   "Start editing a mail message to be sent.
6335 OTHER-HEADERS is an alist of header/value pairs.  CONTINUE says whether
6336 to continue editing a message already being composed.  SWITCH-FUNCTION
6337 is a function used to switch to and display the mail buffer."
6338   (interactive)
6339   (let ((message-this-is-mail t) replybuffer)
6340     (unless (message-mail-user-agent)
6341       (message-pop-to-buffer
6342        ;; Search for the existing message buffer if `continue' is non-nil.
6343        (let ((message-generate-new-buffers
6344               (when (or (not continue)
6345                         (eq message-generate-new-buffers 'standard)
6346                         (functionp message-generate-new-buffers))
6347                 message-generate-new-buffers)))
6348          (message-buffer-name "mail" to))
6349        switch-function))
6350     ;; FIXME: message-mail should do something if YANK-ACTION is not
6351     ;; insert-buffer.
6352     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
6353          (setq replybuffer (nth 1 yank-action)))
6354     (message-setup
6355      (nconc
6356       `((To . ,(or to "")) (Subject . ,(or subject "")))
6357       (when other-headers other-headers))
6358      replybuffer send-actions continue switch-function)
6359     ;; FIXME: Should return nil if failure.
6360     t))
6361
6362 ;;;###autoload
6363 (defun message-news (&optional newsgroups subject)
6364   "Start editing a news article to be sent."
6365   (interactive)
6366   (let ((message-this-is-news t))
6367     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups))
6368     (message-setup `((Newsgroups . ,(or newsgroups ""))
6369                      (Subject . ,(or subject ""))))))
6370
6371 (defun message-alter-recipients-discard-bogus-full-name (addrcell)
6372   "Discard mail address in full names.
6373 When the full name in reply headers contains the mail
6374 address (e.g. \"foo@bar <foo@bar>\"), discard full name.
6375 ADDRCELL is a cons cell where the car is the mail address and the
6376 cdr is the complete address (full name and mail address)."
6377   (if (string-match (concat (regexp-quote (car addrcell)) ".*"
6378                             (regexp-quote (car addrcell)))
6379                     (cdr addrcell))
6380       (cons (car addrcell) (car addrcell))
6381     addrcell))
6382
6383 (defcustom message-alter-recipients-function nil
6384   "Function called to allow alteration of reply header structures.
6385 It is called in `message-get-reply-headers' for each recipient.
6386 The function is called with one parameter, a cons cell ..."
6387   :type '(choice (const :tag "None" nil)
6388                  (const :tag "Discard bogus full name"
6389                         message-alter-recipients-discard-bogus-full-name)
6390                  function)
6391   :version "23.1" ;; No Gnus
6392   :group 'message-headers)
6393
6394 (defun message-get-reply-headers (wide &optional to-address address-headers)
6395   (let (follow-to mct never-mct to cc author mft recipients extra)
6396   ;; Find all relevant headers we need.
6397     (save-restriction
6398       (message-narrow-to-headers-or-head)
6399       ;; Gmane renames "To".  Look at "Original-To", too, if it is present in
6400       ;; message-header-synonyms.
6401       (setq to (or (message-fetch-field "to")
6402                    (and (loop for synonym in message-header-synonyms
6403                               when (memq 'Original-To synonym)
6404                               return t)
6405                         (message-fetch-field "original-to")))
6406             cc (message-fetch-field "cc")
6407             extra (when message-extra-wide-headers
6408                     (mapconcat 'identity
6409                                (mapcar 'message-fetch-field
6410                                        message-extra-wide-headers)
6411                                ", "))
6412             mct (message-fetch-field "mail-copies-to")
6413             author (or (message-fetch-field "mail-reply-to")
6414                        (message-fetch-field "reply-to")
6415                        (message-fetch-field "from")
6416                        "")
6417             mft (and message-use-mail-followup-to
6418                      (message-fetch-field "mail-followup-to"))))
6419
6420     ;; Handle special values of Mail-Copies-To.
6421     (when mct
6422       (cond ((or (equal (downcase mct) "never")
6423                  (equal (downcase mct) "nobody"))
6424              (setq never-mct t)
6425              (setq mct nil))
6426             ((or (equal (downcase mct) "always")
6427                  (equal (downcase mct) "poster"))
6428              (setq mct author))))
6429
6430     (save-match-data
6431       ;; Build (textual) list of new recipient addresses.
6432       (cond
6433        ((not wide)
6434         (setq recipients (concat ", " author)))
6435        (address-headers
6436         (dolist (header address-headers)
6437           (let ((value (message-fetch-field header)))
6438             (when value
6439               (setq recipients (concat recipients ", " value))))))
6440        ((and mft
6441              (string-match "[^ \t,]" mft)
6442              (or (not (eq message-use-mail-followup-to 'ask))
6443                  (message-y-or-n-p "Obey Mail-Followup-To? " t "\
6444 You should normally obey the Mail-Followup-To: header.  In this
6445 article, it has the value of
6446
6447 " mft "
6448
6449 which directs your response to " (if (string-match "," mft)
6450                                      "the specified addresses"
6451                                    "that address only") ".
6452
6453 Most commonly, Mail-Followup-To is used by a mailing list poster to
6454 express that responses should be sent to just the list, and not the
6455 poster as well.
6456
6457 If a message is posted to several mailing lists, Mail-Followup-To may
6458 also be used to direct the following discussion to one list only,
6459 because discussions that are spread over several lists tend to be
6460 fragmented and very difficult to follow.
6461
6462 Also, some source/announcement lists are not intended for discussion;
6463 responses here are directed to other addresses.
6464
6465 You may customize the variable `message-use-mail-followup-to', if you
6466 want to get rid of this query permanently.")))
6467         (setq recipients (concat ", " mft)))
6468        (to-address
6469         (setq recipients (concat ", " to-address))
6470         ;; If the author explicitly asked for a copy, we don't deny it to them.
6471         (if mct (setq recipients (concat recipients ", " mct))))
6472        (t
6473         (setq recipients (if never-mct "" (concat ", " author)))
6474         (if to (setq recipients (concat recipients ", " to)))
6475         (if cc (setq recipients (concat recipients ", " cc)))
6476         (if extra (setq recipients (concat recipients ", " extra)))
6477         (if mct (setq recipients (concat recipients ", " mct)))))
6478       (if (>= (length recipients) 2)
6479           ;; Strip the leading ", ".
6480           (setq recipients (substring recipients 2)))
6481       ;; Squeeze whitespace.
6482       (while (string-match "[ \t][ \t]+" recipients)
6483         (setq recipients (replace-match " " t t recipients)))
6484       ;; Remove addresses that match `rmail-dont-reply-to-names'.
6485       (let ((rmail-dont-reply-to-names (message-dont-reply-to-names)))
6486         (setq recipients (rmail-dont-reply-to recipients)))
6487       ;; Perhaps "Mail-Copies-To: never" removed the only address?
6488       (if (string-equal recipients "")
6489           (setq recipients author))
6490       ;; Convert string to a list of (("foo@bar" . "Name <Foo@BAR>") ...).
6491       (setq recipients
6492             (mapcar
6493              (lambda (addr)
6494                (if message-alter-recipients-function
6495                    (funcall message-alter-recipients-function
6496                             (cons (downcase (mail-strip-quoted-names addr))
6497                                   addr))
6498                  (cons (downcase (mail-strip-quoted-names addr)) addr)))
6499              (message-tokenize-header recipients)))
6500       ;; Remove first duplicates.  (Why not all duplicates?  Is this a bug?)
6501       (let ((s recipients))
6502         (while s
6503           (setq recipients (delq (assoc (car (pop s)) s) recipients))))
6504
6505       ;; Remove hierarchical lists that are contained within each other,
6506       ;; if message-hierarchical-addresses is defined.
6507       (when message-hierarchical-addresses
6508         (let ((plain-addrs (mapcar 'car recipients))
6509               subaddrs recip)
6510           (while plain-addrs
6511             (setq subaddrs (assoc (car plain-addrs)
6512                                   message-hierarchical-addresses)
6513                   plain-addrs (cdr plain-addrs))
6514             (when subaddrs
6515               (setq subaddrs (cdr subaddrs))
6516               (while subaddrs
6517                 (setq recip (assoc (car subaddrs) recipients)
6518                       subaddrs (cdr subaddrs))
6519                 (if recip
6520                     (setq recipients (delq recip recipients))))))))
6521
6522       ;; Build the header alist.  Allow the user to be asked whether
6523       ;; or not to reply to all recipients in a wide reply.
6524       (setq follow-to (list (cons 'To (cdr (pop recipients)))))
6525       (when (and recipients
6526                  (or (not message-wide-reply-confirm-recipients)
6527                      (y-or-n-p "Reply to all recipients? ")))
6528         (setq recipients (mapconcat
6529                           (lambda (addr) (cdr addr)) recipients ", "))
6530         (if (string-match "^ +" recipients)
6531             (setq recipients (substring recipients (match-end 0))))
6532         (push (cons 'Cc recipients) follow-to)))
6533     follow-to))
6534
6535 (defcustom message-simplify-subject-functions
6536   '(message-strip-list-identifiers
6537     message-strip-subject-re
6538     message-strip-subject-trailing-was
6539     message-strip-subject-encoded-words)
6540   "List of functions taking a string argument that simplify subjects.
6541 The functions are applied when replying to a message.
6542
6543 Useful functions to put in this list include:
6544 `message-strip-list-identifiers', `message-strip-subject-re',
6545 `message-strip-subject-trailing-was', and
6546 `message-strip-subject-encoded-words'."
6547   :version "22.1" ;; Gnus 5.10.9
6548   :group 'message-various
6549   :type '(repeat function))
6550
6551 (defun message-simplify-subject (subject &optional functions)
6552   "Return simplified SUBJECT."
6553   (unless functions
6554     ;; Simplify fully:
6555     (setq functions message-simplify-subject-functions))
6556   (when (and (memq 'message-strip-list-identifiers functions)
6557              gnus-list-identifiers)
6558     (setq subject (message-strip-list-identifiers subject)))
6559   (when (memq 'message-strip-subject-re functions)
6560     (setq subject (concat "Re: " (message-strip-subject-re subject))))
6561   (when (and (memq 'message-strip-subject-trailing-was functions)
6562              message-subject-trailing-was-query)
6563     (setq subject (message-strip-subject-trailing-was subject)))
6564   (when (memq 'message-strip-subject-encoded-words functions)
6565     (setq subject (message-strip-subject-encoded-words subject)))
6566   subject)
6567
6568 ;;;###autoload
6569 (defun message-reply (&optional to-address wide)
6570   "Start editing a reply to the article in the current buffer."
6571   (interactive)
6572   (require 'gnus-sum)                   ; for gnus-list-identifiers
6573   (let ((cur (current-buffer))
6574         from subject date reply-to to cc
6575         references message-id follow-to
6576         (inhibit-point-motion-hooks t)
6577         (message-this-is-mail t)
6578         gnus-warning)
6579     (save-restriction
6580       (message-narrow-to-head-1)
6581       ;; Allow customizations to have their say.
6582       (if (not wide)
6583           ;; This is a regular reply.
6584           (when (functionp message-reply-to-function)
6585             (save-excursion
6586               (setq follow-to (funcall message-reply-to-function))))
6587         ;; This is a followup.
6588         (when (functionp message-wide-reply-to-function)
6589           (save-excursion
6590             (setq follow-to
6591                   (funcall message-wide-reply-to-function)))))
6592       (setq message-id (message-fetch-field "message-id" t)
6593             references (message-fetch-field "references")
6594             date (message-fetch-field "date")
6595             from (or (message-fetch-field "from") "nobody")
6596             subject (or (message-fetch-field "subject") "none"))
6597
6598       ;; Strip list identifiers, "Re: ", and "was:"
6599       (setq subject (message-simplify-subject subject))
6600
6601       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6602                  (string-match "<[^>]+>" gnus-warning))
6603         (setq message-id (match-string 0 gnus-warning)))
6604
6605       (unless follow-to
6606         (setq follow-to (message-get-reply-headers wide to-address))))
6607
6608     (unless (message-mail-user-agent)
6609       (message-pop-to-buffer
6610        (message-buffer-name
6611         (if wide "wide reply" "reply") from
6612         (if wide to-address nil))))
6613
6614     (setq message-reply-headers
6615           (vector 0 subject from date message-id references 0 0 ""))
6616
6617     (message-setup
6618      `((Subject . ,subject)
6619        ,@follow-to)
6620      cur)))
6621
6622 ;;;###autoload
6623 (defun message-wide-reply (&optional to-address)
6624   "Make a \"wide\" reply to the message in the current buffer."
6625   (interactive)
6626   (message-reply to-address t))
6627
6628 ;;;###autoload
6629 (defun message-followup (&optional to-newsgroups)
6630   "Follow up to the message in the current buffer.
6631 If TO-NEWSGROUPS, use that as the new Newsgroups line."
6632   (interactive)
6633   (require 'gnus-sum)                   ; for gnus-list-identifiers
6634   (let ((cur (current-buffer))
6635         from subject date reply-to mrt mct
6636         references message-id follow-to
6637         (inhibit-point-motion-hooks t)
6638         (message-this-is-news t)
6639         followup-to distribution newsgroups gnus-warning posted-to)
6640     (save-restriction
6641       (narrow-to-region
6642        (goto-char (point-min))
6643        (if (search-forward "\n\n" nil t)
6644            (1- (point))
6645          (point-max)))
6646       (when (functionp message-followup-to-function)
6647         (setq follow-to
6648               (funcall message-followup-to-function)))
6649       (setq from (message-fetch-field "from")
6650             date (message-fetch-field "date")
6651             subject (or (message-fetch-field "subject") "none")
6652             references (message-fetch-field "references")
6653             message-id (message-fetch-field "message-id" t)
6654             followup-to (message-fetch-field "followup-to")
6655             newsgroups (message-fetch-field "newsgroups")
6656             posted-to (message-fetch-field "posted-to")
6657             reply-to (message-fetch-field "reply-to")
6658             mrt (message-fetch-field "mail-reply-to")
6659             distribution (message-fetch-field "distribution")
6660             mct (message-fetch-field "mail-copies-to"))
6661       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
6662                  (string-match "<[^>]+>" gnus-warning))
6663         (setq message-id (match-string 0 gnus-warning)))
6664       ;; Remove bogus distribution.
6665       (when (and (stringp distribution)
6666                  (let ((case-fold-search t))
6667                    (string-match "world" distribution)))
6668         (setq distribution nil))
6669       ;; Strip list identifiers, "Re: ", and "was:"
6670       (setq subject (message-simplify-subject subject))
6671       (widen))
6672
6673     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
6674
6675     (setq message-reply-headers
6676           (vector 0 subject from date message-id references 0 0 ""))
6677
6678     (message-setup
6679      `((Subject . ,subject)
6680        ,@(cond
6681           (to-newsgroups
6682            (list (cons 'Newsgroups to-newsgroups)))
6683           (follow-to follow-to)
6684           ((and followup-to message-use-followup-to)
6685            (list
6686             (cond
6687              ((equal (downcase followup-to) "poster")
6688               (if (or (eq message-use-followup-to 'use)
6689                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
6690 You should normally obey the Followup-To: header.
6691
6692 `Followup-To: poster' sends your response via e-mail instead of news.
6693
6694 A typical situation where `Followup-To: poster' is used is when the poster
6695 does not read the newsgroup, so he wouldn't see any replies sent to it.
6696
6697 You may customize the variable `message-use-followup-to', if you
6698 want to get rid of this query permanently."))
6699                   (progn
6700                     (setq message-this-is-news nil)
6701                     (cons 'To (or mrt reply-to from "")))
6702                 (cons 'Newsgroups newsgroups)))
6703              (t
6704               (if (or (equal followup-to newsgroups)
6705                       (not (eq message-use-followup-to 'ask))
6706                       (message-y-or-n-p
6707                        (concat "Obey Followup-To: " followup-to "? ") t "\
6708 You should normally obey the Followup-To: header.
6709
6710         `Followup-To: " followup-to "'
6711 directs your response to " (if (string-match "," followup-to)
6712                                "the specified newsgroups"
6713                              "that newsgroup only") ".
6714
6715 If a message is posted to several newsgroups, Followup-To is often
6716 used to direct the following discussion to one newsgroup only,
6717 because discussions that are spread over several newsgroup tend to
6718 be fragmented and very difficult to follow.
6719
6720 Also, some source/announcement newsgroups are not intended for discussion;
6721 responses here are directed to other newsgroups.
6722
6723 You may customize the variable `message-use-followup-to', if you
6724 want to get rid of this query permanently."))
6725                   (cons 'Newsgroups followup-to)
6726                 (cons 'Newsgroups newsgroups))))))
6727           (posted-to
6728            `((Newsgroups . ,posted-to)))
6729           (t
6730            `((Newsgroups . ,newsgroups))))
6731        ,@(and distribution (list (cons 'Distribution distribution)))
6732        ,@(when (and mct
6733                     (not (or (equal (downcase mct) "never")
6734                              (equal (downcase mct) "nobody"))))
6735            (list (cons 'Cc (if (or (equal (downcase mct) "always")
6736                                    (equal (downcase mct) "poster"))
6737                                (or mrt reply-to from "")
6738                              mct)))))
6739
6740      cur)))
6741
6742 (defun message-is-yours-p ()
6743   "Non-nil means current article is yours.
6744 If you have added 'cancel-messages to `message-shoot-gnksa-feet', all articles
6745 are yours except those that have Cancel-Lock header not belonging to you.
6746 Instead of shooting GNKSA feet, you should modify `message-alternative-emails'
6747 regexp to match all of yours addresses."
6748   ;; Canlock-logic as suggested by Per Abrahamsen
6749   ;; <abraham@dina.kvl.dk>
6750   ;;
6751   ;; IF article has cancel-lock THEN
6752   ;;   IF we can verify it THEN
6753   ;;     issue cancel
6754   ;;   ELSE
6755   ;;     error: cancellock: article is not yours
6756   ;; ELSE
6757   ;;   Use old rules, comparing sender...
6758   (save-excursion
6759     (save-restriction
6760       (message-narrow-to-head-1)
6761       (if (message-fetch-field "Cancel-Lock")
6762           (if (null (canlock-verify))
6763               t
6764             (error "Failed to verify Cancel-lock: This article is not yours"))
6765         (let (sender from)
6766           (or
6767            (message-gnksa-enable-p 'cancel-messages)
6768            (and (setq sender (message-fetch-field "sender"))
6769                 (string-equal (downcase sender)
6770                               (downcase (message-make-sender))))
6771            ;; Email address in From field equals to our address
6772            (and (setq from (message-fetch-field "from"))
6773                 (string-equal
6774                  (downcase (car (mail-header-parse-address from)))
6775                  (downcase (car (mail-header-parse-address
6776                                  (message-make-from))))))
6777            ;; Email address in From field matches
6778            ;; 'message-alternative-emails' regexp
6779            (and from
6780                 message-alternative-emails
6781                 (string-match
6782                  message-alternative-emails
6783                  (car (mail-header-parse-address from))))))))))
6784
6785 ;;;###autoload
6786 (defun message-cancel-news (&optional arg)
6787   "Cancel an article you posted.
6788 If ARG, allow editing of the cancellation message."
6789   (interactive "P")
6790   (unless (message-news-p)
6791     (error "This is not a news article; canceling is impossible"))
6792   (let (from newsgroups message-id distribution buf)
6793     (save-excursion
6794       ;; Get header info from original article.
6795       (save-restriction
6796         (message-narrow-to-head-1)
6797         (setq from (message-fetch-field "from")
6798               newsgroups (message-fetch-field "newsgroups")
6799               message-id (message-fetch-field "message-id" t)
6800               distribution (message-fetch-field "distribution")))
6801       ;; Make sure that this article was written by the user.
6802       (unless (message-is-yours-p)
6803         (error "This article is not yours"))
6804       (when (yes-or-no-p "Do you really want to cancel this article? ")
6805         ;; Make control message.
6806         (if arg
6807             (message-news)
6808           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
6809         (erase-buffer)
6810         (insert "Newsgroups: " newsgroups "\n"
6811                 "From: " from "\n"
6812                 "Subject: cmsg cancel " message-id "\n"
6813                 "Control: cancel " message-id "\n"
6814                 (if distribution
6815                     (concat "Distribution: " distribution "\n")
6816                   "")
6817                 mail-header-separator "\n"
6818                 message-cancel-message)
6819         (run-hooks 'message-cancel-hook)
6820         (unless arg
6821           (message "Canceling your article...")
6822           (if (let ((message-syntax-checks
6823                      'dont-check-for-anything-just-trust-me))
6824                 (funcall message-send-news-function))
6825               (message "Canceling your article...done"))
6826           (kill-buffer buf))))))
6827
6828 ;;;###autoload
6829 (defun message-supersede ()
6830   "Start composing a message to supersede the current message.
6831 This is done simply by taking the old article and adding a Supersedes
6832 header line with the old Message-ID."
6833   (interactive)
6834   (let ((cur (current-buffer)))
6835     ;; Check whether the user owns the article that is to be superseded.
6836     (unless (message-is-yours-p)
6837       (error "This article is not yours"))
6838     ;; Get a normal message buffer.
6839     (message-pop-to-buffer (message-buffer-name "supersede"))
6840     (insert-buffer-substring cur)
6841     (mime-to-mml)
6842     (message-narrow-to-head-1)
6843     ;; Remove unwanted headers.
6844     (when message-ignored-supersedes-headers
6845       (message-remove-header message-ignored-supersedes-headers t))
6846     (goto-char (point-min))
6847     (if (not (re-search-forward "^Message-ID: " nil t))
6848         (error "No Message-ID in this article")
6849       (replace-match "Supersedes: " t t))
6850     (goto-char (point-max))
6851     (insert mail-header-separator)
6852     (widen)
6853     (forward-line 1)))
6854
6855 ;;;###autoload
6856 (defun message-recover ()
6857   "Reread contents of current buffer from its last auto-save file."
6858   (interactive)
6859   (let ((file-name (make-auto-save-file-name)))
6860     (cond ((save-window-excursion
6861              (if (not (eq system-type 'vax-vms))
6862                  (with-output-to-temp-buffer "*Directory*"
6863                    (with-current-buffer standard-output
6864                      (fundamental-mode)) ; for Emacs 20.4+
6865                    (buffer-disable-undo standard-output)
6866                    (let ((default-directory "/"))
6867                      (call-process
6868                       "ls" nil standard-output nil "-l" file-name))))
6869              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
6870            (let ((buffer-read-only nil))
6871              (erase-buffer)
6872              (insert-file-contents file-name nil)))
6873           (t (error "message-recover cancelled")))))
6874
6875 ;;; Washing Subject:
6876
6877 (defun message-wash-subject (subject)
6878   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
6879 Previous forwarders, replyers, etc. may add it."
6880   (with-temp-buffer
6881     (insert subject)
6882     (goto-char (point-min))
6883     ;; strip Re/Fwd stuff off the beginning
6884     (while (re-search-forward
6885             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
6886       (replace-match ""))
6887
6888     ;; and gnus-style forwards [foo@bar.com] subject
6889     (goto-char (point-min))
6890     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
6891       (replace-match ""))
6892
6893     ;; and off the end
6894     (goto-char (point-max))
6895     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
6896       (replace-match ""))
6897
6898     ;; and finally, any whitespace that was left-over
6899     (goto-char (point-min))
6900     (while (re-search-forward "^[ \t]+" nil t)
6901       (replace-match ""))
6902     (goto-char (point-max))
6903     (while (re-search-backward "[ \t]+$" nil t)
6904       (replace-match ""))
6905
6906     (buffer-string)))
6907
6908 ;;; Forwarding messages.
6909
6910 (defvar message-forward-decoded-p nil
6911   "Non-nil means the original message is decoded.")
6912
6913 (defun message-forward-subject-name-subject (subject)
6914   "Generate a SUBJECT for a forwarded message.
6915 The form is: [Source] Subject, where if the original message was mail,
6916 Source is the name of the sender, and if the original message was
6917 news, Source is the list of newsgroups is was posted to."
6918   (let* ((group (message-fetch-field "newsgroups"))
6919          (from (message-fetch-field "from"))
6920          (prefix
6921           (if group
6922               (gnus-group-decoded-name group)
6923             (or (and from (or
6924                            (car (gnus-extract-address-components from))
6925                            (cadr (gnus-extract-address-components from))))
6926                 "(nowhere)"))))
6927     (concat "["
6928             (if message-forward-decoded-p
6929                 prefix
6930               (mail-decode-encoded-word-string prefix))
6931             "] " subject)))
6932
6933 (defun message-forward-subject-author-subject (subject)
6934   "Generate a SUBJECT for a forwarded message.
6935 The form is: [Source] Subject, where if the original message was mail,
6936 Source is the sender, and if the original message was news, Source is
6937 the list of newsgroups is was posted to."
6938   (let* ((group (message-fetch-field "newsgroups"))
6939          (prefix
6940           (if group
6941               (gnus-group-decoded-name group)
6942             (or (message-fetch-field "from")
6943                 "(nowhere)"))))
6944     (concat "["
6945             (if message-forward-decoded-p
6946                 prefix
6947               (mail-decode-encoded-word-string prefix))
6948             "] " subject)))
6949
6950 (defun message-forward-subject-fwd (subject)
6951   "Generate a SUBJECT for a forwarded message.
6952 The form is: Fwd: Subject, where Subject is the original subject of
6953 the message."
6954   (if (string-match "^Fwd: " subject)
6955       subject
6956     (concat "Fwd: " subject)))
6957
6958 (defun message-make-forward-subject ()
6959   "Return a Subject header suitable for the message in the current buffer."
6960   (save-excursion
6961     (save-restriction
6962       (message-narrow-to-head-1)
6963       (let ((funcs message-make-forward-subject-function)
6964             (subject (message-fetch-field "Subject")))
6965         (setq subject
6966               (if subject
6967                   (if message-forward-decoded-p
6968                       subject
6969                     (mail-decode-encoded-word-string subject))
6970                 ""))
6971         (when message-wash-forwarded-subjects
6972           (setq subject (message-wash-subject subject)))
6973         ;; Make sure funcs is a list.
6974         (and funcs
6975              (not (listp funcs))
6976              (setq funcs (list funcs)))
6977         ;; Apply funcs in order, passing subject generated by previous
6978         ;; func to the next one.
6979         (dolist (func funcs)
6980           (when (functionp func)
6981             (setq subject (funcall func subject))))
6982         subject))))
6983
6984 (defvar gnus-article-decoded-p)
6985
6986
6987 ;;;###autoload
6988 (defun message-forward (&optional news digest)
6989   "Forward the current message via mail.
6990 Optional NEWS will use news to forward instead of mail.
6991 Optional DIGEST will use digest to forward."
6992   (interactive "P")
6993   (let* ((cur (current-buffer))
6994          (message-forward-decoded-p
6995           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
6996               gnus-article-decoded-p ;; In an article buffer.
6997             message-forward-decoded-p))
6998          (subject (message-make-forward-subject)))
6999     (if news
7000         (message-news nil subject)
7001       (message-mail nil subject))
7002     (message-forward-make-body cur digest)))
7003
7004 (defun message-forward-make-body-plain (forward-buffer)
7005   (insert
7006    "\n-------------------- Start of forwarded message --------------------\n")
7007   (let ((b (point)) e)
7008     (insert
7009      (with-temp-buffer
7010        (mm-disable-multibyte)
7011        (insert
7012         (with-current-buffer forward-buffer
7013           (mm-with-unibyte-current-buffer (buffer-string))))
7014        (mm-enable-multibyte)
7015        (mime-to-mml)
7016        (goto-char (point-min))
7017        (when (looking-at "From ")
7018          (replace-match "X-From-Line: "))
7019        (buffer-string)))
7020     (setq e (point))
7021     (insert
7022      "\n-------------------- End of forwarded message --------------------\n")
7023     (message-remove-ignored-headers b e)))
7024
7025 (defun message-remove-ignored-headers (b e)
7026   (when message-forward-ignored-headers
7027     (save-restriction
7028       (narrow-to-region b e)
7029       (goto-char b)
7030       (narrow-to-region (point)
7031                         (or (search-forward "\n\n" nil t) (point)))
7032       (let ((ignored (if (stringp message-forward-ignored-headers)
7033                          (list message-forward-ignored-headers)
7034                        message-forward-ignored-headers)))
7035         (dolist (elem ignored)
7036           (message-remove-header elem t))))))
7037
7038 (defun message-forward-make-body-mime (forward-buffer)
7039   (let ((b (point)))
7040     (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")
7041     (save-restriction
7042       (narrow-to-region (point) (point))
7043       (mml-insert-buffer forward-buffer)
7044       (goto-char (point-min))
7045       (when (looking-at "From ")
7046         (replace-match "X-From-Line: "))
7047       (goto-char (point-max)))
7048     (insert "<#/part>\n")
7049     ;; Consider there is no illegible text.
7050     (add-text-properties
7051      b (point)
7052      `(no-illegible-text t rear-nonsticky t start-open t))))
7053
7054 (defun message-forward-make-body-mml (forward-buffer)
7055   (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
7056   (let ((b (point)) e)
7057     (if (not message-forward-decoded-p)
7058         (insert
7059          (with-temp-buffer
7060            (mm-disable-multibyte)
7061            (insert
7062             (with-current-buffer forward-buffer
7063               (mm-with-unibyte-current-buffer (buffer-string))))
7064            (mm-enable-multibyte)
7065            (mime-to-mml)
7066            (goto-char (point-min))
7067            (when (looking-at "From ")
7068              (replace-match "X-From-Line: "))
7069            (buffer-string)))
7070       (save-restriction
7071         (narrow-to-region (point) (point))
7072         (mml-insert-buffer forward-buffer)
7073         (goto-char (point-min))
7074         (when (looking-at "From ")
7075           (replace-match "X-From-Line: "))
7076         (goto-char (point-max))))
7077     (setq e (point))
7078     (insert "<#/mml>\n")
7079     (when (and (not message-forward-decoded-p)
7080                message-forward-ignored-headers)
7081       (message-remove-ignored-headers b e))))
7082
7083 (defun message-forward-make-body-digest-plain (forward-buffer)
7084   (insert
7085    "\n-------------------- Start of forwarded message --------------------\n")
7086   (let ((b (point)) e)
7087     (mml-insert-buffer forward-buffer)
7088     (setq e (point))
7089     (insert
7090      "\n-------------------- End of forwarded message --------------------\n")))
7091
7092 (defun message-forward-make-body-digest-mime (forward-buffer)
7093   (insert "\n<#multipart type=digest>\n")
7094   (let ((b (point)) e)
7095     (insert-buffer-substring forward-buffer)
7096     (setq e (point))
7097     (insert "<#/multipart>\n")
7098     (save-restriction
7099       (narrow-to-region b e)
7100       (goto-char b)
7101       (narrow-to-region (point)
7102                         (or (search-forward "\n\n" nil t) (point)))
7103       (delete-region (point-min) (point-max)))))
7104
7105 (defun message-forward-make-body-digest (forward-buffer)
7106   (if message-forward-as-mime
7107       (message-forward-make-body-digest-mime forward-buffer)
7108     (message-forward-make-body-digest-plain forward-buffer)))
7109
7110 (autoload 'mm-uu-dissect-text-parts "mm-uu")
7111 (autoload 'mm-uu-dissect "mm-uu")
7112
7113 (defun message-signed-or-encrypted-p (&optional dont-emulate-mime handles)
7114   "Say whether the current buffer contains signed or encrypted message.
7115 If DONT-EMULATE-MIME is nil, this function does the MIME emulation on
7116 messages that don't conform to PGP/MIME described in RFC2015.  HANDLES
7117 is for the internal use."
7118   (unless handles
7119     (let ((mm-decrypt-option 'never)
7120           (mm-verify-option 'never))
7121       (if (setq handles (mm-dissect-buffer nil t))
7122           (unless dont-emulate-mime
7123             (mm-uu-dissect-text-parts handles))
7124         (unless dont-emulate-mime
7125           (setq handles (mm-uu-dissect))))))
7126   ;; Check text/plain message in which there is a signed or encrypted
7127   ;; body that has been encoded by B or Q.
7128   (unless (or handles dont-emulate-mime)
7129     (let ((cur (current-buffer))
7130           (mm-decrypt-option 'never)
7131           (mm-verify-option 'never))
7132       (with-temp-buffer
7133         (insert-buffer-substring cur)
7134         (when (setq handles (mm-dissect-buffer t t))
7135           (if (and (prog1
7136                        (bufferp (car handles))
7137                      (mm-destroy-parts handles))
7138                    (equal (mm-handle-media-type handles) "text/plain"))
7139               (progn
7140                 (mm-decode-content-transfer-encoding
7141                  (mm-handle-encoding handles))
7142                 (setq handles (mm-uu-dissect)))
7143             (setq handles nil))))))
7144   (when handles
7145     (prog1
7146         (catch 'found
7147           (dolist (handle (if (stringp (car handles))
7148                               (if (member (car handles)
7149                                           '("multipart/signed"
7150                                             "multipart/encrypted"))
7151                                   (throw 'found t)
7152                                 (cdr handles))
7153                             (list handles)))
7154             (if (stringp (car handle))
7155                 (when (message-signed-or-encrypted-p dont-emulate-mime handle)
7156                   (throw 'found t))
7157               (when (and (bufferp (car handle))
7158                          (equal (mm-handle-media-type handle)
7159                                 "message/rfc822"))
7160                 (with-current-buffer (mm-handle-buffer handle)
7161                   (when (message-signed-or-encrypted-p dont-emulate-mime)
7162                     (throw 'found t)))))))
7163       (mm-destroy-parts handles))))
7164
7165 ;;;###autoload
7166 (defun message-forward-make-body (forward-buffer &optional digest)
7167   ;; Put point where we want it before inserting the forwarded
7168   ;; message.
7169   (if message-forward-before-signature
7170       (message-goto-body)
7171     (goto-char (point-max)))
7172   (if digest
7173       (message-forward-make-body-digest forward-buffer)
7174     (if message-forward-as-mime
7175         (if (and message-forward-show-mml
7176                  (not (and (eq message-forward-show-mml 'best)
7177                            ;; Use the raw form in the body if it contains
7178                            ;; signed or encrypted message so as not to be
7179                            ;; destroyed by re-encoding.
7180                            (with-current-buffer forward-buffer
7181                              (condition-case nil
7182                                  (message-signed-or-encrypted-p)
7183                                (error t))))))
7184             (message-forward-make-body-mml forward-buffer)
7185           (message-forward-make-body-mime forward-buffer))
7186       (message-forward-make-body-plain forward-buffer)))
7187   (message-position-point))
7188
7189 ;;;###autoload
7190 (defun message-forward-rmail-make-body (forward-buffer)
7191   (save-window-excursion
7192     (set-buffer forward-buffer)
7193     (if (rmail-msg-is-pruned)
7194         (rmail-msg-restore-non-pruned-header)))
7195   (message-forward-make-body forward-buffer))
7196
7197 ;; Fixme: Should have defcustom.
7198 ;;;###autoload
7199 (defun message-insinuate-rmail ()
7200   "Let RMAIL use message to forward."
7201   (interactive)
7202   (setq rmail-enable-mime-composing t)
7203   (setq rmail-insert-mime-forwarded-message-function
7204         'message-forward-rmail-make-body))
7205
7206 ;;;###autoload
7207 (defun message-resend (address)
7208   "Resend the current article to ADDRESS."
7209   (interactive
7210    (list (message-read-from-minibuffer "Resend message to: ")))
7211   (message "Resending message to %s..." address)
7212   (save-excursion
7213     (let ((cur (current-buffer))
7214           beg)
7215       ;; We first set up a normal mail buffer.
7216       (unless (message-mail-user-agent)
7217         (set-buffer (get-buffer-create " *message resend*"))
7218         (erase-buffer))
7219       (let ((message-this-is-mail t)
7220             message-generate-hashcash
7221             message-setup-hook)
7222         (message-setup `((To . ,address))))
7223       ;; Insert our usual headers.
7224       (message-generate-headers '(From Date To Message-ID))
7225       (message-narrow-to-headers)
7226       ;; Remove X-Draft-From header etc.
7227       (message-remove-header message-ignored-mail-headers t)
7228       ;; Rename them all to "Resent-*".
7229       (goto-char (point-min))
7230       (while (re-search-forward "^[A-Za-z]" nil t)
7231         (forward-char -1)
7232         (insert "Resent-"))
7233       (widen)
7234       (forward-line)
7235       (delete-region (point) (point-max))
7236       (setq beg (point))
7237       ;; Insert the message to be resent.
7238       (insert-buffer-substring cur)
7239       (goto-char (point-min))
7240       (search-forward "\n\n")
7241       (forward-char -1)
7242       (save-restriction
7243         (narrow-to-region beg (point))
7244         (message-remove-header message-ignored-resent-headers t)
7245         (goto-char (point-max)))
7246       (insert mail-header-separator)
7247       ;; Rename all old ("Also-")Resent headers.
7248       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
7249         (beginning-of-line)
7250         (insert "Also-"))
7251       ;; Quote any "From " lines at the beginning.
7252       (goto-char beg)
7253       (when (looking-at "From ")
7254         (replace-match "X-From-Line: "))
7255       ;; Send it.
7256       (let ((message-inhibit-body-encoding t)
7257             message-required-mail-headers
7258             message-generate-hashcash
7259             rfc2047-encode-encoded-words)
7260         (message-send-mail))
7261       (kill-buffer (current-buffer)))
7262     (message "Resending message to %s...done" address)))
7263
7264 ;;;###autoload
7265 (defun message-bounce ()
7266   "Re-mail the current message.
7267 This only makes sense if the current message is a bounce message that
7268 contains some mail you have written which has been bounced back to
7269 you."
7270   (interactive)
7271   (let ((handles (mm-dissect-buffer t))
7272         boundary)
7273     (message-pop-to-buffer (message-buffer-name "bounce"))
7274     (if (stringp (car handles))
7275         ;; This is a MIME bounce.
7276         (mm-insert-part (car (last handles)))
7277       ;; This is a non-MIME bounce, so we try to remove things
7278       ;; manually.
7279       (mm-insert-part handles)
7280       (undo-boundary)
7281       (goto-char (point-min))
7282       (re-search-forward "\n\n+" nil t)
7283       (setq boundary (point))
7284       ;; We remove everything before the bounced mail.
7285       (if (or (re-search-forward message-unsent-separator nil t)
7286               (progn
7287                 (search-forward "\n\n" nil 'move)
7288                 (re-search-backward "^Return-Path:.*\n" boundary t)))
7289           (progn
7290             (forward-line 1)
7291             (delete-region (point-min)
7292                            (if (re-search-forward "^[^ \n\t]+:" nil t)
7293                                (match-beginning 0)
7294                              (point))))
7295         (goto-char boundary)
7296         (when (re-search-backward "^.?From .*\n" nil t)
7297           (delete-region (match-beginning 0) (match-end 0)))))
7298     (mime-to-mml)
7299     (save-restriction
7300       (message-narrow-to-head-1)
7301       (message-remove-header message-ignored-bounced-headers t)
7302       (goto-char (point-max))
7303       (insert mail-header-separator))
7304     (message-position-point)))
7305
7306 ;;;
7307 ;;; Interactive entry points for new message buffers.
7308 ;;;
7309
7310 ;;;###autoload
7311 (defun message-mail-other-window (&optional to subject)
7312   "Like `message-mail' command, but display mail buffer in another window."
7313   (interactive)
7314   (unless (message-mail-user-agent)
7315     (let ((pop-up-windows t)
7316           (special-display-buffer-names nil)
7317           (special-display-regexps nil)
7318           (same-window-buffer-names nil)
7319           (same-window-regexps nil))
7320       (message-pop-to-buffer (message-buffer-name "mail" to))))
7321   (let ((message-this-is-mail t))
7322     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7323                    nil nil nil 'switch-to-buffer-other-window)))
7324
7325 ;;;###autoload
7326 (defun message-mail-other-frame (&optional to subject)
7327   "Like `message-mail' command, but display mail buffer in another frame."
7328   (interactive)
7329   (unless (message-mail-user-agent)
7330     (let ((pop-up-frames t)
7331           (special-display-buffer-names nil)
7332           (special-display-regexps nil)
7333           (same-window-buffer-names nil)
7334           (same-window-regexps nil))
7335       (message-pop-to-buffer (message-buffer-name "mail" to))))
7336   (let ((message-this-is-mail t))
7337     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
7338                    nil nil nil 'switch-to-buffer-other-frame)))
7339
7340 ;;;###autoload
7341 (defun message-news-other-window (&optional newsgroups subject)
7342   "Start editing a news article to be sent."
7343   (interactive)
7344   (let ((pop-up-windows t)
7345         (special-display-buffer-names nil)
7346         (special-display-regexps nil)
7347         (same-window-buffer-names nil)
7348         (same-window-regexps nil))
7349     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7350   (let ((message-this-is-news t))
7351     (message-setup `((Newsgroups . ,(or newsgroups ""))
7352                      (Subject . ,(or subject ""))))))
7353
7354 ;;;###autoload
7355 (defun message-news-other-frame (&optional newsgroups subject)
7356   "Start editing a news article to be sent."
7357   (interactive)
7358   (let ((pop-up-frames t)
7359         (special-display-buffer-names nil)
7360         (special-display-regexps nil)
7361         (same-window-buffer-names nil)
7362         (same-window-regexps nil))
7363     (message-pop-to-buffer (message-buffer-name "posting" nil newsgroups)))
7364   (let ((message-this-is-news t))
7365     (message-setup `((Newsgroups . ,(or newsgroups ""))
7366                      (Subject . ,(or subject ""))))))
7367
7368 ;;; underline.el
7369
7370 ;; This code should be moved to underline.el (from which it is stolen).
7371
7372 ;;;###autoload
7373 (defun message-bold-region (start end)
7374   "Bold all nonblank characters in the region.
7375 Works by overstriking characters.
7376 Called from program, takes two arguments START and END
7377 which specify the range to operate on."
7378   (interactive "r")
7379   (save-excursion
7380     (let ((end1 (make-marker)))
7381       (move-marker end1 (max start end))
7382       (goto-char (min start end))
7383       (while (< (point) end1)
7384         (or (looking-at "[_\^@- ]")
7385             (insert (char-after) "\b"))
7386         (forward-char 1)))))
7387
7388 ;;;###autoload
7389 (defun message-unbold-region (start end)
7390   "Remove all boldness (overstruck characters) in the region.
7391 Called from program, takes two arguments START and END
7392 which specify the range to operate on."
7393   (interactive "r")
7394   (save-excursion
7395     (let ((end1 (make-marker)))
7396       (move-marker end1 (max start end))
7397       (goto-char (min start end))
7398       (while (search-forward "\b" end1 t)
7399         (if (eq (char-after) (char-after (- (point) 2)))
7400             (delete-char -2))))))
7401
7402 (defun message-exchange-point-and-mark ()
7403   "Exchange point and mark, but don't activate region if it was inactive."
7404   (unless (prog1
7405               (message-mark-active-p)
7406             (exchange-point-and-mark))
7407     (setq mark-active nil)))
7408
7409 (defalias 'message-make-overlay 'make-overlay)
7410 (defalias 'message-delete-overlay 'delete-overlay)
7411 (defalias 'message-overlay-put 'overlay-put)
7412 (defun message-kill-all-overlays ()
7413   (if (featurep 'xemacs)
7414       (map-extents (lambda (extent ignore) (delete-extent extent)))
7415     (mapcar #'delete-overlay (overlays-in (point-min) (point-max)))))
7416
7417 ;; Support for toolbar
7418 (defvar tool-bar-mode)
7419
7420 ;; Note: The :set function in the `message-tool-bar*' variables will only
7421 ;; affect _new_ message buffers.  We might add a function that walks thru all
7422 ;; message-mode buffers and force the update.
7423 (defun message-tool-bar-update (&optional symbol value)
7424   "Update message mode toolbar.
7425 Setter function for custom variables."
7426   (setq-default message-tool-bar-map nil)
7427   (when symbol
7428     ;; When used as ":set" function:
7429     (set-default symbol value)))
7430
7431 (defcustom message-tool-bar (if (eq gmm-tool-bar-style 'gnome)
7432                                 'message-tool-bar-gnome
7433                               'message-tool-bar-retro)
7434   "Specifies the message mode tool bar.
7435
7436 It can be either a list or a symbol refering to a list.  See
7437 `gmm-tool-bar-from-list' for the format of the list.  The
7438 default key map is `message-mode-map'.
7439
7440 Pre-defined symbols include `message-tool-bar-gnome' and
7441 `message-tool-bar-retro'."
7442   :type '(repeat gmm-tool-bar-list-item)
7443   :type '(choice (const :tag "GNOME style" message-tool-bar-gnome)
7444                  (const :tag "Retro look"  message-tool-bar-retro)
7445                  (repeat :tag "User defined list" gmm-tool-bar-item)
7446                  (symbol))
7447   :version "23.1" ;; No Gnus
7448   :initialize 'custom-initialize-default
7449   :set 'message-tool-bar-update
7450   :group 'message)
7451
7452 (defcustom message-tool-bar-gnome
7453   '((ispell-message "spell" nil
7454                     :visible (or (not (boundp 'flyspell-mode))
7455                                  (not flyspell-mode)))
7456     (flyspell-buffer "spell" t
7457                      :visible (and (boundp 'flyspell-mode)
7458                                    flyspell-mode)
7459                      :help "Flyspell whole buffer")
7460     (gmm-ignore "separator")
7461     (message-send-and-exit "mail/send")
7462     (message-dont-send "mail/save-draft")
7463     (message-kill-buffer "close") ;; stock_cancel
7464     (mml-attach-file "attach" mml-mode-map)
7465     (mml-preview "mail/preview" mml-mode-map)
7466     (mml-secure-message-sign-encrypt "lock" mml-mode-map :visible nil)
7467     (message-insert-importance-high "important" nil :visible nil)
7468     (message-insert-importance-low "unimportant" nil :visible nil)
7469     (message-insert-disposition-notification-to "receipt" nil :visible nil)
7470     (gmm-customize-mode "preferences" t :help "Edit mode preferences")
7471     (message-info "help" t :help "Message manual"))
7472   "List of items for the message tool bar (GNOME style).
7473
7474 See `gmm-tool-bar-from-list' for details on the format of the list."
7475   :type '(repeat gmm-tool-bar-item)
7476   :version "23.1" ;; No Gnus
7477   :initialize 'custom-initialize-default
7478   :set 'message-tool-bar-update
7479   :group 'message)
7480
7481 (defcustom message-tool-bar-retro
7482   '(;; Old Emacs 21 icon for consistency.
7483     (message-send-and-exit "gnus/mail-send")
7484     (message-kill-buffer "close")
7485     (message-dont-send "cancel")
7486     (mml-attach-file "attach" mml-mode-map)
7487     (ispell-message "spell")
7488     (mml-preview "preview" mml-mode-map)
7489     (message-insert-importance-high "gnus/important")
7490     (message-insert-importance-low "gnus/unimportant")
7491     (message-insert-disposition-notification-to "gnus/receipt"))
7492   "List of items for the message tool bar (retro style).
7493
7494 See `gmm-tool-bar-from-list' for details on the format of the list."
7495   :type '(repeat gmm-tool-bar-item)
7496   :version "23.1" ;; No Gnus
7497   :initialize 'custom-initialize-default
7498   :set 'message-tool-bar-update
7499   :group 'message)
7500
7501 (defcustom message-tool-bar-zap-list
7502   '(new-file open-file dired kill-buffer write-file
7503              print-buffer customize help)
7504   "List of icon items from the global tool bar.
7505 These items are not displayed on the message mode tool bar.
7506
7507 See `gmm-tool-bar-from-list' for the format of the list."
7508   :type 'gmm-tool-bar-zap-list
7509   :version "23.1" ;; No Gnus
7510   :initialize 'custom-initialize-default
7511   :set 'message-tool-bar-update
7512   :group 'message)
7513
7514 (defvar image-load-path)
7515
7516 (defun message-make-tool-bar (&optional force)
7517   "Make a message mode tool bar from `message-tool-bar-list'.
7518 When FORCE, rebuild the tool bar."
7519   (when (and (not (featurep 'xemacs))
7520              (boundp 'tool-bar-mode)
7521              tool-bar-mode
7522              (or (not message-tool-bar-map) force))
7523     (setq message-tool-bar-map
7524           (let* ((load-path
7525                   (gmm-image-load-path-for-library "message"
7526                                                    "mail/save-draft.xpm"
7527                                                    nil t))
7528                  (image-load-path (cons (car load-path)
7529                                         (when (boundp 'image-load-path)
7530                                           image-load-path))))
7531             (gmm-tool-bar-from-list message-tool-bar
7532                                     message-tool-bar-zap-list
7533                                     'message-mode-map))))
7534   message-tool-bar-map)
7535
7536 ;;; Group name completion.
7537
7538 (defcustom message-newgroups-header-regexp
7539   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
7540   "Regexp that match headers that lists groups."
7541   :group 'message
7542   :type 'regexp)
7543
7544 (defcustom message-completion-alist
7545   (list (cons message-newgroups-header-regexp 'message-expand-group)
7546         '("^\\(Resent-\\)?\\(To\\|B?Cc\\):" . message-expand-name)
7547         '("^\\(Reply-To\\|From\\|Mail-Followup-To\\|Mail-Copies-To\\):"
7548           . message-expand-name)
7549         '("^\\(Disposition-Notification-To\\|Return-Receipt-To\\):"
7550           . message-expand-name))
7551   "Alist of (RE . FUN).  Use FUN for completion on header lines matching RE."
7552   :version "22.1"
7553   :group 'message
7554   :type '(alist :key-type regexp :value-type function))
7555
7556 (defcustom message-expand-name-databases
7557   (list 'bbdb 'eudc)
7558   "List of databases to try for name completion (`message-expand-name').
7559 Each element is a symbol and can be `bbdb' or `eudc'."
7560   :group 'message
7561   :type '(set (const bbdb) (const eudc)))
7562
7563 (defcustom message-tab-body-function nil
7564   "*Function to execute when `message-tab' (TAB) is executed in the body.
7565 If nil, the function bound in `text-mode-map' or `global-map' is executed."
7566   :version "22.1"
7567   :group 'message
7568   :link '(custom-manual "(message)Various Commands")
7569   :type '(choice (const nil)
7570                  function))
7571
7572 (declare-function mail-abbrev-in-expansion-header-p "mailabbrev" ())
7573
7574 (defun message-tab ()
7575   "Complete names according to `message-completion-alist'.
7576 Execute function specified by `message-tab-body-function' when not in
7577 those headers."
7578   (interactive)
7579   (let ((alist message-completion-alist))
7580     (while (and alist
7581                 (let ((mail-abbrev-mode-regexp (caar alist)))
7582                   (not (mail-abbrev-in-expansion-header-p))))
7583       (setq alist (cdr alist)))
7584     (funcall (or (cdar alist) message-tab-body-function
7585                  (lookup-key text-mode-map "\t")
7586                  (lookup-key global-map "\t")
7587                  'indent-relative))))
7588
7589 (eval-and-compile
7590   (condition-case nil
7591       (with-temp-buffer
7592         (let ((standard-output (current-buffer)))
7593           (eval '(display-completion-list nil "")))
7594         (defalias 'message-display-completion-list 'display-completion-list))
7595     (error ;; Don't use `wrong-number-of-arguments' here because of XEmacs.
7596      (defun message-display-completion-list (completions &optional ignore)
7597        "Display the list of completions, COMPLETIONS, using `standard-output'."
7598        (display-completion-list completions)))))
7599
7600 (defun message-expand-group ()
7601   "Expand the group name under point."
7602   (let* ((b (save-excursion
7603               (save-restriction
7604                 (narrow-to-region
7605                  (save-excursion
7606                    (beginning-of-line)
7607                    (skip-chars-forward "^:")
7608                    (1+ (point)))
7609                  (point))
7610                 (skip-chars-backward "^, \t\n") (point))))
7611          (completion-ignore-case t)
7612          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
7613                                             (point))))
7614          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
7615          (completions (all-completions string hashtb))
7616          comp)
7617     (delete-region b (point))
7618     (cond
7619      ((= (length completions) 1)
7620       (if (string= (car completions) string)
7621           (progn
7622             (insert string)
7623             (message "Only matching group"))
7624         (insert (car completions))))
7625      ((and (setq comp (try-completion string hashtb))
7626            (not (string= comp string)))
7627       (insert comp))
7628      (t
7629       (insert string)
7630       (if (not comp)
7631           (message "No matching groups")
7632         (save-selected-window
7633           (pop-to-buffer "*Completions*")
7634           (buffer-disable-undo)
7635           (let ((buffer-read-only nil))
7636             (erase-buffer)
7637             (let ((standard-output (current-buffer)))
7638               (message-display-completion-list (sort completions 'string<)
7639                                                string))
7640             (setq buffer-read-only nil)
7641             (goto-char (point-min))
7642             (delete-region (point) (progn (forward-line 3) (point))))))))))
7643
7644 (defun message-expand-name ()
7645   (cond ((and (memq 'eudc message-expand-name-databases)
7646                     (boundp 'eudc-protocol)
7647                     eudc-protocol)
7648          (eudc-expand-inline))
7649         ((and (memq 'bbdb message-expand-name-databases)
7650               (fboundp 'bbdb-complete-name))
7651          (bbdb-complete-name))
7652         (t
7653          (expand-abbrev))))
7654
7655 ;;; Help stuff.
7656
7657 (defun message-talkative-question (ask question show &rest text)
7658   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
7659 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
7660 The following arguments may contain lists of values."
7661   (if (and show
7662            (setq text (message-flatten-list text)))
7663       (save-window-excursion
7664         (with-output-to-temp-buffer " *MESSAGE information message*"
7665           (with-current-buffer " *MESSAGE information message*"
7666             (fundamental-mode)          ; for Emacs 20.4+
7667             (mapc 'princ text)
7668             (goto-char (point-min))))
7669         (funcall ask question))
7670     (funcall ask question)))
7671
7672 (defun message-flatten-list (list)
7673   "Return a new, flat list that contains all elements of LIST.
7674
7675 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
7676 => (1 2 3 4 5 6 7)"
7677   (cond ((consp list)
7678          (apply 'append (mapcar 'message-flatten-list list)))
7679         (list
7680          (list list))))
7681
7682 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
7683   "Create and return a buffer with name based on NAME using `generate-new-buffer'.
7684 Then clone the local variables and values from the old buffer to the
7685 new one, cloning only the locals having a substring matching the
7686 regexp VARSTR."
7687   (let ((oldbuf (current-buffer)))
7688     (with-current-buffer (generate-new-buffer name)
7689       (message-clone-locals oldbuf varstr)
7690       (current-buffer))))
7691
7692 (defun message-clone-locals (buffer &optional varstr)
7693   "Clone the local variables from BUFFER to the current buffer."
7694   (let ((locals (with-current-buffer buffer (buffer-local-variables)))
7695         (regexp "^gnus\\|^nn\\|^message\\|^sendmail\\|^smtp\\|^user-mail-address"))
7696     (mapcar
7697      (lambda (local)
7698        (when (and (consp local)
7699                   (car local)
7700                   (string-match regexp (symbol-name (car local)))
7701                   (or (null varstr)
7702                       (string-match varstr (symbol-name (car local)))))
7703          (ignore-errors
7704            (set (make-local-variable (car local))
7705                 (cdr local)))))
7706      locals)))
7707
7708 ;;;
7709 ;;; MIME functions
7710 ;;;
7711
7712 (defvar message-inhibit-body-encoding nil)
7713
7714 (defun message-encode-message-body ()
7715   (unless message-inhibit-body-encoding
7716     (let ((mail-parse-charset (or mail-parse-charset
7717                                   message-default-charset))
7718           (case-fold-search t)
7719           lines content-type-p)
7720       (message-goto-body)
7721       (save-restriction
7722         (narrow-to-region (point) (point-max))
7723         (let ((new (mml-generate-mime)))
7724           (when new
7725             (delete-region (point-min) (point-max))
7726             (insert new)
7727             (goto-char (point-min))
7728             (if (eq (aref new 0) ?\n)
7729                 (delete-char 1)
7730               (search-forward "\n\n")
7731               (setq lines (buffer-substring (point-min) (1- (point))))
7732               (delete-region (point-min) (point))))))
7733       (save-restriction
7734         (message-narrow-to-headers-or-head)
7735         (message-remove-header "Mime-Version")
7736         (goto-char (point-max))
7737         (insert "MIME-Version: 1.0\n")
7738         (when lines
7739           (insert lines))
7740         (setq content-type-p
7741               (or mml-boundary
7742                   (re-search-backward "^Content-Type:" nil t))))
7743       (save-restriction
7744         (message-narrow-to-headers-or-head)
7745         (message-remove-first-header "Content-Type")
7746         (message-remove-first-header "Content-Transfer-Encoding"))
7747       ;; We always make sure that the message has a Content-Type
7748       ;; header.  This is because some broken MTAs and MUAs get
7749       ;; awfully confused when confronted with a message with a
7750       ;; MIME-Version header and without a Content-Type header.  For
7751       ;; instance, Solaris' /usr/bin/mail.
7752       (unless content-type-p
7753         (goto-char (point-min))
7754         ;; For unknown reason, MIME-Version doesn't exist.
7755         (when (re-search-forward "^MIME-Version:" nil t)
7756           (forward-line 1)
7757           (insert "Content-Type: text/plain; charset=us-ascii\n"))))))
7758
7759 (defun message-read-from-minibuffer (prompt &optional initial-contents)
7760   "Read from the minibuffer while providing abbrev expansion."
7761   (if (fboundp 'mail-abbrevs-setup)
7762       (let ((mail-abbrev-mode-regexp "")
7763             (minibuffer-setup-hook 'mail-abbrevs-setup)
7764             (minibuffer-local-map message-minibuffer-local-map))
7765         (read-from-minibuffer prompt initial-contents))
7766     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
7767           (minibuffer-local-map message-minibuffer-local-map))
7768       (read-string prompt initial-contents))))
7769
7770 (defun message-use-alternative-email-as-from ()
7771   "Set From field of the outgoing message to the first matching
7772 address in `message-alternative-emails', looking at To, Cc and
7773 From headers in the original article."
7774   (require 'mail-utils)
7775   (let* ((fields '("To" "Cc" "From"))
7776          (emails
7777           (split-string
7778            (mail-strip-quoted-names
7779             (mapconcat 'message-fetch-reply-field fields ","))
7780            "[ \f\t\n\r\v,]+"))
7781          email)
7782     (while emails
7783       (if (string-match message-alternative-emails (car emails))
7784           (setq email (car emails)
7785                 emails nil))
7786       (pop emails))
7787     (unless (or (not email) (equal email user-mail-address))
7788       (message-remove-header "From")
7789       (goto-char (point-max))
7790       (insert "From: " (let ((user-mail-address email)) (message-make-from))
7791               "\n"))))
7792
7793 (defun message-options-get (symbol)
7794   (cdr (assq symbol message-options)))
7795
7796 (defun message-options-set (symbol value)
7797   (let ((the-cons (assq symbol message-options)))
7798     (if the-cons
7799         (if value
7800             (setcdr the-cons value)
7801           (setq message-options (delq the-cons message-options)))
7802       (and value
7803            (push (cons symbol value) message-options))))
7804   value)
7805
7806 (defun message-options-set-recipient ()
7807   (save-restriction
7808     (message-narrow-to-headers-or-head)
7809     (message-options-set 'message-sender
7810                          (mail-strip-quoted-names
7811                           (message-fetch-field "from")))
7812     (message-options-set 'message-recipients
7813                          (mail-strip-quoted-names
7814                           (let ((to (message-fetch-field "to"))
7815                                 (cc (message-fetch-field "cc"))
7816                                 (bcc (message-fetch-field "bcc")))
7817                             (concat
7818                              (or to "")
7819                              (if (and to cc) ", ")
7820                              (or cc "")
7821                              (if (and (or to cc) bcc) ", ")
7822                              (or bcc "")))))))
7823
7824 (defun message-hide-headers ()
7825   "Hide headers based on the `message-hidden-headers' variable."
7826   (let ((regexps (if (stringp message-hidden-headers)
7827                      (list message-hidden-headers)
7828                    message-hidden-headers))
7829         (inhibit-point-motion-hooks t)
7830         (after-change-functions nil)
7831         (end-of-headers (point-min)))
7832     (when regexps
7833       (save-excursion
7834         (save-restriction
7835           (message-narrow-to-headers)
7836           (goto-char (point-min))
7837           (while (not (eobp))
7838             (if (not (message-hide-header-p regexps))
7839                 (message-next-header)
7840               (let ((begin (point))
7841                     header header-len)
7842                 (message-next-header)
7843                 (setq header (buffer-substring begin (point))
7844                       header-len (- (point) begin))
7845                 (delete-region begin (point))
7846                 (goto-char end-of-headers)
7847                 (insert header)
7848                 (setq end-of-headers
7849                       (+ end-of-headers header-len))))))))
7850     (narrow-to-region end-of-headers (point-max))))
7851
7852 (defun message-hide-header-p (regexps)
7853   (let ((result nil)
7854         (reverse nil))
7855     (when (eq (car regexps) 'not)
7856       (setq reverse t)
7857       (pop regexps))
7858     (dolist (regexp regexps)
7859       (setq result (or result (looking-at regexp))))
7860     (if reverse
7861         (not result)
7862       result)))
7863
7864 (defun message-put-addresses-in-ecomplete ()
7865   (dolist (header '("to" "cc" "from" "reply-to"))
7866     (let ((value (message-field-value header)))
7867       (dolist (string (mail-header-parse-addresses value 'raw))
7868         (setq string
7869               (gnus-replace-in-string
7870                (gnus-replace-in-string string "^ +\\| +$" "") "\n" ""))
7871         (ecomplete-add-item 'mail (car (mail-header-parse-address string))
7872                             string))))
7873   (ecomplete-save))
7874
7875 (defun message-display-abbrev (&optional choose)
7876   "Display the next possible abbrev for the text before point."
7877   (interactive (list t))
7878   (when (and (memq (char-after (point-at-bol)) '(?C ?T ?\t ? ))
7879              (message-point-in-header-p)
7880              (save-excursion
7881                (beginning-of-line)
7882                (while (and (memq (char-after) '(?\t ? ))
7883                            (zerop (forward-line -1))))
7884                (looking-at "To:\\|Cc:")))
7885     (let* ((end (point))
7886            (start (save-excursion
7887                     (and (re-search-backward "[\n\t ]" nil t)
7888                          (1+ (point)))))
7889            (word (when start (buffer-substring start end)))
7890            (match (when (and word
7891                              (not (zerop (length word))))
7892                     (ecomplete-display-matches 'mail word choose))))
7893       (when (and choose match)
7894         (delete-region start end)
7895         (insert match)))))
7896
7897 ;; To send pre-formatted letters like the example below, you can use
7898 ;; `message-send-form-letter':
7899 ;; --8<---------------cut here---------------start------------->8---
7900 ;; To: alice@invalid.invalid
7901 ;; Subject: Verification of your contact information
7902 ;; From: Contact verification <admin@foo.invalid>
7903 ;; --text follows this line--
7904 ;; Hi Alice,
7905 ;; please verify that your contact information is still valid:
7906 ;; Alice A, A avenue 11, 1111 A town, Austria
7907 ;; ----------next form letter message follows this line----------
7908 ;; To: bob@invalid.invalid
7909 ;; Subject: Verification of your contact information
7910 ;; From: Contact verification <admin@foo.invalid>
7911 ;; --text follows this line--
7912 ;; Hi Bob,
7913 ;; please verify that your contact information is still valid:
7914 ;; Bob, B street 22, 22222 Be town, Belgium
7915 ;; ----------next form letter message follows this line----------
7916 ;; To: charlie@invalid.invalid
7917 ;; Subject: Verification of your contact information
7918 ;; From: Contact verification <admin@foo.invalid>
7919 ;; --text follows this line--
7920 ;; Hi Charlie,
7921 ;; please verify that your contact information is still valid:
7922 ;; Charlie Chaplin, C plaza 33, 33333 C town, Chile
7923 ;; --8<---------------cut here---------------end--------------->8---
7924
7925 ;; FIXME: What is the most common term (circular letter, form letter, serial
7926 ;; letter, standard letter) for such kind of letter?  See also
7927 ;; <http://en.wikipedia.org/wiki/Form_letter>
7928
7929 ;; FIXME: Maybe extent message-mode's font-lock support to recognize
7930 ;; `message-form-letter-separator', i.e. highlight each message like a single
7931 ;; message.
7932
7933 (defcustom message-form-letter-separator
7934   "\n----------next form letter message follows this line----------\n"
7935   "Separator for `message-send-form-letter'."
7936   ;; :group 'message-form-letter
7937   :group 'message-various
7938   :version "23.1" ;; No Gnus
7939   :type 'string)
7940
7941 (defcustom message-send-form-letter-delay 1
7942   "Delay in seconds when sending a message with `message-send-form-letter'.
7943 Only used when `message-send-form-letter' is called with non-nil
7944 argument `force'."
7945   ;; :group 'message-form-letter
7946   :group 'message-various
7947   :version "23.1" ;; No Gnus
7948   :type 'integer)
7949
7950 (defun message-send-form-letter (&optional force)
7951   "Sent all form letter messages from current buffer.
7952 Unless FORCE, prompt before sending.
7953
7954 The messages are separated by `message-form-letter-separator'.
7955 Header and body are separated by `mail-header-separator'."
7956   (interactive "P")
7957   (let ((sent 0) (skipped 0)
7958         start end text
7959         buff
7960         to done)
7961     (goto-char (point-min))
7962     (while (not done)
7963       (setq start (point)
7964             end (if (search-forward message-form-letter-separator nil t)
7965                     (- (point) (length message-form-letter-separator) -1)
7966                   (setq done t)
7967                   (point-max)))
7968       (setq text
7969             (buffer-substring-no-properties start end))
7970       (setq buff (generate-new-buffer "*mail - form letter*"))
7971       (with-current-buffer buff
7972         (insert text)
7973         (message-mode)
7974         (setq to (message-fetch-field "To"))
7975         (switch-to-buffer buff)
7976         (when force
7977           (sit-for message-send-form-letter-delay))
7978         (if (or force
7979                   (y-or-n-p (format "Send message to `%s'? " to)))
7980             (progn
7981               (setq sent (1+ sent))
7982               (message-send-and-exit))
7983           (message (format "Message to `%s' skipped." to))
7984           (setq skipped (1+ skipped)))
7985         (when (buffer-live-p buff)
7986           (kill-buffer buff))))
7987     (message "%s message(s) sent, %s skipped." sent skipped)))
7988
7989 (defun message-replace-header (header new-value &optional after force)
7990   "Remove HEADER and insert the NEW-VALUE.
7991 If AFTER, insert after this header.  If FORCE, insert new field
7992 even if NEW-VALUE is empty."
7993   ;; Similar to `nnheader-replace-header' but for message buffers.
7994   (save-excursion
7995     (save-restriction
7996       (message-narrow-to-headers)
7997       (message-remove-header header))
7998     (when (or force (> (length new-value) 0))
7999       (if after
8000           (message-position-on-field header after)
8001         (message-position-on-field header))
8002       (insert new-value))))
8003
8004 (defcustom message-recipients-without-full-name
8005   (list "ding@gnus.org"
8006         "bugs@gnus.org"
8007         "emacs-devel@gnu.org"
8008         "emacs-pretest-bug@gnu.org"
8009         "bug-gnu-emacs@gnu.org")
8010   "Mail addresses that have no full name.
8011 Used in `message-simplify-recipients'."
8012   ;; Maybe the addresses could be extracted from
8013   ;; `gnus-parameter-to-list-alist'?
8014   :type '(choice (const :tag "None" nil)
8015                  (repeat string))
8016   :version "23.1" ;; No Gnus
8017   :group 'message-headers)
8018
8019 (defun message-simplify-recipients ()
8020   (interactive)
8021   (dolist (hdr '("Cc" "To"))
8022     (message-replace-header
8023      hdr
8024      (mapconcat
8025       (lambda (addrcomp)
8026         (if (and message-recipients-without-full-name
8027                  (string-match
8028                   (regexp-opt message-recipients-without-full-name)
8029                   (cadr addrcomp)))
8030             (cadr addrcomp)
8031           (if (car addrcomp)
8032               (message-make-from (car addrcomp) (cadr addrcomp))
8033             (cadr addrcomp))))
8034       (when (message-fetch-field hdr)
8035         (mail-extract-address-components
8036          (message-fetch-field hdr) t))
8037       ", "))))
8038
8039 (when (featurep 'xemacs)
8040   (require 'messagexmas)
8041   (message-xmas-redefine))
8042
8043 (provide 'message)
8044
8045 (run-hooks 'message-load-hook)
8046
8047 ;; Local Variables:
8048 ;; coding: iso-8859-1
8049 ;; End:
8050
8051 ;; arch-tag: 94b32cac-4504-4b6c-8181-030ebf380ee0
8052 ;;; message.el ends here