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