2001-06-21 10:00:00 ShengHuo ZHU <zsh@cs.rochester.edu>
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages  -*- coding: iso-latin-1 -*-
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers))       ; gnus-sum is required where necessary
36 (require 'mailheader)
37 (require 'nnheader)
38 ;; This is apparently necessary even though things are autoloaded:
39 (if (featurep 'xemacs)
40     (require 'mail-abbrevs))
41 (require 'mail-parse)
42 (require 'mml)
43
44 (defgroup message '((user-mail-address custom-variable)
45                     (user-full-name custom-variable))
46   "Mail and news message composing."
47   :link '(custom-manual "(message)Top")
48   :group 'mail
49   :group 'news)
50
51 (put 'user-mail-address 'custom-type 'string)
52 (put 'user-full-name 'custom-type 'string)
53
54 (defgroup message-various nil
55   "Various Message Variables"
56   :link '(custom-manual "(message)Various Message Variables")
57   :group 'message)
58
59 (defgroup message-buffers nil
60   "Message Buffers"
61   :link '(custom-manual "(message)Message Buffers")
62   :group 'message)
63
64 (defgroup message-sending nil
65   "Message Sending"
66   :link '(custom-manual "(message)Sending Variables")
67   :group 'message)
68
69 (defgroup message-interface nil
70   "Message Interface"
71   :link '(custom-manual "(message)Interface")
72   :group 'message)
73
74 (defgroup message-forwarding nil
75   "Message Forwarding"
76   :link '(custom-manual "(message)Forwarding")
77   :group 'message-interface)
78
79 (defgroup message-insertion nil
80   "Message Insertion"
81   :link '(custom-manual "(message)Insertion")
82   :group 'message)
83
84 (defgroup message-headers nil
85   "Message Headers"
86   :link '(custom-manual "(message)Message Headers")
87   :group 'message)
88
89 (defgroup message-news nil
90   "Composing News Messages"
91   :group 'message)
92
93 (defgroup message-mail nil
94   "Composing Mail Messages"
95   :group 'message)
96
97 (defgroup message-faces nil
98   "Faces used for message composing."
99   :group 'message
100   :group 'faces)
101
102 (defcustom message-directory "~/Mail/"
103   "*Directory from which all other mail file variables are derived."
104   :group 'message-various
105   :type 'directory)
106
107 (defcustom message-max-buffers 10
108   "*How many buffers to keep before starting to kill them off."
109   :group 'message-buffers
110   :type 'integer)
111
112 (defcustom message-send-rename-function nil
113   "Function called to rename the buffer after sending it."
114   :group 'message-buffers
115   :type '(choice function (const nil)))
116
117 (defcustom message-fcc-handler-function 'message-output
118   "*A function called to save outgoing articles.
119 This function will be called with the name of the file to store the
120 article in.  The default function is `message-output' which saves in Unix
121 mailbox format."
122   :type '(radio (function-item message-output)
123                 (function :tag "Other"))
124   :group 'message-sending)
125
126 (defcustom message-courtesy-message
127   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
128   "*This is inserted at the start of a mailed copy of a posted message.
129 If the string contains the format spec \"%s\", the Newsgroups
130 the article has been posted to will be inserted there.
131 If this variable is nil, no such courtesy message will be added."
132   :group 'message-sending
133   :type 'string)
134
135 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
136   "*Regexp that matches headers to be removed in resent bounced mail."
137   :group 'message-interface
138   :type 'regexp)
139
140 ;;;###autoload
141 (defcustom message-from-style 'default
142   "*Specifies how \"From\" headers look.
143
144 If nil, they contain just the return address like:
145         king@grassland.com
146 If `parens', they look like:
147         king@grassland.com (Elvis Parsley)
148 If `angles', they look like:
149         Elvis Parsley <king@grassland.com>
150
151 Otherwise, most addresses look like `angles', but they look like
152 `parens' if `angles' would need quoting and `parens' would not."
153   :type '(choice (const :tag "simple" nil)
154                  (const parens)
155                  (const angles)
156                  (const default))
157   :group 'message-headers)
158
159 (defcustom message-syntax-checks nil
160   ;; Guess this one shouldn't be easy to customize...
161   "*Controls what syntax checks should not be performed on outgoing posts.
162 To disable checking of long signatures, for instance, add
163  `(signature . disabled)' to this list.
164
165 Don't touch this variable unless you really know what you're doing.
166
167 Checks include `subject-cmsg', `multiple-headers', `sendsys',
168 `message-id', `from', `long-lines', `control-chars', `size',
169 `new-text', `quoting-style', `redirected-followup', `signature',
170 `approved', `sender', `empty', `empty-headers', `message-id', `from',
171 `subject', `shorten-followup-to', `existing-newsgroups',
172 `buffer-file-name', `unchanged', `newsgroups', `reply-to'."
173   :group 'message-news
174   :type '(repeat sexp))                 ; Fixme: improve this
175
176 (defcustom message-required-news-headers
177   '(From Newsgroups Subject Date Message-ID
178          (optional . Organization) Lines
179          (optional . User-Agent))
180   "*Headers to be generated or prompted for when posting an article.
181 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
182 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
183 User-Agent are optional.  If don't you want message to insert some
184 header, remove it from this list."
185   :group 'message-news
186   :group 'message-headers
187   :type '(repeat sexp))
188
189 (defcustom message-required-mail-headers
190   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
191          (optional . User-Agent))
192   "*Headers to be generated or prompted for when mailing a message.
193 RFC822 required that From, Date, To, Subject and Message-ID be
194 included.  Organization, Lines and User-Agent are optional."
195   :group 'message-mail
196   :group 'message-headers
197   :type '(repeat sexp))
198
199 (defcustom message-deletable-headers '(Message-ID Date Lines)
200   "Headers to be deleted if they already exist and were generated by message previously."
201   :group 'message-headers
202   :type 'sexp)
203
204 (defcustom message-ignored-news-headers
205   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|^X-Draft-From:"
206   "*Regexp of headers to be removed unconditionally before posting."
207   :group 'message-news
208   :group 'message-headers
209   :type 'regexp)
210
211 (defcustom message-ignored-mail-headers
212   "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:\\|^X-Draft-From:"
213   "*Regexp of headers to be removed unconditionally before mailing."
214   :group 'message-mail
215   :group 'message-headers
216   :type 'regexp)
217
218 (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:"
219   "*Header lines matching this regexp will be deleted before posting.
220 It's best to delete old Path and Date headers before posting to avoid
221 any confusion."
222   :group 'message-interface
223   :type 'regexp)
224
225 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
226   "*Regexp matching \"Re: \" in the subject line."
227   :group 'message-various
228   :type 'regexp)
229
230 ;;;###autoload
231 (defcustom message-signature-separator "^-- *$"
232   "Regexp matching the signature separator."
233   :type 'regexp
234   :group 'message-various)
235
236 (defcustom message-elide-ellipsis "\n[...]\n\n"
237   "*The string which is inserted for elided text."
238   :type 'string
239   :group 'message-various)
240
241 (defcustom message-interactive nil
242   "Non-nil means when sending a message wait for and display errors.
243 nil means let mailer mail back a message to report errors."
244   :group 'message-sending
245   :group 'message-mail
246   :type 'boolean)
247
248 (defcustom message-generate-new-buffers 'unique
249   "*Non-nil means create a new message buffer whenever `message-setup' is called.
250 If this is a function, call that function with three parameters:  The type,
251 the to address and the group name.  (Any of these may be nil.)  The function
252 should return the new buffer name."
253   :group 'message-buffers
254   :type '(choice (const :tag "off" nil)
255                  (const :tag "unique" unique)
256                  (const :tag "unsent" unsent)
257                  (function fun)))
258
259 (defcustom message-kill-buffer-on-exit nil
260   "*Non-nil means that the message buffer will be killed after sending a message."
261   :group 'message-buffers
262   :type 'boolean)
263
264 (eval-when-compile
265   (defvar gnus-local-organization))
266 (defcustom message-user-organization
267   (or (and (boundp 'gnus-local-organization)
268            (stringp gnus-local-organization)
269            gnus-local-organization)
270       (getenv "ORGANIZATION")
271       t)
272   "*String to be used as an Organization header.
273 If t, use `message-user-organization-file'."
274   :group 'message-headers
275   :type '(choice string
276                  (const :tag "consult file" t)))
277
278 ;;;###autoload
279 (defcustom message-user-organization-file "/usr/lib/news/organization"
280   "*Local news organization file."
281   :type 'file
282   :group 'message-headers)
283
284 (defcustom message-make-forward-subject-function
285   'message-forward-subject-author-subject
286   "*List of functions called to generate subject headers for forwarded messages.
287 The subject generated by the previous function is passed into each
288 successive function.
289
290 The provided functions are:
291
292 * `message-forward-subject-author-subject' (Source of article (author or
293       newsgroup)), in brackets followed by the subject
294 * `message-forward-subject-fwd' (Subject of article with 'Fwd:' prepended
295       to it."
296   :group 'message-forwarding
297   :type '(radio (function-item message-forward-subject-author-subject)
298                 (function-item message-forward-subject-fwd)
299                 (repeat :tag "List of functions" function)))
300
301 (defcustom message-forward-as-mime t
302   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
303   :version "21.1"
304   :group 'message-forwarding
305   :type 'boolean)
306
307 (defcustom message-forward-show-mml t
308   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
309   :version "21.1"
310   :group 'message-forwarding
311   :type 'boolean)
312
313 (defcustom message-forward-before-signature t
314   "*If non-nil, put forwarded message before signature, else after."
315   :group 'message-forwarding
316   :type 'boolean)
317
318 (defcustom message-wash-forwarded-subjects nil
319   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
320   :group 'message-forwarding
321   :type 'boolean)
322
323 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
324   "*All headers that match this regexp will be deleted when resending a message."
325   :group 'message-interface
326   :type 'regexp)
327
328 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
329   "*All headers that match this regexp will be deleted when forwarding a message."
330   :version "21.1"
331   :group 'message-forwarding
332   :type '(choice (const :tag "None" nil)
333                  regexp))
334
335 (defcustom message-ignored-cited-headers "."
336   "*Delete these headers from the messages you yank."
337   :group 'message-insertion
338   :type 'regexp)
339
340 (defcustom message-cite-prefix-regexp
341   (if (string-match "[[:digit:]]" "1") ;; support POSIX?
342       "\\([ \t]*[-_.[:word:]]+>+\\|[ \t]*[]>»|:}+]\\)+"
343     ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
344     "\\([ \t]*\\(\\w\\|[-_.]\\)+>+\\|[ \t]*[]>»|:}+]\\)+")
345   "*Regexp matching the longest possible citation prefix on a line."
346   :group 'message-insertion
347   :type 'regexp)
348
349 (defcustom message-cancel-message "I am canceling my own article.\n"
350   "Message to be inserted in the cancel message."
351   :group 'message-interface
352   :type 'string)
353
354 ;; Useful to set in site-init.el
355 ;;;###autoload
356 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
357   "Function to call to send the current buffer as mail.
358 The headers should be delimited by a line whose contents match the
359 variable `mail-header-separator'.
360
361 Valid values include `message-send-mail-with-sendmail' (the default),
362 `message-send-mail-with-mh', `message-send-mail-with-qmail',
363 `smtpmail-send-it' and `feedmail-send-it'.
364
365 See also `send-mail-function'."
366   :type '(radio (function-item message-send-mail-with-sendmail)
367                 (function-item message-send-mail-with-mh)
368                 (function-item message-send-mail-with-qmail)
369                 (function-item smtpmail-send-it)
370                 (function-item feedmail-send-it)
371                 (function :tag "Other"))
372   :group 'message-sending
373   :group 'message-mail)
374
375 (defcustom message-send-news-function 'message-send-news
376   "Function to call to send the current buffer as news.
377 The headers should be delimited by a line whose contents match the
378 variable `mail-header-separator'."
379   :group 'message-sending
380   :group 'message-news
381   :type 'function)
382
383 (defcustom message-reply-to-function nil
384   "If non-nil, function that should return a list of headers.
385 This function should pick out addresses from the To, Cc, and From headers
386 and respond with new To and Cc headers."
387   :group 'message-interface
388   :type '(choice function (const nil)))
389
390 (defcustom message-wide-reply-to-function nil
391   "If non-nil, function that should return a list of headers.
392 This function should pick out addresses from the To, Cc, and From headers
393 and respond with new To and Cc headers."
394   :group 'message-interface
395   :type '(choice function (const nil)))
396
397 (defcustom message-followup-to-function nil
398   "If non-nil, function that should return a list of headers.
399 This function should pick out addresses from the To, Cc, and From headers
400 and respond with new To and Cc headers."
401   :group 'message-interface
402   :type '(choice function (const nil)))
403
404 (defcustom message-use-followup-to t
405   "*Specifies what to do with Followup-To header.
406 If nil, always ignore the header.  If it is t, use its value, but
407 query before using the \"poster\" value.  If it is the symbol `ask',
408 always query the user whether to use the value.  If it is the symbol
409 `use', always use the value."
410   :group 'message-interface
411   :type '(choice (const :tag "ignore" nil)
412                  (const :tag "use & query" t)
413                  (const use)
414                  (const ask)))
415
416 (defcustom message-sendmail-f-is-evil nil
417   "*Non-nil means don't add \"-f username\" to the sendmail command line.
418 Doing so would be even more evil than leaving it out."
419   :group 'message-sending
420   :type 'boolean)
421
422 ;; qmail-related stuff
423 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
424   "Location of the qmail-inject program."
425   :group 'message-sending
426   :type 'file)
427
428 (defcustom message-qmail-inject-args nil
429   "Arguments passed to qmail-inject programs.
430 This should be a list of strings, one string for each argument.
431
432 For e.g., if you wish to set the envelope sender address so that bounces
433 go to the right place or to deal with listserv's usage of that address, you
434 might set this variable to '(\"-f\" \"you@some.where\")."
435   :group 'message-sending
436   :type '(repeat string))
437
438 (defvar message-cater-to-broken-inn t
439   "Non-nil means Gnus should not fold the `References' header.
440 Folding `References' makes ancient versions of INN create incorrect
441 NOV lines.")
442
443 (eval-when-compile
444   (defvar gnus-post-method)
445   (defvar gnus-select-method))
446 (defcustom message-post-method
447   (cond ((and (boundp 'gnus-post-method)
448               (listp gnus-post-method)
449               gnus-post-method)
450          gnus-post-method)
451         ((boundp 'gnus-select-method)
452          gnus-select-method)
453         (t '(nnspool "")))
454   "*Method used to post news.
455 Note that when posting from inside Gnus, for instance, this
456 variable isn't used."
457   :group 'message-news
458   :group 'message-sending
459   ;; This should be the `gnus-select-method' widget, but that might
460   ;; create a dependence to `gnus.el'.
461   :type 'sexp)
462
463 (defcustom message-generate-headers-first nil
464   "*If non-nil, generate all required headers before composing.
465 The variables `message-required-news-headers' and
466 `message-required-mail-headers' specify which headers to generate.
467
468 Note that the variable `message-deletable-headers' specifies headers which
469 are to be deleted and then re-generated before sending, so this variable
470 will not have a visible effect for those headers."
471   :group 'message-headers
472   :type 'boolean)
473
474 (defcustom message-setup-hook nil
475   "Normal hook, run each time a new outgoing message is initialized.
476 The function `message-setup' runs this hook."
477   :group 'message-various
478   :type 'hook)
479
480 (defcustom message-cancel-hook nil
481   "Hook run when cancelling articles."
482   :group 'message-various
483   :type 'hook)
484
485 (defcustom message-signature-setup-hook nil
486   "Normal hook, run each time a new outgoing message is initialized.
487 It is run after the headers have been inserted and before
488 the signature is inserted."
489   :group 'message-various
490   :type 'hook)
491
492 (defcustom message-mode-hook nil
493   "Hook run in message mode buffers."
494   :group 'message-various
495   :type 'hook)
496
497 (defcustom message-header-hook nil
498   "Hook run in a message mode buffer narrowed to the headers."
499   :group 'message-various
500   :type 'hook)
501
502 (defcustom message-header-setup-hook nil
503   "Hook called narrowed to the headers when setting up a message buffer."
504   :group 'message-various
505   :type 'hook)
506
507 (defcustom message-minibuffer-local-map
508   (let ((map (make-sparse-keymap 'message-minibuffer-local-map)))
509     (set-keymap-parent map minibuffer-local-map)
510     map)
511   "Keymap for `message-read-from-minibuffer'.")
512
513 ;;;###autoload
514 (defcustom message-citation-line-function 'message-insert-citation-line
515   "*Function called to insert the \"Whomever writes:\" line."
516   :type 'function
517   :group 'message-insertion)
518
519 ;;;###autoload
520 (defcustom message-yank-prefix "> "
521   "*Prefix inserted on the lines of yanked messages.
522 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
523 See also `message-yank-cited-prefix'."
524   :type 'string
525   :group 'message-insertion)
526
527 (defcustom message-yank-cited-prefix ">"
528   "*Prefix inserted on cited lines of yanked messages.
529 Fix `message-cite-prefix-regexp' if it is set to an abnormal value.
530 See also `message-yank-prefix'."
531   :type 'string
532   :group 'message-insertion)
533
534 (defcustom message-indentation-spaces 3
535   "*Number of spaces to insert at the beginning of each cited line.
536 Used by `message-yank-original' via `message-yank-cite'."
537   :group 'message-insertion
538   :type 'integer)
539
540 ;;;###autoload
541 (defcustom message-cite-function 'message-cite-original
542   "*Function for citing an original message.
543 Predefined functions include `message-cite-original' and
544 `message-cite-original-without-signature'.
545 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
546   :type '(radio (function-item message-cite-original)
547                 (function-item message-cite-original-without-signature)
548                 (function-item sc-cite-original)
549                 (function :tag "Other"))
550   :group 'message-insertion)
551
552 ;;;###autoload
553 (defcustom message-indent-citation-function 'message-indent-citation
554   "*Function for modifying a citation just inserted in the mail buffer.
555 This can also be a list of functions.  Each function can find the
556 citation between (point) and (mark t).  And each function should leave
557 point and mark around the citation text as modified."
558   :type 'function
559   :group 'message-insertion)
560
561 (defvar message-abbrevs-loaded nil)
562
563 ;;;###autoload
564 (defcustom message-signature t
565   "*String to be inserted at the end of the message buffer.
566 If t, the `message-signature-file' file will be inserted instead.
567 If a function, the result from the function will be used instead.
568 If a form, the result from the form will be used instead."
569   :type 'sexp
570   :group 'message-insertion)
571
572 ;;;###autoload
573 (defcustom message-signature-file "~/.signature"
574   "*Name of file containing the text inserted at end of message buffer.
575 Ignored if the named file doesn't exist.
576 If nil, don't insert a signature."
577   :type '(choice file (const :tags "None" nil))
578   :group 'message-insertion)
579
580 (defcustom message-distribution-function nil
581   "*Function called to return a Distribution header."
582   :group 'message-news
583   :group 'message-headers
584   :type '(choice function (const nil)))
585
586 (defcustom message-expires 14
587   "Number of days before your article expires."
588   :group 'message-news
589   :group 'message-headers
590   :link '(custom-manual "(message)News Headers")
591   :type 'integer)
592
593 (defcustom message-user-path nil
594   "If nil, use the NNTP server name in the Path header.
595 If stringp, use this; if non-nil, use no host name (user name only)."
596   :group 'message-news
597   :group 'message-headers
598   :link '(custom-manual "(message)News Headers")
599   :type '(choice (const :tag "nntp" nil)
600                  (string :tag "name")
601                  (sexp :tag "none" :format "%t" t)))
602
603 (defvar message-reply-buffer nil)
604 (defvar message-reply-headers nil)
605 (defvar message-newsreader nil)
606 (defvar message-mailer nil)
607 (defvar message-sent-message-via nil)
608 (defvar message-checksum nil)
609 (defvar message-send-actions nil
610   "A list of actions to be performed upon successful sending of a message.")
611 (defvar message-exit-actions nil
612   "A list of actions to be performed upon exiting after sending a message.")
613 (defvar message-kill-actions nil
614   "A list of actions to be performed before killing a message buffer.")
615 (defvar message-postpone-actions nil
616   "A list of actions to be performed after postponing a message.")
617
618 (define-widget 'message-header-lines 'text
619   "All header lines must be LFD terminated."
620   :format "%{%t%}:%n%v"
621   :valid-regexp "^\\'"
622   :error "All header lines must be newline terminated")
623
624 (defcustom message-default-headers ""
625   "*A string containing header lines to be inserted in outgoing messages.
626 It is inserted before you edit the message, so you can edit or delete
627 these lines."
628   :group 'message-headers
629   :type 'message-header-lines)
630
631 (defcustom message-default-mail-headers ""
632   "*A string of header lines to be inserted in outgoing mails."
633   :group 'message-headers
634   :group 'message-mail
635   :type 'message-header-lines)
636
637 (defcustom message-default-news-headers ""
638   "*A string of header lines to be inserted in outgoing news articles."
639   :group 'message-headers
640   :group 'message-news
641   :type 'message-header-lines)
642
643 ;; Note: could use /usr/ucb/mail instead of sendmail;
644 ;; options -t, and -v if not interactive.
645 (defcustom message-mailer-swallows-blank-line
646   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
647                          system-configuration)
648            (file-readable-p "/etc/sendmail.cf")
649            (let ((buffer (get-buffer-create " *temp*")))
650              (unwind-protect
651                  (save-excursion
652                    (set-buffer buffer)
653                    (insert-file-contents "/etc/sendmail.cf")
654                    (goto-char (point-min))
655                    (let ((case-fold-search nil))
656                      (re-search-forward "^OR\\>" nil t)))
657                (kill-buffer buffer))))
658       ;; According to RFC822, "The field-name must be composed of printable
659       ;; ASCII characters (i. e., characters that have decimal values between
660       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
661       ;; space, or colon.
662       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
663   "*Set this non-nil if the system's mailer runs the header and body together.
664 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
665 The value should be an expression to test whether the problem will
666 actually occur."
667   :group 'message-sending
668   :type 'sexp)
669
670 ;;;###autoload
671 (define-mail-user-agent 'message-user-agent
672   'message-mail 'message-send-and-exit
673   'message-kill-buffer 'message-send-hook)
674
675 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
676   "If non-nil, delete the deletable headers before feeding to mh.")
677
678 (defvar message-send-method-alist
679   '((news message-news-p message-send-via-news)
680     (mail message-mail-p message-send-via-mail))
681   "Alist of ways to send outgoing messages.
682 Each element has the form
683
684   \(TYPE PREDICATE FUNCTION)
685
686 where TYPE is a symbol that names the method; PREDICATE is a function
687 called without any parameters to determine whether the message is
688 a message of type TYPE; and FUNCTION is a function to be called if
689 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
690 the prefix.")
691
692 (defcustom message-mail-alias-type 'abbrev
693   "*What alias expansion type to use in Message buffers.
694 The default is `abbrev', which uses mailabbrev.  nil switches
695 mail aliases off."
696   :group 'message
697   :link '(custom-manual "(message)Mail Aliases")
698   :type '(choice (const :tag "Use Mailabbrev" abbrev)
699                  (const :tag "No expansion" nil)))
700
701 (defcustom message-auto-save-directory
702   (file-name-as-directory (nnheader-concat message-directory "drafts"))
703   "*Directory where Message auto-saves buffers if Gnus isn't running.
704 If nil, Message won't auto-save."
705   :group 'message-buffers
706   :type '(choice directory (const :tag "Don't auto-save" nil)))
707
708 (defcustom message-buffer-naming-style 'unique
709   "*The way new message buffers are named.
710 Valid valued are `unique' and `unsent'."
711   :version "21.1"
712   :group 'message-buffers
713   :type '(choice (const :tag "unique" unique)
714                  (const :tag "unsent" unsent)))
715
716 (defcustom message-default-charset
717   (and (not (mm-multibyte-p)) 'iso-8859-1)
718   "Default charset used in non-MULE Emacsen.
719 If nil, you might be asked to input the charset."
720   :version "21.1"
721   :group 'message
722   :type 'symbol)
723
724 (defcustom message-dont-reply-to-names
725   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
726   "*A regexp specifying addresses to prune when doing wide replies.
727 A value of nil means exclude your own user name only."
728   :version "21.1"
729   :group 'message
730   :type '(choice (const :tag "Yourself" nil)
731                  regexp))
732
733 (defvar message-shoot-gnksa-feet nil
734   "*A list of GNKSA feet you are allowed to shoot.
735 Gnus gives you all the opportunity you could possibly want for
736 shooting yourself in the foot.  Also, Gnus allows you to shoot the
737 feet of Good Net-Keeping Seal of Approval. The following are foot
738 candidates:
739 `empty-article'     Allow you to post an empty article;
740 `quoted-text-only'  Allow you to post quoted text only;
741 `multiple-copies'   Allow you to post multiple copies.")
742 ;; `cancel-messages'   Allow you to cancel or supersede others' messages.
743
744 (defsubst message-gnksa-enable-p (feature)
745   (or (not (listp message-shoot-gnksa-feet))
746       (memq feature message-shoot-gnksa-feet)))
747
748 ;;; Internal variables.
749 ;;; Well, not really internal.
750
751 (defvar message-mode-syntax-table
752   (let ((table (copy-syntax-table text-mode-syntax-table)))
753     (modify-syntax-entry ?% ". " table)
754     (modify-syntax-entry ?> ". " table)
755     (modify-syntax-entry ?< ". " table)
756     table)
757   "Syntax table used while in Message mode.")
758
759 (defvar message-mode-abbrev-table text-mode-abbrev-table
760   "Abbrev table used in Message mode buffers.
761 Defaults to `text-mode-abbrev-table'.")
762
763 (defface message-header-to-face
764   '((((class color)
765       (background dark))
766      (:foreground "green2" :bold t))
767     (((class color)
768       (background light))
769      (:foreground "MidnightBlue" :bold t))
770     (t
771      (:bold t :italic t)))
772   "Face used for displaying From headers."
773   :group 'message-faces)
774
775 (defface message-header-cc-face
776   '((((class color)
777       (background dark))
778      (:foreground "green4" :bold t))
779     (((class color)
780       (background light))
781      (:foreground "MidnightBlue"))
782     (t
783      (:bold t)))
784   "Face used for displaying Cc headers."
785   :group 'message-faces)
786
787 (defface message-header-subject-face
788   '((((class color)
789       (background dark))
790      (:foreground "green3"))
791     (((class color)
792       (background light))
793      (:foreground "navy blue" :bold t))
794     (t
795      (:bold t)))
796   "Face used for displaying subject headers."
797   :group 'message-faces)
798
799 (defface message-header-newsgroups-face
800   '((((class color)
801       (background dark))
802      (:foreground "yellow" :bold t :italic t))
803     (((class color)
804       (background light))
805      (:foreground "blue4" :bold t :italic t))
806     (t
807      (:bold t :italic t)))
808   "Face used for displaying newsgroups headers."
809   :group 'message-faces)
810
811 (defface message-header-other-face
812   '((((class color)
813       (background dark))
814      (:foreground "#b00000"))
815     (((class color)
816       (background light))
817      (:foreground "steel blue"))
818     (t
819      (:bold t :italic t)))
820   "Face used for displaying newsgroups headers."
821   :group 'message-faces)
822
823 (defface message-header-name-face
824   '((((class color)
825       (background dark))
826      (:foreground "DarkGreen"))
827     (((class color)
828       (background light))
829      (:foreground "cornflower blue"))
830     (t
831      (:bold t)))
832   "Face used for displaying header names."
833   :group 'message-faces)
834
835 (defface message-header-xheader-face
836   '((((class color)
837       (background dark))
838      (:foreground "blue"))
839     (((class color)
840       (background light))
841      (:foreground "blue"))
842     (t
843      (:bold t)))
844   "Face used for displaying X-Header headers."
845   :group 'message-faces)
846
847 (defface message-separator-face
848   '((((class color)
849       (background dark))
850      (:foreground "blue3"))
851     (((class color)
852       (background light))
853      (:foreground "brown"))
854     (t
855      (:bold t)))
856   "Face used for displaying the separator."
857   :group 'message-faces)
858
859 (defface message-cited-text-face
860   '((((class color)
861       (background dark))
862      (:foreground "red"))
863     (((class color)
864       (background light))
865      (:foreground "red"))
866     (t
867      (:bold t)))
868   "Face used for displaying cited text names."
869   :group 'message-faces)
870
871 (defface message-mml-face
872   '((((class color)
873       (background dark))
874      (:foreground "ForestGreen"))
875     (((class color)
876       (background light))
877      (:foreground "ForestGreen"))
878     (t
879      (:bold t)))
880   "Face used for displaying MML."
881   :group 'message-faces)
882
883 (defvar message-font-lock-keywords
884   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
885     `((,(concat "^\\([Tt]o:\\)" content)
886        (1 'message-header-name-face)
887        (2 'message-header-to-face nil t))
888       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
889        (1 'message-header-name-face)
890        (2 'message-header-cc-face nil t))
891       (,(concat "^\\([Ss]ubject:\\)" content)
892        (1 'message-header-name-face)
893        (2 'message-header-subject-face nil t))
894       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
895        (1 'message-header-name-face)
896        (2 'message-header-newsgroups-face nil t))
897       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
898        (1 'message-header-name-face)
899        (2 'message-header-other-face nil t))
900       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
901        (1 'message-header-name-face)
902        (2 'message-header-name-face))
903       ,@(if (and mail-header-separator
904                  (not (equal mail-header-separator "")))
905             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
906                1 'message-separator-face))
907           nil)
908       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
909        (0 'message-cited-text-face))
910       ("<#/?\\(multipart\\|part\\|external\\|mml\\).*>"
911        (0 'message-mml-face))))
912   "Additional expressions to highlight in Message mode.")
913
914 ;; XEmacs does it like this.  For Emacs, we have to set the
915 ;; `font-lock-defaults' buffer-local variable.
916 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
917
918 (defvar message-face-alist
919   '((bold . bold-region)
920     (underline . underline-region)
921     (default . (lambda (b e)
922                  (unbold-region b e)
923                  (ununderline-region b e))))
924   "Alist of mail and news faces for facemenu.
925 The cdr of ech entry is a function for applying the face to a region.")
926
927 (defcustom message-send-hook nil
928   "Hook run before sending messages."
929   :group 'message-various
930   :options '(ispell-message)
931   :type 'hook)
932
933 (defcustom message-send-mail-hook nil
934   "Hook run before sending mail messages."
935   :group 'message-various
936   :type 'hook)
937
938 (defcustom message-send-news-hook nil
939   "Hook run before sending news messages."
940   :group 'message-various
941   :type 'hook)
942
943 (defcustom message-sent-hook nil
944   "Hook run after sending messages."
945   :group 'message-various
946   :type 'hook)
947
948 (defvar message-send-coding-system 'binary
949   "Coding system to encode outgoing mail.")
950
951 (defvar message-draft-coding-system
952   mm-auto-save-coding-system
953   "Coding system to compose mail.")
954
955 (defcustom message-send-mail-partially-limit 1000000
956   "The limitation of messages sent as message/partial.
957 The lower bound of message size in characters, beyond which the message
958 should be sent in several parts.  If it is nil, the size is unlimited."
959   :version "21.1"
960   :group 'message-buffers
961   :type '(choice (const :tag "unlimited" nil)
962                  (integer 1000000)))
963
964 (defcustom message-alternative-emails nil
965   "A regexp to match the alternative email addresses.
966 The first matched address (not primary one) is used in the From field."
967   :group 'message-headers
968   :type '(choice (const :tag "Always use primary" nil)
969                  regexp))
970
971 (defcustom message-mail-user-agent nil
972   "Like `mail-user-agent'.
973 Except if it is nil, use Gnus native MUA; if it is t, use
974 `mail-user-agent'."
975   :type '(radio (const :tag "Gnus native"
976                        :format "%t\n"
977                        nil)
978                 (const :tag "`mail-user-agent'"
979                        :format "%t\n"
980                        t)
981                 (function-item :tag "Default Emacs mail"
982                                :format "%t\n"
983                                sendmail-user-agent)
984                 (function-item :tag "Emacs interface to MH"
985                                :format "%t\n"
986                                mh-e-user-agent)
987                 (function :tag "Other"))
988   :version "21.1"
989   :group 'message)
990
991 (defcustom message-wide-reply-confirm-recipients nil
992   "Whether to confirm a wide reply to multiple email recipients.
993 If this variable is nil, don't ask whether to reply to all recipients.
994 If this variable is non-nil, pose the question \"Reply to all
995 recipients?\" before a wide reply to multiple recipients.  If the user
996 answers yes, reply to all recipients as usual.  If the user answers
997 no, only reply back to the author."
998   :group 'message-headers
999   :type 'boolean)
1000
1001 ;;; Internal variables.
1002
1003 (defvar message-sending-message "Sending...")
1004 (defvar message-buffer-list nil)
1005 (defvar message-this-is-news nil)
1006 (defvar message-this-is-mail nil)
1007 (defvar message-draft-article nil)
1008 (defvar message-mime-part nil)
1009 (defvar message-posting-charset nil)
1010
1011 ;; Byte-compiler warning
1012 (eval-when-compile
1013   (defvar gnus-active-hashtb)
1014   (defvar gnus-read-active-file))
1015
1016 ;;; Regexp matching the delimiter of messages in UNIX mail format
1017 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
1018 ;;; of rmail.el's rmail-unix-mail-delimiter.
1019 (defvar message-unix-mail-delimiter
1020   (let ((time-zone-regexp
1021          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
1022                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
1023                  "\\|"
1024                  "\\) *")))
1025     (concat
1026      "From "
1027
1028      ;; Many things can happen to an RFC 822 mailbox before it is put into
1029      ;; a `From' line.  The leading phrase can be stripped, e.g.
1030      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
1031      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
1032      ;; can be removed, e.g.
1033      ;;         From: joe@y.z (Joe      K
1034      ;;                 User)
1035      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
1036      ;;         From: Joe User
1037      ;;                 <joe@y.z>
1038      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
1039      ;; The mailbox can be removed or be replaced by white space, e.g.
1040      ;;         From: "Joe User"{space}{tab}
1041      ;;                 <joe@y.z>
1042      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1043      ;; where {space} and {tab} represent the Ascii space and tab characters.
1044      ;; We want to match the results of any of these manglings.
1045      ;; The following regexp rejects names whose first characters are
1046      ;; obviously bogus, but after that anything goes.
1047      "\\([^\0-\b\n-\r\^?].*\\)? "
1048
1049      ;; The time the message was sent.
1050      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1051      "\\([^\0-\r \^?]+\\) +"            ; month
1052      "\\([0-3]?[0-9]\\) +"              ; day of month
1053      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1054
1055      ;; Perhaps a time zone, specified by an abbreviation, or by a
1056      ;; numeric offset.
1057      time-zone-regexp
1058
1059      ;; The year.
1060      " \\([0-9][0-9]+\\) *"
1061
1062      ;; On some systems the time zone can appear after the year, too.
1063      time-zone-regexp
1064
1065      ;; Old uucp cruft.
1066      "\\(remote from .*\\)?"
1067
1068      "\n"))
1069   "Regexp matching the delimiter of messages in UNIX mail format.")
1070
1071 (defvar message-unsent-separator
1072   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1073           "^ *---+ +Returned message +---+ *$\\|"
1074           "^Start of returned message$\\|"
1075           "^ *---+ +Original message +---+ *$\\|"
1076           "^ *--+ +begin message +--+ *$\\|"
1077           "^ *---+ +Original message follows +---+ *$\\|"
1078           "^ *---+ +Undelivered message follows +---+ *$\\|"
1079           "^|? *---+ +Message text follows: +---+ *|?$")
1080   "A regexp that matches the separator before the text of a failed message.")
1081
1082 (defvar message-header-format-alist
1083   `((Newsgroups)
1084     (To . message-fill-address)
1085     (Cc . message-fill-address)
1086     (Subject)
1087     (In-Reply-To)
1088     (Fcc)
1089     (Bcc)
1090     (Date)
1091     (Organization)
1092     (Distribution)
1093     (Lines)
1094     (Expires)
1095     (Message-ID)
1096     (References . message-shorten-references)
1097     (User-Agent))
1098   "Alist used for formatting headers.")
1099
1100 (defvar message-options nil
1101   "Some saved answers when sending message.")
1102
1103 (eval-and-compile
1104   (autoload 'message-setup-toolbar "messagexmas")
1105   (autoload 'mh-new-draft-name "mh-comp")
1106   (autoload 'mh-send-letter "mh-comp")
1107   (autoload 'gnus-point-at-eol "gnus-util")
1108   (autoload 'gnus-point-at-bol "gnus-util")
1109   (autoload 'gnus-output-to-rmail "gnus-util")
1110   (autoload 'gnus-output-to-mail "gnus-util")
1111   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1112   (autoload 'nndraft-request-associate-buffer "nndraft")
1113   (autoload 'nndraft-request-expire-articles "nndraft")
1114   (autoload 'gnus-open-server "gnus-int")
1115   (autoload 'gnus-request-post "gnus-int")
1116   (autoload 'gnus-alive-p "gnus-util")
1117   (autoload 'gnus-server-string "gnus")
1118   (autoload 'gnus-group-name-charset "gnus-group")
1119   (autoload 'rmail-output "rmailout"))
1120
1121 \f
1122
1123 ;;;
1124 ;;; Utility functions.
1125 ;;;
1126
1127 (defmacro message-y-or-n-p (question show &rest text)
1128   "Ask QUESTION, displaying remaining args in a temporary buffer if SHOW."
1129   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1130
1131 (defmacro message-delete-line (&optional n)
1132   "Delete the current line (and the next N lines)."
1133   `(delete-region (progn (beginning-of-line) (point))
1134                   (progn (forward-line ,(or n 1)) (point))))
1135
1136 (defun message-unquote-tokens (elems)
1137   "Remove double quotes (\") from strings in list ELEMS."
1138   (mapcar (lambda (item)
1139             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1140               (setq item (concat (match-string 1 item)
1141                                  (match-string 2 item))))
1142             item)
1143           elems))
1144
1145 (defun message-tokenize-header (header &optional separator)
1146   "Split HEADER into a list of header elements.
1147 SEPARATOR is a string of characters to be used as separators.  \",\"
1148 is used by default."
1149   (if (not header)
1150       nil
1151     (let ((regexp (format "[%s]+" (or separator ",")))
1152           (beg 1)
1153           (first t)
1154           quoted elems paren)
1155       (save-excursion
1156         (message-set-work-buffer)
1157         (insert header)
1158         (goto-char (point-min))
1159         (while (not (eobp))
1160           (if first
1161               (setq first nil)
1162             (forward-char 1))
1163           (cond ((and (> (point) beg)
1164                       (or (eobp)
1165                           (and (looking-at regexp)
1166                                (not quoted)
1167                                (not paren))))
1168                  (push (buffer-substring beg (point)) elems)
1169                  (setq beg (match-end 0)))
1170                 ((eq (char-after) ?\")
1171                  (setq quoted (not quoted)))
1172                 ((and (eq (char-after) ?\()
1173                       (not quoted))
1174                  (setq paren t))
1175                 ((and (eq (char-after) ?\))
1176                       (not quoted))
1177                  (setq paren nil))))
1178         (nreverse elems)))))
1179
1180 (defun message-mail-file-mbox-p (file)
1181   "Say whether FILE looks like a Unix mbox file."
1182   (when (and (file-exists-p file)
1183              (file-readable-p file)
1184              (file-regular-p file))
1185     (with-temp-buffer
1186       (nnheader-insert-file-contents file)
1187       (goto-char (point-min))
1188       (looking-at message-unix-mail-delimiter))))
1189
1190 (defun message-fetch-field (header &optional not-all)
1191   "The same as `mail-fetch-field', only remove all newlines."
1192   (let* ((inhibit-point-motion-hooks t)
1193          (case-fold-search t)
1194          (value (mail-fetch-field header nil (not not-all))))
1195     (when value
1196       (while (string-match "\n[\t ]+" value)
1197         (setq value (replace-match " " t t value)))
1198       (set-text-properties 0 (length value) nil value)
1199       value)))
1200
1201 (defun message-narrow-to-field ()
1202   "Narrow the buffer to the header on the current line."
1203   (beginning-of-line)
1204   (narrow-to-region
1205    (point)
1206    (progn
1207      (forward-line 1)
1208      (if (re-search-forward "^[^ \n\t]" nil t)
1209          (progn
1210            (beginning-of-line)
1211            (point))
1212        (point-max))))
1213   (goto-char (point-min)))
1214
1215 (defun message-add-header (&rest headers)
1216   "Add the HEADERS to the message header, skipping those already present."
1217   (while headers
1218     (let (hclean)
1219       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1220         (error "Invalid header `%s'" (car headers)))
1221       (setq hclean (match-string 1 (car headers)))
1222       (save-restriction
1223         (message-narrow-to-headers)
1224         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1225           (goto-char (point-max))
1226           (if (string-match "\n$" (car headers))
1227               (insert (car headers))
1228             (insert (car headers) ?\n)))))
1229     (setq headers (cdr headers))))
1230
1231
1232 (defun message-fetch-reply-field (header)
1233   "Fetch field HEADER from the message we're replying to."
1234   (when (and message-reply-buffer
1235              (buffer-name message-reply-buffer))
1236     (save-excursion
1237       (set-buffer message-reply-buffer)
1238       (message-fetch-field header))))
1239
1240 (defun message-set-work-buffer ()
1241   (if (get-buffer " *message work*")
1242       (progn
1243         (set-buffer " *message work*")
1244         (erase-buffer))
1245     (set-buffer (get-buffer-create " *message work*"))
1246     (kill-all-local-variables)
1247     (mm-enable-multibyte)))
1248
1249 (defun message-functionp (form)
1250   "Return non-nil if FORM is funcallable."
1251   (or (and (symbolp form) (fboundp form))
1252       (and (listp form) (eq (car form) 'lambda))
1253       (byte-code-function-p form)))
1254
1255 (defun message-strip-list-identifiers (subject)
1256   "Remove list identifiers in `gnus-list-identifiers' from string SUBJECT."
1257   (require 'gnus-sum)                   ; for gnus-list-identifiers
1258   (let ((regexp (if (stringp gnus-list-identifiers)
1259                     gnus-list-identifiers
1260                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1261     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp
1262                                 " *\\)\\)+\\(Re: +\\)?\\)") subject)
1263         (concat (substring subject 0 (match-beginning 1))
1264                 (or (match-string 3 subject)
1265                     (match-string 5 subject))
1266                 (substring subject
1267                            (match-end 1)))
1268       subject)))
1269
1270 (defun message-strip-subject-re (subject)
1271   "Remove \"Re:\" from subject lines in string SUBJECT."
1272   (if (string-match message-subject-re-regexp subject)
1273       (substring subject (match-end 0))
1274     subject))
1275
1276 (defun message-remove-header (header &optional is-regexp first reverse)
1277   "Remove HEADER in the narrowed buffer.
1278 If IS-REGEXP, HEADER is a regular expression.
1279 If FIRST, only remove the first instance of the header.
1280 Return the number of headers removed."
1281   (goto-char (point-min))
1282   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1283         (number 0)
1284         (case-fold-search t)
1285         last)
1286     (while (and (not (eobp))
1287                 (not last))
1288       (if (if reverse
1289               (not (looking-at regexp))
1290             (looking-at regexp))
1291           (progn
1292             (incf number)
1293             (when first
1294               (setq last t))
1295             (delete-region
1296              (point)
1297              ;; There might be a continuation header, so we have to search
1298              ;; until we find a new non-continuation line.
1299              (progn
1300                (forward-line 1)
1301                (if (re-search-forward "^[^ \t]" nil t)
1302                    (goto-char (match-beginning 0))
1303                  (point-max)))))
1304         (forward-line 1)
1305         (if (re-search-forward "^[^ \t]" nil t)
1306             (goto-char (match-beginning 0))
1307           (goto-char (point-max)))))
1308     number))
1309
1310 (defun message-remove-first-header (header)
1311   "Remove the first instance of HEADER if there is more than one."
1312   (let ((count 0)
1313         (regexp (concat "^" (regexp-quote header) ":")))
1314     (save-excursion
1315       (goto-char (point-min))
1316       (while (re-search-forward regexp nil t)
1317         (incf count)))
1318     (while (> count 1)
1319       (message-remove-header header nil t)
1320       (decf count))))
1321
1322 (defun message-narrow-to-headers ()
1323   "Narrow the buffer to the head of the message."
1324   (widen)
1325   (narrow-to-region
1326    (goto-char (point-min))
1327    (if (re-search-forward
1328         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1329        (match-beginning 0)
1330      (point-max)))
1331   (goto-char (point-min)))
1332
1333 (defun message-narrow-to-head-1 ()
1334   "Like `message-narrow-to-head'.  Don't widen."
1335   (narrow-to-region
1336    (goto-char (point-min))
1337    (if (search-forward "\n\n" nil 1)
1338        (1- (point))
1339      (point-max)))
1340   (goto-char (point-min)))
1341
1342 (defun message-narrow-to-head ()
1343   "Narrow the buffer to the head of the message.
1344 Point is left at the beginning of the narrowed-to region."
1345   (widen)
1346   (message-narrow-to-head-1))
1347
1348 (defun message-narrow-to-headers-or-head ()
1349   "Narrow the buffer to the head of the message."
1350   (widen)
1351   (narrow-to-region
1352    (goto-char (point-min))
1353    (cond
1354     ((re-search-forward
1355       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1356      (match-beginning 0))
1357     ((search-forward "\n\n" nil t)
1358      (1- (point)))
1359     (t
1360      (point-max))))
1361   (goto-char (point-min)))
1362
1363 (defun message-news-p ()
1364   "Say whether the current buffer contains a news message."
1365   (and (not message-this-is-mail)
1366        (or message-this-is-news
1367            (save-excursion
1368              (save-restriction
1369                (message-narrow-to-headers)
1370                (and (message-fetch-field "newsgroups")
1371                     (not (message-fetch-field "posted-to"))))))))
1372
1373 (defun message-mail-p ()
1374   "Say whether the current buffer contains a mail message."
1375   (and (not message-this-is-news)
1376        (or message-this-is-mail
1377            (save-excursion
1378              (save-restriction
1379                (message-narrow-to-headers)
1380                (or (message-fetch-field "to")
1381                    (message-fetch-field "cc")
1382                    (message-fetch-field "bcc")))))))
1383
1384 (defun message-next-header ()
1385   "Go to the beginning of the next header."
1386   (beginning-of-line)
1387   (or (eobp) (forward-char 1))
1388   (not (if (re-search-forward "^[^ \t]" nil t)
1389            (beginning-of-line)
1390          (goto-char (point-max)))))
1391
1392 (defun message-sort-headers-1 ()
1393   "Sort the buffer as headers using `message-rank' text props."
1394   (goto-char (point-min))
1395   (require 'sort)
1396   (sort-subr
1397    nil 'message-next-header
1398    (lambda ()
1399      (message-next-header)
1400      (unless (bobp)
1401        (forward-char -1)))
1402    (lambda ()
1403      (or (get-text-property (point) 'message-rank)
1404          10000))))
1405
1406 (defun message-sort-headers ()
1407   "Sort the headers of the current message according to `message-header-format-alist'."
1408   (interactive)
1409   (save-excursion
1410     (save-restriction
1411       (let ((max (1+ (length message-header-format-alist)))
1412             rank)
1413         (message-narrow-to-headers)
1414         (while (re-search-forward "^[^ \n]+:" nil t)
1415           (put-text-property
1416            (match-beginning 0) (1+ (match-beginning 0))
1417            'message-rank
1418            (if (setq rank (length (memq (assq (intern (buffer-substring
1419                                                        (match-beginning 0)
1420                                                        (1- (match-end 0))))
1421                                               message-header-format-alist)
1422                                         message-header-format-alist)))
1423                (- max rank)
1424              (1+ max)))))
1425       (message-sort-headers-1))))
1426
1427 \f
1428
1429 ;;;
1430 ;;; Message mode
1431 ;;;
1432
1433 ;;; Set up keymap.
1434
1435 (defvar message-mode-map nil)
1436
1437 (unless message-mode-map
1438   (setq message-mode-map (make-keymap))
1439   (set-keymap-parent message-mode-map text-mode-map)
1440   (define-key message-mode-map "\C-c?" 'describe-mode)
1441
1442   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1443   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1444   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1445   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1446   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1447   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1448   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1449   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1450   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1451   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1452   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1453   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1454   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1455
1456   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1457   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1458
1459   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1460   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1461   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1462   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1463   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1464   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1465   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1466   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1467
1468   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1469   (define-key message-mode-map "\C-c\C-s" 'message-send)
1470   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1471   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1472
1473   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1474   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1475   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1476   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1477   ;;(define-key message-mode-map "\M-q" 'message-fill-paragraph)
1478
1479   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1480
1481   (define-key message-mode-map "\t" 'message-tab)
1482   (define-key message-mode-map "\M-;" 'comment-region))
1483
1484 (easy-menu-define
1485  message-mode-menu message-mode-map "Message Menu."
1486  `("Message"
1487    ["Sort Headers" message-sort-headers t]
1488    ["Yank Original" message-yank-original t]
1489    ["Fill Yanked Message" message-fill-yanked-message t]
1490    ["Insert Signature" message-insert-signature t]
1491    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1492    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1493    ["Elide Region" message-elide-region (mark t)]
1494    ["Delete Outside Region" message-delete-not-region (mark t)]
1495    ["Kill To Signature" message-kill-to-signature t]
1496    ["Newline and Reformat" message-newline-and-reformat t]
1497    ["Rename buffer" message-rename-buffer t]
1498    ["Spellcheck" ispell-message
1499     ,@(if (featurep 'xemacs) '(t)
1500         '(:help "Spellcheck this message"))]
1501    ["Attach file as MIME" mml-attach-file
1502     ,@(if (featurep 'xemacs) '(t)
1503         '(:help "Attach a file at point"))]
1504    "----"
1505    ["Send Message" message-send-and-exit
1506     ,@(if (featurep 'xemacs) '(t)
1507         '(:help "Send this message"))]
1508    ["Abort Message" message-dont-send
1509     ,@(if (featurep 'xemacs) '(t)
1510         '(:help "File this draft message and exit"))]
1511    ["Kill Message" message-kill-buffer
1512     ,@(if (featurep 'xemacs) '(t)
1513         '(:help "Delete this message without sending"))]))
1514
1515 (easy-menu-define
1516  message-mode-field-menu message-mode-map ""
1517  '("Field"
1518    ["Fetch To" message-insert-to t]
1519    ["Fetch Newsgroups" message-insert-newsgroups t]
1520    "----"
1521    ["To" message-goto-to t]
1522    ["Subject" message-goto-subject t]
1523    ["Cc" message-goto-cc t]
1524    ["Reply-To" message-goto-reply-to t]
1525    ["Summary" message-goto-summary t]
1526    ["Keywords" message-goto-keywords t]
1527    ["Newsgroups" message-goto-newsgroups t]
1528    ["Followup-To" message-goto-followup-to t]
1529    ["Distribution" message-goto-distribution t]
1530    ["Body" message-goto-body t]
1531    ["Signature" message-goto-signature t]))
1532
1533 (defvar message-tool-bar-map nil)
1534
1535 (eval-when-compile
1536   (defvar facemenu-add-face-function)
1537   (defvar facemenu-remove-face-function))
1538
1539 ;;;###autoload
1540 (defun message-mode ()
1541   "Major mode for editing mail and news to be sent.
1542 Like Text Mode but with these additional commands:\\<message-mode-map>
1543 C-c C-s  `message-send' (send the message)  C-c C-c  `message-send-and-exit'
1544 C-c C-d  Postpone sending the message       C-c C-k  Kill the message
1545 C-c C-f  move to a header field (and create it if there isn't):
1546          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1547          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1548          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1549          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1550          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1551          C-c C-f C-f  move to Followup-To
1552 C-c C-t  `message-insert-to' (add a To header to a news followup)
1553 C-c C-n  `message-insert-newsgroups' (add a Newsgroup header to a news reply)
1554 C-c C-b  `message-goto-body' (move to beginning of message text).
1555 C-c C-i  `message-goto-signature' (move to the beginning of the signature).
1556 C-c C-w  `message-insert-signature' (insert `message-signature-file' file).
1557 C-c C-y  `message-yank-original' (insert current message, if any).
1558 C-c C-q  `message-fill-yanked-message' (fill what was yanked).
1559 C-c C-e  `message-elide-region' (elide the text between point and mark).
1560 C-c C-v  `message-delete-not-region' (remove the text outside the region).
1561 C-c C-z  `message-kill-to-signature' (kill the text up to the signature).
1562 C-c C-r  `message-caesar-buffer-body' (rot13 the message body).
1563 C-c C-a  `mml-attach-file' (attach a file as MIME).
1564 M-RET    `message-newline-and-reformat' (break the line and reformat)."
1565   (interactive)
1566   (if (local-variable-p 'mml-buffer-list (current-buffer))
1567       (mml-destroy-buffers))
1568   (kill-all-local-variables)
1569   (set (make-local-variable 'message-reply-buffer) nil)
1570   (make-local-variable 'message-send-actions)
1571   (make-local-variable 'message-exit-actions)
1572   (make-local-variable 'message-kill-actions)
1573   (make-local-variable 'message-postpone-actions)
1574   (make-local-variable 'message-draft-article)
1575   (make-local-hook 'kill-buffer-hook)
1576   (set-syntax-table message-mode-syntax-table)
1577   (use-local-map message-mode-map)
1578   (setq local-abbrev-table message-mode-abbrev-table)
1579   (setq major-mode 'message-mode)
1580   (setq mode-name "Message")
1581   (setq buffer-offer-save t)
1582   (make-local-variable 'facemenu-add-face-function)
1583   (make-local-variable 'facemenu-remove-face-function)
1584   (setq facemenu-add-face-function
1585         (lambda (face end)
1586           (let ((face-fun (cdr (assq face message-face-alist))))
1587             (if face-fun
1588                 (funcall face-fun (point) end)
1589               (error "Face %s not configured for %s mode" face mode-name)))
1590           "")
1591         facemenu-remove-face-function t)
1592   (make-local-variable 'message-reply-headers)
1593   (setq message-reply-headers nil)
1594   (make-local-variable 'message-newsreader)
1595   (make-local-variable 'message-mailer)
1596   (make-local-variable 'message-post-method)
1597   (set (make-local-variable 'message-sent-message-via) nil)
1598   (set (make-local-variable 'message-checksum) nil)
1599   (set (make-local-variable 'message-mime-part) 0)
1600   (message-setup-fill-variables)
1601   ;; Allow using comment commands to add/remove quoting.
1602   (set (make-local-variable 'comment-start) message-yank-prefix)
1603   (if (featurep 'xemacs)
1604       (message-setup-toolbar)
1605     (set (make-local-variable 'font-lock-defaults)
1606          '(message-font-lock-keywords t))
1607     (if (boundp 'tool-bar-map)
1608         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1609   (easy-menu-add message-mode-menu message-mode-map)
1610   (easy-menu-add message-mode-field-menu message-mode-map)
1611   ;; Allow mail alias things.
1612   (when (eq message-mail-alias-type 'abbrev)
1613     (if (fboundp 'mail-abbrevs-setup)
1614         (mail-abbrevs-setup)
1615       (mail-aliases-setup)))
1616   (message-set-auto-save-file-name)
1617   (mm-enable-multibyte)
1618   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1619   (setq indent-tabs-mode nil)
1620   (mml-mode)
1621   (run-hooks 'text-mode-hook 'message-mode-hook))
1622
1623 (defun message-setup-fill-variables ()
1624   "Setup message fill variables."
1625   (set (make-local-variable 'fill-paragraph-function)
1626        'message-fill-paragraph)
1627   (make-local-variable 'paragraph-separate)
1628   (make-local-variable 'paragraph-start)
1629   (make-local-variable 'adaptive-fill-regexp)
1630   (unless (boundp 'adaptive-fill-first-line-regexp)
1631     (setq adaptive-fill-first-line-regexp nil))
1632   (make-local-variable 'adaptive-fill-first-line-regexp)
1633   (make-local-variable 'auto-fill-inhibit-regexp)
1634   (let ((quote-prefix-regexp
1635          ;; User should change message-cite-prefix-regexp if
1636          ;; message-yank-prefix is set to an abnormal value.
1637          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))
1638     (setq paragraph-start
1639           (concat
1640            (regexp-quote mail-header-separator) "$\\|"
1641            "[ \t]*$\\|"                 ; blank lines
1642            "-- $\\|"                    ; signature delimiter
1643            "---+$\\|"                   ; delimiters for forwarded messages
1644            page-delimiter "$\\|"        ; spoiler warnings
1645            ".*wrote:$\\|"               ; attribution lines
1646            quote-prefix-regexp "$"))    ; empty lines in quoted text
1647     (setq paragraph-separate paragraph-start)
1648     (setq adaptive-fill-regexp
1649           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1650     (setq adaptive-fill-first-line-regexp
1651           (concat quote-prefix-regexp "\\|"
1652                   adaptive-fill-first-line-regexp))
1653     (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")))
1654
1655 \f
1656
1657 ;;;
1658 ;;; Message mode commands
1659 ;;;
1660
1661 ;;; Movement commands
1662
1663 (defun message-goto-to ()
1664   "Move point to the To header."
1665   (interactive)
1666   (message-position-on-field "To"))
1667
1668 (defun message-goto-subject ()
1669   "Move point to the Subject header."
1670   (interactive)
1671   (message-position-on-field "Subject"))
1672
1673 (defun message-goto-cc ()
1674   "Move point to the Cc header."
1675   (interactive)
1676   (message-position-on-field "Cc" "To"))
1677
1678 (defun message-goto-bcc ()
1679   "Move point to the Bcc  header."
1680   (interactive)
1681   (message-position-on-field "Bcc" "Cc" "To"))
1682
1683 (defun message-goto-fcc ()
1684   "Move point to the Fcc header."
1685   (interactive)
1686   (message-position-on-field "Fcc" "To" "Newsgroups"))
1687
1688 (defun message-goto-reply-to ()
1689   "Move point to the Reply-To header."
1690   (interactive)
1691   (message-position-on-field "Reply-To" "Subject"))
1692
1693 (defun message-goto-newsgroups ()
1694   "Move point to the Newsgroups header."
1695   (interactive)
1696   (message-position-on-field "Newsgroups"))
1697
1698 (defun message-goto-distribution ()
1699   "Move point to the Distribution header."
1700   (interactive)
1701   (message-position-on-field "Distribution"))
1702
1703 (defun message-goto-followup-to ()
1704   "Move point to the Followup-To header."
1705   (interactive)
1706   (message-position-on-field "Followup-To" "Newsgroups"))
1707
1708 (defun message-goto-keywords ()
1709   "Move point to the Keywords header."
1710   (interactive)
1711   (message-position-on-field "Keywords" "Subject"))
1712
1713 (defun message-goto-summary ()
1714   "Move point to the Summary header."
1715   (interactive)
1716   (message-position-on-field "Summary" "Subject"))
1717
1718 (defun message-goto-body (&optional interactivep)
1719   "Move point to the beginning of the message body."
1720   (interactive (list t))
1721   (when (and interactivep
1722              (looking-at "[ \t]*\n"))
1723     (expand-abbrev))
1724   (goto-char (point-min))
1725   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1726       (search-forward-regexp "[^:]+:\\([^\n]\\|\n[ \t]\\)+\n\n" nil t)
1727       (point-min)))
1728
1729 (defun message-goto-eoh ()
1730   "Move point to the end of the headers."
1731   (interactive)
1732   (message-goto-body)
1733   (forward-line -1))
1734
1735 (defun message-goto-signature ()
1736   "Move point to the beginning of the message signature.
1737 If there is no signature in the article, go to the end and
1738 return nil."
1739   (interactive)
1740   (goto-char (point-min))
1741   (if (re-search-forward message-signature-separator nil t)
1742       (forward-line 1)
1743     (goto-char (point-max))
1744     nil))
1745
1746 \f
1747
1748 (defun message-insert-to (&optional force)
1749   "Insert a To header that points to the author of the article being replied to.
1750 If the original author requested not to be sent mail, the function signals
1751 an error.
1752 With the prefix argument FORCE, insert the header anyway."
1753   (interactive "P")
1754   (let ((co (message-fetch-reply-field "mail-copies-to")))
1755     (when (and (null force)
1756                co
1757                (or (equal (downcase co) "never")
1758                    (equal (downcase co) "nobody")))
1759       (error "The user has requested not to have copies sent via mail")))
1760   (when (and (message-position-on-field "To")
1761              (mail-fetch-field "to")
1762              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1763     (insert ", "))
1764   (insert (or (message-fetch-reply-field "mail-reply-to")
1765               (message-fetch-reply-field "reply-to")
1766               (message-fetch-reply-field "from") "")))
1767
1768 (defun message-widen-reply ()
1769   "Widen the reply to include maximum recipients."
1770   (interactive)
1771   (let ((follow-to
1772          (and message-reply-buffer
1773               (buffer-name message-reply-buffer)
1774               (save-excursion
1775                 (set-buffer message-reply-buffer)
1776                 (message-get-reply-headers t)))))
1777     (save-excursion
1778       (save-restriction
1779         (message-narrow-to-headers)
1780         (dolist (elem follow-to)
1781           (message-remove-header (symbol-name (car elem)))
1782           (goto-char (point-min))
1783           (insert (symbol-name (car elem)) ": "
1784                   (cdr elem) "\n"))))))
1785
1786 (defun message-insert-newsgroups ()
1787   "Insert the Newsgroups header from the article being replied to."
1788   (interactive)
1789   (when (and (message-position-on-field "Newsgroups")
1790              (mail-fetch-field "newsgroups")
1791              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1792     (insert ","))
1793   (insert (or (message-fetch-reply-field "newsgroups") "")))
1794
1795 \f
1796
1797 ;;; Various commands
1798
1799 (defun message-delete-not-region (beg end)
1800   "Delete everything in the body of the current message outside of the region."
1801   (interactive "r")
1802   (let (citeprefix)
1803     (save-excursion
1804       (goto-char beg)
1805       ;; snarf citation prefix, if appropriate
1806       (unless (eq (point) (progn (beginning-of-line) (point)))
1807         (when (looking-at message-cite-prefix-regexp)
1808           (setq citeprefix (match-string 0))))
1809       (goto-char end)
1810       (delete-region (point) (if (not (message-goto-signature))
1811                                  (point)
1812                                (forward-line -2)
1813                                (point)))
1814       (insert "\n")
1815       (goto-char beg)
1816       (delete-region beg (progn (message-goto-body)
1817                                 (forward-line 2)
1818                                 (point)))
1819       (when citeprefix
1820         (insert citeprefix))))
1821   (when (message-goto-signature)
1822     (forward-line -2)))
1823
1824 (defun message-kill-to-signature ()
1825   "Deletes all text up to the signature."
1826   (interactive)
1827   (let ((point (point)))
1828     (message-goto-signature)
1829     (unless (eobp)
1830       (forward-line -2))
1831     (kill-region point (point))
1832     (unless (bolp)
1833       (insert "\n"))))
1834
1835 (defun message-newline-and-reformat (&optional arg not-break)
1836   "Insert four newlines, and then reformat if inside quoted text.
1837 Prefix arg means justify as well."
1838   (interactive (list (if current-prefix-arg 'full)))
1839   (let (quoted point beg end leading-space bolp)
1840     (setq point (point))
1841     (beginning-of-line)
1842     (setq beg (point))
1843     (setq bolp (= beg point))
1844     ;; Find first line of the paragraph.
1845     (if not-break
1846         (while (and (not (eobp))
1847                     (not (looking-at message-cite-prefix-regexp))
1848                 (looking-at paragraph-start))
1849           (forward-line 1)))
1850     ;; Find the prefix
1851     (when (looking-at message-cite-prefix-regexp)
1852       (setq quoted (match-string 0))
1853       (goto-char (match-end 0))
1854       (looking-at "[ \t]*")
1855       (setq leading-space (match-string 0)))
1856     (if (and quoted
1857              (not not-break)
1858              (not bolp)
1859              (< (- point beg) (length quoted)))
1860         ;; break inside the cite prefix.
1861         (setq quoted nil
1862               end nil))
1863     (if quoted
1864         (progn
1865           (forward-line 1)
1866           (while (and (not (eobp))
1867                       (not (looking-at paragraph-separate))
1868                       (looking-at message-cite-prefix-regexp)
1869                       (equal quoted (match-string 0)))
1870             (goto-char (match-end 0))
1871             (looking-at "[ \t]*")
1872             (if (> (length leading-space) (length (match-string 0)))
1873                 (setq leading-space (match-string 0)))
1874             (forward-line 1))
1875           (setq end (point))
1876           (goto-char beg)
1877           (while (and (if (bobp) nil (forward-line -1) t)
1878                       (not (looking-at paragraph-start))
1879                       (looking-at message-cite-prefix-regexp)
1880                       (equal quoted (match-string 0)))
1881             (setq beg (point))
1882             (goto-char (match-end 0))
1883             (looking-at "[ \t]*")
1884             (if (> (length leading-space) (length (match-string 0)))
1885                 (setq leading-space (match-string 0)))))
1886       (while (and (not (eobp))
1887                   (not (looking-at paragraph-separate))
1888                   (not (looking-at message-cite-prefix-regexp)))
1889         (forward-line 1))
1890       (setq end (point))
1891       (goto-char beg)
1892       (while (and (if (bobp) nil (forward-line -1) t)
1893                   (not (looking-at paragraph-start))
1894                   (not (looking-at message-cite-prefix-regexp)))
1895         (setq beg (point))))
1896     (goto-char point)
1897     (save-restriction
1898       (narrow-to-region beg end)
1899       (if not-break
1900           (setq point nil)
1901         (if bolp
1902             (insert "\n")
1903           (insert "\n\n"))
1904         (setq point (point))
1905         (insert "\n\n")
1906         (delete-region (point) (re-search-forward "[ \t]*"))
1907         (when (and quoted (not bolp))
1908           (insert quoted leading-space)))
1909       (if quoted
1910           (let* ((adaptive-fill-regexp
1911                  (regexp-quote (concat quoted leading-space)))
1912                  (adaptive-fill-first-line-regexp
1913                   adaptive-fill-regexp ))
1914             (fill-paragraph arg))
1915         (fill-paragraph arg))
1916       (if point (goto-char point)))))
1917
1918 (defun message-fill-paragraph (&optional arg)
1919   "Like `fill-paragraph'."
1920   (interactive (list (if current-prefix-arg 'full)))
1921   (message-newline-and-reformat arg t)
1922   t)
1923
1924 (defun message-insert-signature (&optional force)
1925   "Insert a signature.  See documentation for variable `message-signature'."
1926   (interactive (list 0))
1927   (let* ((signature
1928           (cond
1929            ((and (null message-signature)
1930                  (eq force 0))
1931             (save-excursion
1932               (goto-char (point-max))
1933               (not (re-search-backward message-signature-separator nil t))))
1934            ((and (null message-signature)
1935                  force)
1936             t)
1937            ((message-functionp message-signature)
1938             (funcall message-signature))
1939            ((listp message-signature)
1940             (eval message-signature))
1941            (t message-signature)))
1942          (signature
1943           (cond ((stringp signature)
1944                  signature)
1945                 ((and (eq t signature)
1946                       message-signature-file
1947                       (file-exists-p message-signature-file))
1948                  signature))))
1949     (when signature
1950       (goto-char (point-max))
1951       ;; Insert the signature.
1952       (unless (bolp)
1953         (insert "\n"))
1954       (insert "\n-- \n")
1955       (if (eq signature t)
1956           (insert-file-contents message-signature-file)
1957         (insert signature))
1958       (goto-char (point-max))
1959       (or (bolp) (insert "\n")))))
1960
1961 (defun message-elide-region (b e)
1962   "Elide the text in the region.
1963 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1964 text was killed."
1965   (interactive "r")
1966   (kill-region b e)
1967   (insert message-elide-ellipsis))
1968
1969 (defvar message-caesar-translation-table nil)
1970
1971 (defun message-caesar-region (b e &optional n)
1972   "Caesar rotate region B to E by N, default 13, for decrypting netnews."
1973   (interactive
1974    (list
1975     (min (point) (or (mark t) (point)))
1976     (max (point) (or (mark t) (point)))
1977     (when current-prefix-arg
1978       (prefix-numeric-value current-prefix-arg))))
1979
1980   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1981   (unless (or (zerop n)                 ; no action needed for a rot of 0
1982               (= b e))                  ; no region to rotate
1983     ;; We build the table, if necessary.
1984     (when (or (not message-caesar-translation-table)
1985               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1986       (setq message-caesar-translation-table
1987             (message-make-caesar-translation-table n)))
1988     (translate-region b e message-caesar-translation-table)))
1989
1990 (defun message-make-caesar-translation-table (n)
1991   "Create a rot table with offset N."
1992   (let ((i -1)
1993         (table (make-string 256 0)))
1994     (while (< (incf i) 256)
1995       (aset table i i))
1996     (concat
1997      (substring table 0 ?A)
1998      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1999      (substring table ?A (+ ?A n))
2000      (substring table (+ ?A 26) ?a)
2001      (substring table (+ ?a n) (+ ?a n (- 26 n)))
2002      (substring table ?a (+ ?a n))
2003      (substring table (+ ?a 26) 255))))
2004
2005 (defun message-caesar-buffer-body (&optional rotnum)
2006   "Caesar rotate all letters in the current buffer by 13 places.
2007 Used to encode/decode possibly offensive messages (commonly in rec.humor).
2008 With prefix arg, specifies the number of places to rotate each letter forward.
2009 Mail and USENET news headers are not rotated."
2010   (interactive (if current-prefix-arg
2011                    (list (prefix-numeric-value current-prefix-arg))
2012                  (list nil)))
2013   (save-excursion
2014     (save-restriction
2015       (when (message-goto-body)
2016         (narrow-to-region (point) (point-max)))
2017       (message-caesar-region (point-min) (point-max) rotnum))))
2018
2019 (defun message-pipe-buffer-body (program)
2020   "Pipe the message body in the current buffer through PROGRAM."
2021   (save-excursion
2022     (save-restriction
2023       (when (message-goto-body)
2024         (narrow-to-region (point) (point-max)))
2025       (shell-command-on-region
2026        (point-min) (point-max) program nil t))))
2027
2028 (defun message-rename-buffer (&optional enter-string)
2029   "Rename the *message* buffer to \"*message* RECIPIENT\".
2030 If the function is run with a prefix, it will ask for a new buffer
2031 name, rather than giving an automatic name."
2032   (interactive "Pbuffer name: ")
2033   (save-excursion
2034     (save-restriction
2035       (goto-char (point-min))
2036       (narrow-to-region (point)
2037                         (search-forward mail-header-separator nil 'end))
2038       (let* ((mail-to (or
2039                        (if (message-news-p) (message-fetch-field "Newsgroups")
2040                          (message-fetch-field "To"))
2041                        ""))
2042              (mail-trimmed-to
2043               (if (string-match "," mail-to)
2044                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
2045                 mail-to))
2046              (name-default (concat "*message* " mail-trimmed-to))
2047              (name (if enter-string
2048                        (read-string "New buffer name: " name-default)
2049                      name-default)))
2050         (rename-buffer name t)))))
2051
2052 (defun message-fill-yanked-message (&optional justifyp)
2053   "Fill the paragraphs of a message yanked into this one.
2054 Numeric argument means justify as well."
2055   (interactive "P")
2056   (save-excursion
2057     (goto-char (point-min))
2058     (search-forward (concat "\n" mail-header-separator "\n") nil t)
2059     (let ((fill-prefix message-yank-prefix))
2060       (fill-individual-paragraphs (point) (point-max) justifyp))))
2061
2062 (defun message-indent-citation ()
2063   "Modify text just inserted from a message to be cited.
2064 The inserted text should be the region.
2065 When this function returns, the region is again around the modified text.
2066
2067 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2068 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2069   (let ((start (point)))
2070     ;; Remove unwanted headers.
2071     (when message-ignored-cited-headers
2072       (let (all-removed)
2073         (save-restriction
2074           (narrow-to-region
2075            (goto-char start)
2076            (if (search-forward "\n\n" nil t)
2077                (1- (point))
2078              (point)))
2079           (message-remove-header message-ignored-cited-headers t)
2080           (when (= (point-min) (point-max))
2081             (setq all-removed t))
2082           (goto-char (point-max)))
2083         (if all-removed
2084             (goto-char start)
2085           (forward-line 1))))
2086     ;; Delete blank lines at the start of the buffer.
2087     (while (and (point-min)
2088                 (eolp)
2089                 (not (eobp)))
2090       (message-delete-line))
2091     ;; Delete blank lines at the end of the buffer.
2092     (goto-char (point-max))
2093     (unless (eolp)
2094       (insert "\n"))
2095     (while (and (zerop (forward-line -1))
2096                 (looking-at "$"))
2097       (message-delete-line))
2098     ;; Do the indentation.
2099     (if (null message-yank-prefix)
2100         (indent-rigidly start (mark t) message-indentation-spaces)
2101       (save-excursion
2102         (goto-char start)
2103         (while (< (point) (mark t))
2104           (if (looking-at message-cite-prefix-regexp)
2105               (insert message-yank-cited-prefix)
2106             (insert message-yank-prefix))
2107           (forward-line 1))))
2108     (goto-char start)))
2109
2110 (defun message-yank-original (&optional arg)
2111   "Insert the message being replied to, if any.
2112 Puts point before the text and mark after.
2113 Normally indents each nonblank line ARG spaces (default 3).  However,
2114 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2115
2116 This function uses `message-cite-function' to do the actual citing.
2117
2118 Just \\[universal-argument] as argument means don't indent, insert no
2119 prefix, and don't delete any headers."
2120   (interactive "P")
2121   (let ((modified (buffer-modified-p)))
2122     (when (and message-reply-buffer
2123                message-cite-function)
2124       (delete-windows-on message-reply-buffer t)
2125       (insert-buffer message-reply-buffer)
2126       (unless arg
2127         (funcall message-cite-function))
2128       (message-exchange-point-and-mark)
2129       (unless (bolp)
2130         (insert ?\n))
2131       (unless modified
2132         (setq message-checksum (message-checksum))))))
2133
2134 (defun message-yank-buffer (buffer)
2135   "Insert BUFFER into the current buffer and quote it."
2136   (interactive "bYank buffer: ")
2137   (let ((message-reply-buffer buffer))
2138     (save-window-excursion
2139       (message-yank-original))))
2140
2141 (defun message-buffers ()
2142   "Return a list of active message buffers."
2143   (let (buffers)
2144     (save-excursion
2145       (dolist (buffer (buffer-list t))
2146         (set-buffer buffer)
2147         (when (and (eq major-mode 'message-mode)
2148                    (null message-sent-message-via))
2149           (push (buffer-name buffer) buffers))))
2150     (nreverse buffers)))
2151
2152 (defun message-cite-original-without-signature ()
2153   "Cite function in the standard Message manner."
2154   (let ((start (point))
2155         (end (mark t))
2156         (functions
2157          (when message-indent-citation-function
2158            (if (listp message-indent-citation-function)
2159                message-indent-citation-function
2160              (list message-indent-citation-function)))))
2161     (mml-quote-region start end)
2162     ;; Allow undoing.
2163     (undo-boundary)
2164     (goto-char end)
2165     (when (re-search-backward message-signature-separator start t)
2166       ;; Also peel off any blank lines before the signature.
2167       (forward-line -1)
2168       (while (looking-at "^[ \t]*$")
2169         (forward-line -1))
2170       (forward-line 1)
2171       (delete-region (point) end)
2172       (unless (search-backward "\n\n" start t)
2173         ;; Insert a blank line if it is peeled off.
2174         (insert "\n")))
2175     (goto-char start)
2176     (while functions
2177       (funcall (pop functions)))
2178     (when message-citation-line-function
2179       (unless (bolp)
2180         (insert "\n"))
2181       (funcall message-citation-line-function))))
2182
2183 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2184 (defun message-cite-original ()
2185   "Cite function in the standard Message manner."
2186   (if (and (boundp 'mail-citation-hook)
2187            mail-citation-hook)
2188       (run-hooks 'mail-citation-hook)
2189     (let ((start (point))
2190           (end (mark t))
2191           (functions
2192            (when message-indent-citation-function
2193              (if (listp message-indent-citation-function)
2194                  message-indent-citation-function
2195                (list message-indent-citation-function)))))
2196       (mml-quote-region start end)
2197       (goto-char start)
2198       (while functions
2199         (funcall (pop functions)))
2200       (when message-citation-line-function
2201         (unless (bolp)
2202           (insert "\n"))
2203         (funcall message-citation-line-function)))))
2204
2205 (defun message-insert-citation-line ()
2206   "Insert a simple citation line."
2207   (when message-reply-headers
2208     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2209
2210 (defun message-position-on-field (header &rest afters)
2211   (let ((case-fold-search t))
2212     (save-restriction
2213       (narrow-to-region
2214        (goto-char (point-min))
2215        (progn
2216          (re-search-forward
2217           (concat "^" (regexp-quote mail-header-separator) "$"))
2218          (match-beginning 0)))
2219       (goto-char (point-min))
2220       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2221           (progn
2222             (re-search-forward "^[^ \t]" nil 'move)
2223             (beginning-of-line)
2224             (skip-chars-backward "\n")
2225             t)
2226         (while (and afters
2227                     (not (re-search-forward
2228                           (concat "^" (regexp-quote (car afters)) ":")
2229                           nil t)))
2230           (pop afters))
2231         (when afters
2232           (re-search-forward "^[^ \t]" nil 'move)
2233           (beginning-of-line))
2234         (insert header ": \n")
2235         (forward-char -1)
2236         nil))))
2237
2238 (defun message-remove-signature ()
2239   "Remove the signature from the text between point and mark.
2240 The text will also be indented the normal way."
2241   (save-excursion
2242     (let ((start (point))
2243           mark)
2244       (if (not (re-search-forward message-signature-separator (mark t) t))
2245           ;; No signature here, so we just indent the cited text.
2246           (message-indent-citation)
2247         ;; Find the last non-empty line.
2248         (forward-line -1)
2249         (while (looking-at "[ \t]*$")
2250           (forward-line -1))
2251         (forward-line 1)
2252         (setq mark (set-marker (make-marker) (point)))
2253         (goto-char start)
2254         (message-indent-citation)
2255         ;; Enable undoing the deletion.
2256         (undo-boundary)
2257         (delete-region mark (mark t))
2258         (set-marker mark nil)))))
2259
2260 \f
2261
2262 ;;;
2263 ;;; Sending messages
2264 ;;;
2265
2266 (defun message-send-and-exit (&optional arg)
2267   "Send message like `message-send', then, if no errors, exit from mail buffer."
2268   (interactive "P")
2269   (let ((buf (current-buffer))
2270         (actions message-exit-actions))
2271     (when (and (message-send arg)
2272                (buffer-name buf))
2273       (if message-kill-buffer-on-exit
2274           (kill-buffer buf)
2275         (bury-buffer buf)
2276         (when (eq buf (current-buffer))
2277           (message-bury buf)))
2278       (message-do-actions actions)
2279       t)))
2280
2281 (defun message-dont-send ()
2282   "Don't send the message you have been editing."
2283   (interactive)
2284   (set-buffer-modified-p t)
2285   (save-buffer)
2286   (let ((actions message-postpone-actions))
2287     (message-bury (current-buffer))
2288     (message-do-actions actions)))
2289
2290 (defun message-kill-buffer ()
2291   "Kill the current buffer."
2292   (interactive)
2293   (when (or (not (buffer-modified-p))
2294             (yes-or-no-p "Message modified; kill anyway? "))
2295     (let ((actions message-kill-actions))
2296       (setq buffer-file-name nil)
2297       (kill-buffer (current-buffer))
2298       (message-do-actions actions))))
2299
2300 (defun message-bury (buffer)
2301   "Bury this mail BUFFER."
2302   (let ((newbuf (other-buffer buffer)))
2303     (bury-buffer buffer)
2304     (if (and (fboundp 'frame-parameters)
2305              (cdr (assq 'dedicated (frame-parameters)))
2306              (not (null (delq (selected-frame) (visible-frame-list)))))
2307         (delete-frame (selected-frame))
2308       (switch-to-buffer newbuf))))
2309
2310 (defun message-send (&optional arg)
2311   "Send the message in the current buffer.
2312 If `message-interactive' is non-nil, wait for success indication or
2313 error messages, and inform user.
2314 Otherwise any failure is reported in a message back to the user from
2315 the mailer.
2316 The usage of ARG is defined by the instance that called Message.
2317 It should typically alter the sending method in some way or other."
2318   (interactive "P")
2319   ;; Make it possible to undo the coming changes.
2320   (undo-boundary)
2321   (let ((inhibit-read-only t))
2322     (put-text-property (point-min) (point-max) 'read-only nil))
2323   (message-fix-before-sending)
2324   (run-hooks 'message-send-hook)
2325   (message message-sending-message)
2326   (let ((alist message-send-method-alist)
2327         (success t)
2328         elem sent
2329         (message-options message-options))
2330     (message-options-set-recipient)
2331     (while (and success
2332                 (setq elem (pop alist)))
2333       (when (funcall (cadr elem))
2334         (when (and (or (not (memq (car elem)
2335                                   message-sent-message-via))
2336                        (if (or (message-gnksa-enable-p 'multiple-copies)
2337                                (not (eq (car elem) 'news)))
2338                            (y-or-n-p
2339                             (format
2340                              "Already sent message via %s; resend? "
2341                              (car elem)))
2342                          (error "Denied posting -- multiple copies.")))
2343                    (setq success (funcall (caddr elem) arg)))
2344           (setq sent t))))
2345     (unless (or sent (not success))
2346       (error "No methods specified to send by"))
2347     (when (and success sent)
2348       (message-do-fcc)
2349       (save-excursion
2350         (run-hooks 'message-sent-hook))
2351       (message "Sending...done")
2352       ;; Mark the buffer as unmodified and delete auto-save.
2353       (set-buffer-modified-p nil)
2354       (delete-auto-save-file-if-necessary t)
2355       (message-disassociate-draft)
2356       ;; Delete other mail buffers and stuff.
2357       (message-do-send-housekeeping)
2358       (message-do-actions message-send-actions)
2359       ;; Return success.
2360       t)))
2361
2362 (defun message-send-via-mail (arg)
2363   "Send the current message via mail."
2364   (message-send-mail arg))
2365
2366 (defun message-send-via-news (arg)
2367   "Send the current message via news."
2368   (funcall message-send-news-function arg))
2369
2370 (defmacro message-check (type &rest forms)
2371   "Eval FORMS if TYPE is to be checked."
2372   `(or (message-check-element ,type)
2373        (save-excursion
2374          ,@forms)))
2375
2376 (put 'message-check 'lisp-indent-function 1)
2377 (put 'message-check 'edebug-form-spec '(form body))
2378
2379 (defun message-fix-before-sending ()
2380   "Do various things to make the message nice before sending it."
2381   ;; Make sure there's a newline at the end of the message.
2382   (goto-char (point-max))
2383   (unless (bolp)
2384     (insert "\n"))
2385   ;; Delete all invisible text.
2386   (message-check 'invisible-text
2387     (when (text-property-any (point-min) (point-max) 'invisible t)
2388       (put-text-property (point-min) (point-max) 'invisible nil)
2389       (unless (yes-or-no-p
2390                "Invisible text found and made visible; continue posting? ")
2391         (error "Invisible text found and made visible")))))
2392
2393 (defun message-add-action (action &rest types)
2394   "Add ACTION to be performed when doing an exit of type TYPES."
2395   (let (var)
2396     (while types
2397       (set (setq var (intern (format "message-%s-actions" (pop types))))
2398            (nconc (symbol-value var) (list action))))))
2399
2400 (defun message-do-actions (actions)
2401   "Perform all actions in ACTIONS."
2402   ;; Now perform actions on successful sending.
2403   (while actions
2404     (ignore-errors
2405       (cond
2406        ;; A simple function.
2407        ((message-functionp (car actions))
2408         (funcall (car actions)))
2409        ;; Something to be evaled.
2410        (t
2411         (eval (car actions)))))
2412     (pop actions)))
2413
2414 (defun message-send-mail-partially ()
2415   "Send mail as message/partial."
2416   ;; replace the header delimiter with a blank line
2417   (goto-char (point-min))
2418   (re-search-forward
2419    (concat "^" (regexp-quote mail-header-separator) "\n"))
2420   (replace-match "\n")
2421   (run-hooks 'message-send-mail-hook)
2422   (let ((p (goto-char (point-min)))
2423         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2424         (curbuf (current-buffer))
2425         (id (message-make-message-id)) (n 1)
2426         plist total  header required-mail-headers)
2427     (while (not (eobp))
2428       (if (< (point-max) (+ p message-send-mail-partially-limit))
2429           (goto-char (point-max))
2430         (goto-char (+ p message-send-mail-partially-limit))
2431         (beginning-of-line)
2432         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2433       (push p plist)
2434       (setq p (point)))
2435     (setq total (length plist))
2436     (push (point-max) plist)
2437     (setq plist (nreverse plist))
2438     (unwind-protect
2439         (save-excursion
2440           (setq p (pop plist))
2441           (while plist
2442             (set-buffer curbuf)
2443             (copy-to-buffer tembuf p (car plist))
2444             (set-buffer tembuf)
2445             (goto-char (point-min))
2446             (if header
2447                 (progn
2448                   (goto-char (point-min))
2449                   (narrow-to-region (point) (point))
2450                   (insert header))
2451               (message-goto-eoh)
2452               (setq header (buffer-substring (point-min) (point)))
2453               (goto-char (point-min))
2454               (narrow-to-region (point) (point))
2455               (insert header)
2456               (message-remove-header "Mime-Version")
2457               (message-remove-header "Content-Type")
2458               (message-remove-header "Content-Transfer-Encoding")
2459               (message-remove-header "Message-ID")
2460               (message-remove-header "Lines")
2461               (goto-char (point-max))
2462               (insert "Mime-Version: 1.0\n")
2463               (setq header (buffer-substring (point-min) (point-max))))
2464             (goto-char (point-max))
2465             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2466                             id n total))
2467             (let ((mail-header-separator ""))
2468               (when (memq 'Message-ID message-required-mail-headers)
2469                 (insert "Message-ID: " (message-make-message-id) "\n"))
2470               (when (memq 'Lines message-required-mail-headers)
2471                 (let ((mail-header-separator ""))
2472                   (insert "Lines: " (message-make-lines) "\n")))
2473               (message-goto-subject)
2474               (end-of-line)
2475               (insert (format " (%d/%d)" n total))
2476               (goto-char (point-max))
2477               (insert "\n")
2478               (widen)
2479               (mm-with-unibyte-current-buffer
2480                 (funcall message-send-mail-function)))
2481             (setq n (+ n 1))
2482             (setq p (pop plist))
2483             (erase-buffer)))
2484       (kill-buffer tembuf))))
2485
2486 (defun message-send-mail (&optional arg)
2487   (require 'mail-utils)
2488   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2489          (case-fold-search nil)
2490          (news (message-news-p))
2491          (mailbuf (current-buffer))
2492          (message-this-is-mail t)
2493          (message-posting-charset
2494           (if (fboundp 'gnus-setup-posting-charset)
2495               (gnus-setup-posting-charset nil)
2496             message-posting-charset)))
2497     (save-restriction
2498       (message-narrow-to-headers)
2499       ;; Insert some headers.
2500       (let ((message-deletable-headers
2501              (if news nil message-deletable-headers)))
2502         (message-generate-headers message-required-mail-headers))
2503       ;; Let the user do all of the above.
2504       (run-hooks 'message-header-hook))
2505     (unwind-protect
2506         (save-excursion
2507           (set-buffer tembuf)
2508           (erase-buffer)
2509           ;; Avoid copying text props.
2510           (insert (with-current-buffer mailbuf
2511                     (buffer-substring-no-properties (point-min) (point-max))))
2512           ;; Remove some headers.
2513           (message-encode-message-body)
2514           (save-restriction
2515             (message-narrow-to-headers)
2516             ;; We (re)generate the Lines header.
2517             (when (memq 'Lines message-required-mail-headers)
2518               (message-generate-headers '(Lines)))
2519             ;; Remove some headers.
2520             (message-remove-header message-ignored-mail-headers t)
2521             (let ((mail-parse-charset message-default-charset))
2522               (mail-encode-encoded-word-buffer)))
2523           (goto-char (point-max))
2524           ;; require one newline at the end.
2525           (or (= (preceding-char) ?\n)
2526               (insert ?\n))
2527           (when
2528               (save-restriction
2529                 (message-narrow-to-headers)
2530                 (and news
2531                      (or (message-fetch-field "cc")
2532                          (message-fetch-field "to"))
2533                      (let ((content-type (message-fetch-field "content-type")))
2534                        (or
2535                         (not content-type)
2536                         (string= "text/plain"
2537                                  (car
2538                                   (mail-header-parse-content-type
2539                                    content-type)))))))
2540             (message-insert-courtesy-copy))
2541           (if (or (not message-send-mail-partially-limit)
2542                   (< (point-max) message-send-mail-partially-limit)
2543                   (not (y-or-n-p "Message exceeds message-send-mail-partially-limit, send in parts? ")))
2544               (mm-with-unibyte-current-buffer
2545                 (message "Sending via mail...")
2546                 (funcall message-send-mail-function))
2547             (message-send-mail-partially)))
2548       (kill-buffer tembuf))
2549     (set-buffer mailbuf)
2550     (push 'mail message-sent-message-via)))
2551
2552 (defun message-send-mail-with-sendmail ()
2553   "Send off the prepared buffer with sendmail."
2554   (let ((errbuf (if message-interactive
2555                     (message-generate-new-buffer-clone-locals
2556                      " sendmail errors")
2557                   0))
2558         resend-to-addresses delimline)
2559     (let ((case-fold-search t))
2560       (save-restriction
2561         (message-narrow-to-headers)
2562         (setq resend-to-addresses (message-fetch-field "resent-to")))
2563       ;; Change header-delimiter to be what sendmail expects.
2564       (goto-char (point-min))
2565       (re-search-forward
2566        (concat "^" (regexp-quote mail-header-separator) "\n"))
2567       (replace-match "\n")
2568       (backward-char 1)
2569       (setq delimline (point-marker))
2570       (run-hooks 'message-send-mail-hook)
2571       ;; Insert an extra newline if we need it to work around
2572       ;; Sun's bug that swallows newlines.
2573       (goto-char (1+ delimline))
2574       (when (eval message-mailer-swallows-blank-line)
2575         (newline))
2576       (when message-interactive
2577         (save-excursion
2578           (set-buffer errbuf)
2579           (erase-buffer))))
2580     (let ((default-directory "/")
2581           (coding-system-for-write message-send-coding-system))
2582       (apply 'call-process-region
2583              (append (list (point-min) (point-max)
2584                            (if (boundp 'sendmail-program)
2585                                sendmail-program
2586                              "/usr/lib/sendmail")
2587                            nil errbuf nil "-oi")
2588                      ;; Always specify who from,
2589                      ;; since some systems have broken sendmails.
2590                      ;; But some systems are more broken with -f, so
2591                      ;; we'll let users override this.
2592                      (if (null message-sendmail-f-is-evil)
2593                          (list "-f" (message-make-address)))
2594                      ;; These mean "report errors by mail"
2595                      ;; and "deliver in background".
2596                      (if (null message-interactive) '("-oem" "-odb"))
2597                      ;; Get the addresses from the message
2598                      ;; unless this is a resend.
2599                      ;; We must not do that for a resend
2600                      ;; because we would find the original addresses.
2601                      ;; For a resend, include the specific addresses.
2602                      (if resend-to-addresses
2603                          (list resend-to-addresses)
2604                        '("-t")))))
2605     (when message-interactive
2606       (save-excursion
2607         (set-buffer errbuf)
2608         (goto-char (point-min))
2609         (while (re-search-forward "\n\n* *" nil t)
2610           (replace-match "; "))
2611         (if (not (zerop (buffer-size)))
2612             (error "Sending...failed to %s"
2613                    (buffer-substring (point-min) (point-max)))))
2614       (when (bufferp errbuf)
2615         (kill-buffer errbuf)))))
2616
2617 (defun message-send-mail-with-qmail ()
2618   "Pass the prepared message buffer to qmail-inject.
2619 Refer to the documentation for the variable `message-send-mail-function'
2620 to find out how to use this."
2621   ;; replace the header delimiter with a blank line
2622   (goto-char (point-min))
2623   (re-search-forward
2624    (concat "^" (regexp-quote mail-header-separator) "\n"))
2625   (replace-match "\n")
2626   (run-hooks 'message-send-mail-hook)
2627   ;; send the message
2628   (case
2629       (let ((coding-system-for-write message-send-coding-system))
2630         (apply
2631          'call-process-region 1 (point-max) message-qmail-inject-program
2632          nil nil nil
2633          ;; qmail-inject's default behaviour is to look for addresses on the
2634          ;; command line; if there're none, it scans the headers.
2635          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2636          ;;
2637          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2638          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2639          ;; message from stdin.
2640          ;;
2641          ;; qmail also has the advantage of not having been raped by
2642          ;; various vendors, so we don't have to allow for that, either --
2643          ;; compare this with message-send-mail-with-sendmail and weep
2644          ;; for sendmail's lost innocence.
2645          ;;
2646          ;; all this is way cool coz it lets us keep the arguments entirely
2647          ;; free for -inject-arguments -- a big win for the user and for us
2648          ;; since we don't have to play that double-guessing game and the user
2649          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2650          message-qmail-inject-args))
2651     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2652     ;; we have to look at the retval instead
2653     (0 nil)
2654     (100 (error "qmail-inject reported permanent failure"))
2655     (111 (error "qmail-inject reported transient failure"))
2656     ;; should never happen
2657     (t   (error "qmail-inject reported unknown failure"))))
2658
2659 (defun message-send-mail-with-mh ()
2660   "Send the prepared message buffer with mh."
2661   (let ((mh-previous-window-config nil)
2662         (name (mh-new-draft-name)))
2663     (setq buffer-file-name name)
2664     ;; MH wants to generate these headers itself.
2665     (when message-mh-deletable-headers
2666       (let ((headers message-mh-deletable-headers))
2667         (while headers
2668           (goto-char (point-min))
2669           (and (re-search-forward
2670                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2671                (message-delete-line))
2672           (pop headers))))
2673     (run-hooks 'message-send-mail-hook)
2674     ;; Pass it on to mh.
2675     (mh-send-letter)))
2676
2677 (defun message-send-news (&optional arg)
2678   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2679          (case-fold-search nil)
2680          (method (if (message-functionp message-post-method)
2681                      (funcall message-post-method arg)
2682                    message-post-method))
2683          (group-name-charset (gnus-group-name-charset method ""))
2684          (rfc2047-header-encoding-alist
2685           (if group-name-charset
2686               (cons (cons "Newsgroups" group-name-charset)
2687                     rfc2047-header-encoding-alist)
2688             rfc2047-header-encoding-alist))
2689          (messbuf (current-buffer))
2690          (message-syntax-checks
2691           (if arg
2692               (cons '(existing-newsgroups . disabled)
2693                     message-syntax-checks)
2694             message-syntax-checks))
2695          (message-this-is-news t)
2696          (message-posting-charset (gnus-setup-posting-charset
2697                                    (save-restriction
2698                                      (message-narrow-to-headers-or-head)
2699                                      (message-fetch-field "Newsgroups"))))
2700          result)
2701     (if (not (message-check-news-body-syntax))
2702         nil
2703       (save-restriction
2704         (message-narrow-to-headers)
2705         ;; Insert some headers.
2706         (message-generate-headers message-required-news-headers)
2707         ;; Let the user do all of the above.
2708         (run-hooks 'message-header-hook))
2709       (when group-name-charset
2710         (setq message-syntax-checks
2711               (cons '(valid-newsgroups . disabled)
2712                     message-syntax-checks)))
2713       (message-cleanup-headers)
2714       (if (not (message-check-news-syntax))
2715           nil
2716         (unwind-protect
2717             (save-excursion
2718               (set-buffer tembuf)
2719               (buffer-disable-undo)
2720               (erase-buffer)
2721               ;; Avoid copying text props.
2722               (insert (with-current-buffer messbuf
2723                         (buffer-substring-no-properties
2724                          (point-min) (point-max))))
2725               (message-encode-message-body)
2726               ;; Remove some headers.
2727               (save-restriction
2728                 (message-narrow-to-headers)
2729                 ;; We (re)generate the Lines header.
2730                 (when (memq 'Lines message-required-mail-headers)
2731                   (message-generate-headers '(Lines)))
2732                 ;; Remove some headers.
2733                 (message-remove-header message-ignored-news-headers t)
2734                 (let ((mail-parse-charset message-default-charset))
2735                   (mail-encode-encoded-word-buffer)))
2736               (goto-char (point-max))
2737               ;; require one newline at the end.
2738               (or (= (preceding-char) ?\n)
2739                   (insert ?\n))
2740               (let ((case-fold-search t))
2741                 ;; Remove the delimiter.
2742                 (goto-char (point-min))
2743                 (re-search-forward
2744                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2745                 (replace-match "\n")
2746                 (backward-char 1))
2747               (run-hooks 'message-send-news-hook)
2748               (gnus-open-server method)
2749               (message "Sending news with %s..." (gnus-server-string method))
2750               (setq result (let ((mail-header-separator ""))
2751                              (gnus-request-post method))))
2752           (kill-buffer tembuf))
2753         (set-buffer messbuf)
2754         (if result
2755             (push 'news message-sent-message-via)
2756           (message "Couldn't send message via news: %s"
2757                    (nnheader-get-report (car method)))
2758           nil)))))
2759
2760 ;;;
2761 ;;; Header generation & syntax checking.
2762 ;;;
2763
2764 (defun message-check-element (type)
2765   "Return non-nil if this TYPE is not to be checked."
2766   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2767       t
2768     (let ((able (assq type message-syntax-checks)))
2769       (and (consp able)
2770            (eq (cdr able) 'disabled)))))
2771
2772 (defun message-check-news-syntax ()
2773   "Check the syntax of the message."
2774   (save-excursion
2775     (save-restriction
2776       (widen)
2777       ;; We narrow to the headers and check them first.
2778       (save-excursion
2779         (save-restriction
2780           (message-narrow-to-headers)
2781           (message-check-news-header-syntax))))))
2782
2783 (defun message-check-news-header-syntax ()
2784   (and
2785    ;; Check Newsgroups header.
2786    (message-check 'newsgroups
2787      (let ((group (message-fetch-field "newsgroups")))
2788        (or
2789         (and group
2790              (not (string-match "\\`[ \t]*\\'" group)))
2791         (ignore
2792          (message
2793           "The newsgroups field is empty or missing.  Posting is denied.")))))
2794    ;; Check the Subject header.
2795    (message-check 'subject
2796      (let* ((case-fold-search t)
2797             (subject (message-fetch-field "subject")))
2798        (or
2799         (and subject
2800              (not (string-match "\\`[ \t]*\\'" subject)))
2801         (ignore
2802          (message
2803           "The subject field is empty or missing.  Posting is denied.")))))
2804    ;; Check for commands in Subject.
2805    (message-check 'subject-cmsg
2806      (if (string-match "^cmsg " (message-fetch-field "subject"))
2807          (y-or-n-p
2808           "The control code \"cmsg\" is in the subject.  Really post? ")
2809        t))
2810    ;; Check for multiple identical headers.
2811    (message-check 'multiple-headers
2812      (let (found)
2813        (while (and (not found)
2814                    (re-search-forward "^[^ \t:]+: " nil t))
2815          (save-excursion
2816            (or (re-search-forward
2817                 (concat "^"
2818                         (regexp-quote
2819                          (setq found
2820                                (buffer-substring
2821                                 (match-beginning 0) (- (match-end 0) 2))))
2822                         ":")
2823                 nil t)
2824                (setq found nil))))
2825        (if found
2826            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2827          t)))
2828    ;; Check for Version and Sendsys.
2829    (message-check 'sendsys
2830      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2831          (y-or-n-p
2832           (format "The article contains a %s command.  Really post? "
2833                   (buffer-substring (match-beginning 0)
2834                                     (1- (match-end 0)))))
2835        t))
2836    ;; See whether we can shorten Followup-To.
2837    (message-check 'shorten-followup-to
2838      (let ((newsgroups (message-fetch-field "newsgroups"))
2839            (followup-to (message-fetch-field "followup-to"))
2840            to)
2841        (when (and newsgroups
2842                   (string-match "," newsgroups)
2843                   (not followup-to)
2844                   (not
2845                    (zerop
2846                     (length
2847                      (setq to (completing-read
2848                                "Followups to: (default all groups) "
2849                                (mapcar (lambda (g) (list g))
2850                                        (cons "poster"
2851                                              (message-tokenize-header
2852                                               newsgroups)))))))))
2853          (goto-char (point-min))
2854          (insert "Followup-To: " to "\n"))
2855        t))
2856    ;; Check "Shoot me".
2857    (message-check 'shoot
2858      (if (re-search-forward
2859           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2860          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2861        t))
2862    ;; Check for Approved.
2863    (message-check 'approved
2864      (if (re-search-forward "^Approved:" nil t)
2865          (y-or-n-p "The article contains an Approved header.  Really post? ")
2866        t))
2867    ;; Check the Message-ID header.
2868    (message-check 'message-id
2869      (let* ((case-fold-search t)
2870             (message-id (message-fetch-field "message-id" t)))
2871        (or (not message-id)
2872            ;; Is there an @ in the ID?
2873            (and (string-match "@" message-id)
2874                 ;; Is there a dot in the ID?
2875                 (string-match "@[^.]*\\." message-id)
2876                 ;; Does the ID end with a dot?
2877                 (not (string-match "\\.>" message-id)))
2878            (y-or-n-p
2879             (format "The Message-ID looks strange: \"%s\".  Really post? "
2880                     message-id)))))
2881    ;; Check the Newsgroups & Followup-To headers.
2882    (message-check 'existing-newsgroups
2883      (let* ((case-fold-search t)
2884             (newsgroups (message-fetch-field "newsgroups"))
2885             (followup-to (message-fetch-field "followup-to"))
2886             (groups (message-tokenize-header
2887                      (if followup-to
2888                          (concat newsgroups "," followup-to)
2889                        newsgroups)))
2890             (hashtb (and (boundp 'gnus-active-hashtb)
2891                          gnus-active-hashtb))
2892             errors)
2893        (while groups
2894          (when (and (not (boundp (intern (car groups) hashtb)))
2895                     (not (equal (car groups) "poster")))
2896            (push (car groups) errors))
2897          (pop groups))
2898        (cond
2899         ;; Gnus is not running.
2900         ((or (not hashtb)
2901              (not (boundp 'gnus-read-active-file)))
2902          t)
2903         ;; We don't have all the group names.
2904         ((and (or (not gnus-read-active-file)
2905                   (eq gnus-read-active-file 'some))
2906               errors)
2907          (y-or-n-p
2908           (format
2909            "Really post to %s possibly unknown group%s: %s? "
2910            (if (= (length errors) 1) "this" "these")
2911            (if (= (length errors) 1) "" "s")
2912            (mapconcat 'identity errors ", "))))
2913         ;; There were no errors.
2914         ((not errors)
2915          t)
2916         ;; There are unknown groups.
2917         (t
2918          (y-or-n-p
2919           (format
2920            "Really post to %s unknown group%s: %s? "
2921            (if (= (length errors) 1) "this" "these")
2922            (if (= (length errors) 1) "" "s")
2923            (mapconcat 'identity errors ", ")))))))
2924      ;; Check the Newsgroups & Followup-To headers for syntax errors.
2925      (message-check 'valid-newsgroups
2926        (let ((case-fold-search t)
2927              (headers '("Newsgroups" "Followup-To"))
2928              header error)
2929          (while (and headers (not error))
2930            (when (setq header (mail-fetch-field (car headers)))
2931              (if (or
2932                   (not
2933                    (string-match
2934                     "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2935                     header))
2936                   (memq
2937                    nil (mapcar
2938                         (lambda (g)
2939                           (not (string-match "\\.\\'\\|\\.\\." g)))
2940                         (message-tokenize-header header ","))))
2941                  (setq error t)))
2942            (unless error
2943              (pop headers)))
2944          (if (not error)
2945              t
2946            (y-or-n-p
2947             (format "The %s header looks odd: \"%s\".  Really post? "
2948                     (car headers) header)))))
2949      (message-check 'repeated-newsgroups
2950        (let ((case-fold-search t)
2951              (headers '("Newsgroups" "Followup-To"))
2952              header error groups group)
2953          (while (and headers
2954                      (not error))
2955            (when (setq header (mail-fetch-field (pop headers)))
2956              (setq groups (message-tokenize-header header ","))
2957              (while (setq group (pop groups))
2958                (when (member group groups)
2959                  (setq error group
2960                        groups nil)))))
2961          (if (not error)
2962              t
2963            (y-or-n-p
2964             (format "Group %s is repeated in headers.  Really post? " error)))))
2965      ;; Check the From header.
2966      (message-check 'from
2967        (let* ((case-fold-search t)
2968               (from (message-fetch-field "from"))
2969               ad)
2970          (cond
2971           ((not from)
2972            (message "There is no From line.  Posting is denied.")
2973            nil)
2974           ((or (not (string-match
2975                      "@[^\\.]*\\."
2976                      (setq ad (nth 1 (mail-extract-address-components
2977                                       from))))) ;larsi@ifi
2978                (string-match "\\.\\." ad) ;larsi@ifi..uio
2979                (string-match "@\\." ad) ;larsi@.ifi.uio
2980                (string-match "\\.$" ad) ;larsi@ifi.uio.
2981                (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2982                (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2983            (message
2984             "Denied posting -- the From looks strange: \"%s\"." from)
2985            nil)
2986           (t t))))
2987      ;; Check the Reply-To header.
2988      (message-check 'reply-to
2989        (let* ((case-fold-search t)
2990               (reply-to (message-fetch-field "reply-to"))
2991               ad)
2992          (cond
2993           ((not reply-to)
2994            t)
2995           ((string-match "," reply-to)
2996            (y-or-n-p
2997             (format "Multiple Reply-To addresses: \"%s\". Really post? "
2998                     reply-to)))
2999           ((or (not (string-match
3000                      "@[^\\.]*\\."
3001                      (setq ad (nth 1 (mail-extract-address-components
3002                                       reply-to))))) ;larsi@ifi
3003                (string-match "\\.\\." ad) ;larsi@ifi..uio
3004                (string-match "@\\." ad) ;larsi@.ifi.uio
3005                (string-match "\\.$" ad) ;larsi@ifi.uio.
3006                (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
3007                (string-match "(.*).*(.*)" reply-to)) ;(lars) (lars)
3008            (y-or-n-p
3009             (format
3010              "The Reply-To looks strange: \"%s\". Really post? " 
3011              reply-to)))
3012           (t t))))))
3013
3014 (defun message-check-news-body-syntax ()
3015   (and
3016    ;; Check for long lines.
3017    (message-check 'long-lines
3018      (goto-char (point-min))
3019      (re-search-forward
3020       (concat "^" (regexp-quote mail-header-separator) "$"))
3021      (forward-line 1)
3022      (while (and
3023              (or (looking-at
3024                   "<#\\(/\\)?\\(multipart\\|part\\|external\\|mml\\)")
3025                  (let ((p (point)))
3026                    (end-of-line)
3027                    (< (- (point) p) 80)))
3028              (zerop (forward-line 1))))
3029      (or (bolp)
3030          (eobp)
3031          (y-or-n-p
3032           "You have lines longer than 79 characters.  Really post? ")))
3033    ;; Check whether the article is empty.
3034    (message-check 'empty
3035      (goto-char (point-min))
3036      (re-search-forward
3037       (concat "^" (regexp-quote mail-header-separator) "$"))
3038      (forward-line 1)
3039      (let ((b (point)))
3040        (goto-char (point-max))
3041        (re-search-backward message-signature-separator nil t)
3042        (beginning-of-line)
3043        (or (re-search-backward "[^ \n\t]" b t)
3044            (if (message-gnksa-enable-p 'empty-article)
3045                (y-or-n-p "Empty article.  Really post? ")
3046              (message "Denied posting -- Empty article.")
3047              nil))))
3048    ;; Check for control characters.
3049    (message-check 'control-chars
3050      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
3051          (y-or-n-p
3052           "The article contains control characters.  Really post? ")
3053        t))
3054    ;; Check excessive size.
3055    (message-check 'size
3056      (if (> (buffer-size) 60000)
3057          (y-or-n-p
3058           (format "The article is %d octets long.  Really post? "
3059                   (buffer-size)))
3060        t))
3061    ;; Check whether any new text has been added.
3062    (message-check 'new-text
3063      (or
3064       (not message-checksum)
3065       (not (eq (message-checksum) message-checksum))
3066       (if (message-gnksa-enable-p 'quoted-text-only)
3067           (y-or-n-p
3068            "It looks like no new text has been added.  Really post? ")
3069         (message "Denied posting -- no new text has been added.")
3070         nil)))
3071    ;; Check the length of the signature.
3072    (message-check 'signature
3073      (goto-char (point-max))
3074      (if (> (count-lines (point) (point-max)) 5)
3075          (y-or-n-p
3076           (format
3077            "Your .sig is %d lines; it should be max 4.  Really post? "
3078            (1- (count-lines (point) (point-max)))))
3079        t))
3080    ;; Ensure that text follows last quoted portion.
3081    (message-check 'quoting-style
3082      (goto-char (point-max))
3083      (let ((no-problem t))
3084        (when (search-backward-regexp "^>[^\n]*\n" nil t)
3085          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
3086        (if no-problem
3087            t
3088          (if (message-gnksa-enable-p 'quoted-text-only)
3089              (y-or-n-p "Your text should follow quoted text.  Really post? ")
3090            ;; Ensure that
3091            (goto-char (point-min))
3092            (re-search-forward
3093             (concat "^" (regexp-quote mail-header-separator) "$"))
3094            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
3095                (y-or-n-p "Your text should follow quoted text.  Really post? ")
3096              (message "Denied posting -- only quoted text.")
3097              nil)))))))
3098
3099 (defun message-checksum ()
3100   "Return a \"checksum\" for the current buffer."
3101   (let ((sum 0))
3102     (save-excursion
3103       (goto-char (point-min))
3104       (re-search-forward
3105        (concat "^" (regexp-quote mail-header-separator) "$"))
3106       (while (not (eobp))
3107         (when (not (looking-at "[ \t\n]"))
3108           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
3109                             (char-after))))
3110         (forward-char 1)))
3111     sum))
3112
3113 (defun message-do-fcc ()
3114   "Process Fcc headers in the current buffer."
3115   (let ((case-fold-search t)
3116         (buf (current-buffer))
3117         list file)
3118     (save-excursion
3119       (save-restriction
3120         (message-narrow-to-headers)
3121         (setq file (message-fetch-field "fcc" t)))
3122       (when file
3123         (set-buffer (get-buffer-create " *message temp*"))
3124         (erase-buffer)
3125         (insert-buffer-substring buf)
3126         (message-encode-message-body)
3127         (save-restriction
3128           (message-narrow-to-headers)
3129           (while (setq file (message-fetch-field "fcc" t))
3130             (push file list)
3131             (message-remove-header "fcc" nil t))
3132           (let ((mail-parse-charset message-default-charset)
3133                 (rfc2047-header-encoding-alist
3134                  (cons '("Newsgroups" . default)
3135                        rfc2047-header-encoding-alist)))
3136             (mail-encode-encoded-word-buffer)))
3137         (goto-char (point-min))
3138         (when (re-search-forward
3139                (concat "^" (regexp-quote mail-header-separator) "$")
3140                nil t)
3141           (replace-match "" t t ))
3142         ;; Process FCC operations.
3143         (while list
3144           (setq file (pop list))
3145           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3146               ;; Pipe the article to the program in question.
3147               (call-process-region (point-min) (point-max) shell-file-name
3148                                    nil nil nil shell-command-switch
3149                                    (match-string 1 file))
3150             ;; Save the article.
3151             (setq file (expand-file-name file))
3152             (unless (file-exists-p (file-name-directory file))
3153               (make-directory (file-name-directory file) t))
3154             (if (and message-fcc-handler-function
3155                      (not (eq message-fcc-handler-function 'rmail-output)))
3156                 (funcall message-fcc-handler-function file)
3157               (if (and (file-readable-p file) (mail-file-babyl-p file))
3158                   (rmail-output file 1 nil t)
3159                 (let ((mail-use-rfc822 t))
3160                   (rmail-output file 1 t t))))))
3161         (kill-buffer (current-buffer))))))
3162
3163 (defun message-output (filename)
3164   "Append this article to Unix/babyl mail file FILENAME."
3165   (if (and (file-readable-p filename)
3166            (mail-file-babyl-p filename))
3167       (gnus-output-to-rmail filename t)
3168     (gnus-output-to-mail filename t)))
3169
3170 (defun message-cleanup-headers ()
3171   "Do various automatic cleanups of the headers."
3172   ;; Remove empty lines in the header.
3173   (save-restriction
3174     (message-narrow-to-headers)
3175     ;; Remove blank lines.
3176     (while (re-search-forward "^[ \t]*\n" nil t)
3177       (replace-match "" t t))
3178
3179     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3180     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3181     ;; embedded line breaks.
3182     (goto-char (point-min))
3183     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3184       (save-restriction
3185         (narrow-to-region
3186          (point)
3187          (if (re-search-forward "^[^ \t]" nil t)
3188              (match-beginning 0)
3189            (forward-line 1)
3190            (point)))
3191         (goto-char (point-min))
3192         (while (re-search-forward "\n[ \t]+" nil t)
3193           (replace-match " " t t))      ;No line breaks (too confusing)
3194         (goto-char (point-min))
3195         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3196           (replace-match "," t t))
3197         (goto-char (point-min))
3198         ;; Remove trailing commas.
3199         (when (re-search-forward ",+$" nil t)
3200           (replace-match "" t t))))))
3201
3202 (defun message-make-date (&optional now)
3203   "Make a valid data header.
3204 If NOW, use that time instead."
3205   (let* ((now (or now (current-time)))
3206          (zone (nth 8 (decode-time now)))
3207          (sign "+"))
3208     (when (< zone 0)
3209       (setq sign "-")
3210       (setq zone (- zone)))
3211     (concat
3212      (format-time-string "%a, %d" now)
3213      ;; The month name of the %b spec is locale-specific.  Pfff.
3214      (format " %s "
3215              (capitalize (car (rassoc (nth 4 (decode-time now))
3216                                       parse-time-months))))
3217      (format-time-string "%Y %H:%M:%S " now)
3218      ;; We do all of this because XEmacs doesn't have the %z spec.
3219      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3220
3221 (defun message-make-message-id ()
3222   "Make a unique Message-ID."
3223   (concat "<" (message-unique-id)
3224           (let ((psubject (save-excursion (message-fetch-field "subject")))
3225                 (psupersedes
3226                  (save-excursion (message-fetch-field "supersedes"))))
3227             (if (or
3228                  (and message-reply-headers
3229                       (mail-header-references message-reply-headers)
3230                       (mail-header-subject message-reply-headers)
3231                       psubject
3232                       (not (string=
3233                             (message-strip-subject-re
3234                              (mail-header-subject message-reply-headers))
3235                             (message-strip-subject-re psubject))))
3236                  (and psupersedes
3237                       (string-match "_-_@" psupersedes)))
3238                 "_-_" ""))
3239           "@" (message-make-fqdn) ">"))
3240
3241 (defvar message-unique-id-char nil)
3242
3243 ;; If you ever change this function, make sure the new version
3244 ;; cannot generate IDs that the old version could.
3245 ;; You might for example insert a "." somewhere (not next to another dot
3246 ;; or string boundary), or modify the "fsf" string.
3247 (defun message-unique-id ()
3248   ;; Don't use microseconds from (current-time), they may be unsupported.
3249   ;; Instead we use this randomly inited counter.
3250   (setq message-unique-id-char
3251         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3252            ;; (current-time) returns 16-bit ints,
3253            ;; and 2^16*25 just fits into 4 digits i base 36.
3254            (* 25 25)))
3255   (let ((tm (current-time)))
3256     (concat
3257      (if (memq system-type '(ms-dos emx vax-vms))
3258          (let ((user (downcase (user-login-name))))
3259            (while (string-match "[^a-z0-9_]" user)
3260              (aset user (match-beginning 0) ?_))
3261            user)
3262        (message-number-base36 (user-uid) -1))
3263      (message-number-base36 (+ (car   tm)
3264                                (lsh (% message-unique-id-char 25) 16)) 4)
3265      (message-number-base36 (+ (nth 1 tm)
3266                                (lsh (/ message-unique-id-char 25) 16)) 4)
3267      ;; Append the newsreader name, because while the generated
3268      ;; ID is unique to this newsreader, other newsreaders might
3269      ;; otherwise generate the same ID via another algorithm.
3270      ".fsf")))
3271
3272 (defun message-number-base36 (num len)
3273   (if (if (< len 0)
3274           (<= num 0)
3275         (= len 0))
3276       ""
3277     (concat (message-number-base36 (/ num 36) (1- len))
3278             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3279                                   (% num 36))))))
3280
3281 (defun message-make-organization ()
3282   "Make an Organization header."
3283   (let* ((organization
3284           (when message-user-organization
3285             (if (message-functionp message-user-organization)
3286                 (funcall message-user-organization)
3287               message-user-organization))))
3288     (save-excursion
3289       (message-set-work-buffer)
3290       (cond ((stringp organization)
3291              (insert organization))
3292             ((and (eq t organization)
3293                   message-user-organization-file
3294                   (file-exists-p message-user-organization-file))
3295              (insert-file-contents message-user-organization-file)))
3296       (goto-char (point-min))
3297       (while (re-search-forward "[\t\n]+" nil t)
3298         (replace-match "" t t))
3299       (unless (zerop (buffer-size))
3300         (buffer-string)))))
3301
3302 (defun message-make-lines ()
3303   "Count the number of lines and return numeric string."
3304   (save-excursion
3305     (save-restriction
3306       (widen)
3307       (message-goto-body)
3308       (int-to-string (count-lines (point) (point-max))))))
3309
3310 (defun message-make-in-reply-to ()
3311   "Return the In-Reply-To header for this message."
3312   (when message-reply-headers
3313     (let ((from (mail-header-from message-reply-headers))
3314           (date (mail-header-date message-reply-headers))
3315           (msg-id (mail-header-message-id message-reply-headers)))
3316       (when from
3317         (let ((stop-pos
3318                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
3319           (concat msg-id (if msg-id " (")
3320                   (if (and stop-pos
3321                            (not (zerop stop-pos)))
3322                       (substring from 0 stop-pos) from)
3323                   "'s message of \""
3324                   (if (or (not date) (string= date ""))
3325                       "(unknown date)" date)
3326                   "\"" (if msg-id ")")))))))
3327
3328 (defun message-make-distribution ()
3329   "Make a Distribution header."
3330   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3331     (cond ((message-functionp message-distribution-function)
3332            (funcall message-distribution-function))
3333           (t orig-distribution))))
3334
3335 (defun message-make-expires ()
3336   "Return an Expires header based on `message-expires'."
3337   (let ((current (current-time))
3338         (future (* 1.0 message-expires 60 60 24)))
3339     ;; Add the future to current.
3340     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3341     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3342     (message-make-date current)))
3343
3344 (defun message-make-path ()
3345   "Return uucp path."
3346   (let ((login-name (user-login-name)))
3347     (cond ((null message-user-path)
3348            (concat (system-name) "!" login-name))
3349           ((stringp message-user-path)
3350            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3351            (concat message-user-path "!" login-name))
3352           (t login-name))))
3353
3354 (defun message-make-from ()
3355   "Make a From header."
3356   (let* ((style message-from-style)
3357          (login (message-make-address))
3358          (fullname
3359           (or (and (boundp 'user-full-name)
3360                    user-full-name)
3361               (user-full-name))))
3362     (when (string= fullname "&")
3363       (setq fullname (user-login-name)))
3364     (save-excursion
3365       (message-set-work-buffer)
3366       (cond
3367        ((or (null style)
3368             (equal fullname ""))
3369         (insert login))
3370        ((or (eq style 'angles)
3371             (and (not (eq style 'parens))
3372                  ;; Use angles if no quoting is needed, or if parens would
3373                  ;; need quoting too.
3374                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3375                      (let ((tmp (concat fullname nil)))
3376                        (while (string-match "([^()]*)" tmp)
3377                          (aset tmp (match-beginning 0) ?-)
3378                          (aset tmp (1- (match-end 0)) ?-))
3379                        (string-match "[\\()]" tmp)))))
3380         (insert fullname)
3381         (goto-char (point-min))
3382         ;; Look for a character that cannot appear unquoted
3383         ;; according to RFC 822.
3384         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3385           ;; Quote fullname, escaping specials.
3386           (goto-char (point-min))
3387           (insert "\"")
3388           (while (re-search-forward "[\"\\]" nil 1)
3389             (replace-match "\\\\\\&" t))
3390           (insert "\""))
3391         (insert " <" login ">"))
3392        (t                               ; 'parens or default
3393         (insert login " (")
3394         (let ((fullname-start (point)))
3395           (insert fullname)
3396           (goto-char fullname-start)
3397           ;; RFC 822 says \ and nonmatching parentheses
3398           ;; must be escaped in comments.
3399           ;; Escape every instance of ()\ ...
3400           (while (re-search-forward "[()\\]" nil 1)
3401             (replace-match "\\\\\\&" t))
3402           ;; ... then undo escaping of matching parentheses,
3403           ;; including matching nested parentheses.
3404           (goto-char fullname-start)
3405           (while (re-search-forward
3406                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3407                   nil 1)
3408             (replace-match "\\1(\\3)" t)
3409             (goto-char fullname-start)))
3410         (insert ")")))
3411       (buffer-string))))
3412
3413 (defun message-make-sender ()
3414   "Return the \"real\" user address.
3415 This function tries to ignore all user modifications, and
3416 give as trustworthy answer as possible."
3417   (concat (user-login-name) "@" (system-name)))
3418
3419 (defun message-make-address ()
3420   "Make the address of the user."
3421   (or (message-user-mail-address)
3422       (concat (user-login-name) "@" (message-make-domain))))
3423
3424 (defun message-user-mail-address ()
3425   "Return the pertinent part of `user-mail-address'."
3426   (when user-mail-address
3427     (if (string-match " " user-mail-address)
3428         (nth 1 (mail-extract-address-components user-mail-address))
3429       user-mail-address)))
3430
3431 (defun message-make-fqdn ()
3432   "Return user's fully qualified domain name."
3433   (let ((system-name (system-name))
3434         (user-mail (message-user-mail-address)))
3435     (cond
3436      ((string-match "[^.]\\.[^.]" system-name)
3437       ;; `system-name' returned the right result.
3438       system-name)
3439      ;; Try `mail-host-address'.
3440      ((and (boundp 'mail-host-address)
3441            (stringp mail-host-address)
3442            (string-match "\\." mail-host-address))
3443       mail-host-address)
3444      ;; We try `user-mail-address' as a backup.
3445      ((and user-mail
3446            (string-match "\\." user-mail)
3447            (string-match "@\\(.*\\)\\'" user-mail))
3448       (match-string 1 user-mail))
3449      ;; Default to this bogus thing.
3450      (t
3451       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3452
3453 (defun message-make-host-name ()
3454   "Return the name of the host."
3455   (let ((fqdn (message-make-fqdn)))
3456     (string-match "^[^.]+\\." fqdn)
3457     (substring fqdn 0 (1- (match-end 0)))))
3458
3459 (defun message-make-domain ()
3460   "Return the domain name."
3461   (or mail-host-address
3462       (message-make-fqdn)))
3463
3464 (defun message-generate-headers (headers)
3465   "Prepare article HEADERS.
3466 Headers already prepared in the buffer are not modified."
3467   (save-restriction
3468     (message-narrow-to-headers)
3469     (let* ((Date (message-make-date))
3470            (Message-ID (message-make-message-id))
3471            (Organization (message-make-organization))
3472            (From (message-make-from))
3473            (Path (message-make-path))
3474            (Subject nil)
3475            (Newsgroups nil)
3476            (In-Reply-To (message-make-in-reply-to))
3477            (To nil)
3478            (Distribution (message-make-distribution))
3479            (Lines (message-make-lines))
3480            (User-Agent message-newsreader)
3481            (Expires (message-make-expires))
3482            (case-fold-search t)
3483            header value elem)
3484       ;; First we remove any old generated headers.
3485       (let ((headers message-deletable-headers))
3486         (unless (buffer-modified-p)
3487           (setq headers (delq 'Message-ID (copy-sequence headers))))
3488         (while headers
3489           (goto-char (point-min))
3490           (and (re-search-forward
3491                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3492                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3493                (message-delete-line))
3494           (pop headers)))
3495       ;; Go through all the required headers and see if they are in the
3496       ;; articles already.  If they are not, or are empty, they are
3497       ;; inserted automatically - except for Subject, Newsgroups and
3498       ;; Distribution.
3499       (while headers
3500         (goto-char (point-min))
3501         (setq elem (pop headers))
3502         (if (consp elem)
3503             (if (eq (car elem) 'optional)
3504                 (setq header (cdr elem))
3505               (setq header (car elem)))
3506           (setq header elem))
3507         (when (or (not (re-search-forward
3508                         (concat "^"
3509                                 (regexp-quote
3510                                  (downcase
3511                                   (if (stringp header)
3512                                       header
3513                                     (symbol-name header))))
3514                                 ":")
3515                         nil t))
3516                   (progn
3517                     ;; The header was found.  We insert a space after the
3518                     ;; colon, if there is none.
3519                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3520                     ;; Find out whether the header is empty...
3521                     (looking-at "[ \t]*\n[^ \t]")))
3522           ;; So we find out what value we should insert.
3523           (setq value
3524                 (cond
3525                  ((and (consp elem) (eq (car elem) 'optional))
3526                   ;; This is an optional header.  If the cdr of this
3527                   ;; is something that is nil, then we do not insert
3528                   ;; this header.
3529                   (setq header (cdr elem))
3530                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3531                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3532                  ((consp elem)
3533                   ;; The element is a cons.  Either the cdr is a
3534                   ;; string to be inserted verbatim, or it is a
3535                   ;; function, and we insert the value returned from
3536                   ;; this function.
3537                   (or (and (stringp (cdr elem)) (cdr elem))
3538                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3539                  ((and (boundp header) (symbol-value header))
3540                   ;; The element is a symbol.  We insert the value
3541                   ;; of this symbol, if any.
3542                   (symbol-value header))
3543                  ((not (message-check-element header))
3544                   ;; We couldn't generate a value for this header,
3545                   ;; so we just ask the user.
3546                   (read-from-minibuffer
3547                    (format "Empty header for %s; enter value: " header)))))
3548           ;; Finally insert the header.
3549           (when (and value
3550                      (not (equal value "")))
3551             (save-excursion
3552               (if (bolp)
3553                   (progn
3554                     ;; This header didn't exist, so we insert it.
3555                     (goto-char (point-max))
3556                     (insert (if (stringp header) header (symbol-name header))
3557                             ": " value "\n")
3558                     (forward-line -1))
3559                 ;; The value of this header was empty, so we clear
3560                 ;; totally and insert the new value.
3561                 (delete-region (point) (gnus-point-at-eol))
3562                 (insert value))
3563               ;; Add the deletable property to the headers that require it.
3564               (and (memq header message-deletable-headers)
3565                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3566                    (add-text-properties
3567                     (point) (match-end 0)
3568                     '(message-deletable t face italic) (current-buffer)))))))
3569       ;; Insert new Sender if the From is strange.
3570       (let ((from (message-fetch-field "from"))
3571             (sender (message-fetch-field "sender"))
3572             (secure-sender (message-make-sender)))
3573         (when (and from
3574                    (not (message-check-element 'sender))
3575                    (not (string=
3576                          (downcase
3577                           (cadr (mail-extract-address-components from)))
3578                          (downcase secure-sender)))
3579                    (or (null sender)
3580                        (not
3581                         (string=
3582                          (downcase
3583                           (cadr (mail-extract-address-components sender)))
3584                          (downcase secure-sender)))))
3585           (goto-char (point-min))
3586           ;; Rename any old Sender headers to Original-Sender.
3587           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3588             (beginning-of-line)
3589             (insert "Original-")
3590             (beginning-of-line))
3591           (when (or (message-news-p)
3592                     (string-match "@.+\\.." secure-sender))
3593             (insert "Sender: " secure-sender "\n")))))))
3594
3595 (defun message-insert-courtesy-copy ()
3596   "Insert a courtesy message in mail copies of combined messages."
3597   (let (newsgroups)
3598     (save-excursion
3599       (save-restriction
3600         (message-narrow-to-headers)
3601         (when (setq newsgroups (message-fetch-field "newsgroups"))
3602           (goto-char (point-max))
3603           (insert "Posted-To: " newsgroups "\n")))
3604       (forward-line 1)
3605       (when message-courtesy-message
3606         (cond
3607          ((string-match "%s" message-courtesy-message)
3608           (insert (format message-courtesy-message newsgroups)))
3609          (t
3610           (insert message-courtesy-message)))))))
3611
3612 ;;;
3613 ;;; Setting up a message buffer
3614 ;;;
3615
3616 (defun message-fill-address (header value)
3617   (save-restriction
3618     (narrow-to-region (point) (point))
3619     (insert (capitalize (symbol-name header))
3620             ": "
3621             (if (consp value) (car value) value)
3622             "\n")
3623     (narrow-to-region (point-min) (1- (point-max)))
3624     (let (quoted last)
3625       (goto-char (point-min))
3626       (while (not (eobp))
3627         (skip-chars-forward "^,\"" (point-max))
3628         (if (or (eq (char-after) ?,)
3629                 (eobp))
3630             (when (not quoted)
3631               (if (and (> (current-column) 78)
3632                        last)
3633                   (progn
3634                     (save-excursion
3635                       (goto-char last)
3636                       (insert "\n\t"))
3637                     (setq last (1+ (point))))
3638                 (setq last (1+ (point)))))
3639           (setq quoted (not quoted)))
3640         (unless (eobp)
3641           (forward-char 1))))
3642     (goto-char (point-max))
3643     (widen)
3644     (forward-line 1)))
3645
3646 (defun message-fill-header (header value)
3647   (let ((begin (point))
3648         (fill-column 78)
3649         (fill-prefix "\t"))
3650     (insert (capitalize (symbol-name header))
3651             ": "
3652             (if (consp value) (car value) value)
3653             "\n")
3654     (save-restriction
3655       (narrow-to-region begin (point))
3656       (fill-region-as-paragraph begin (point))
3657       ;; Tapdance around looong Message-IDs.
3658       (forward-line -1)
3659       (when (looking-at "[ \t]*$")
3660         (message-delete-line))
3661       (goto-char begin)
3662       (re-search-forward ":" nil t)
3663       (when (looking-at "\n[ \t]+")
3664         (replace-match " " t t))
3665       (goto-char (point-max)))))
3666
3667 (defun message-shorten-1 (list cut surplus)
3668   "Cut SURPLUS elements out of LIST, beginning with CUTth one."
3669   (setcdr (nthcdr (- cut 2) list)
3670           (nthcdr (+ (- cut 2) surplus 1) list)))
3671
3672 (defun message-shorten-references (header references)
3673   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3674 If folding is disallowed, also check that the REFERENCES are less
3675 than 988 characters long, and if they are not, trim them until they are."
3676   (let ((maxcount 31)
3677         (count 0)
3678         (cut 6)
3679         refs)
3680     (with-temp-buffer
3681       (insert references)
3682       (goto-char (point-min))
3683       ;; Cons a list of valid references.
3684       (while (re-search-forward "<[^>]+>" nil t)
3685         (push (match-string 0) refs))
3686       (setq refs (nreverse refs)
3687             count (length refs)))
3688
3689     ;; If the list has more than MAXCOUNT elements, trim it by
3690     ;; removing the CUTth element and the required number of
3691     ;; elements that follow.
3692     (when (> count maxcount)
3693       (let ((surplus (- count maxcount)))
3694         (message-shorten-1 refs cut surplus)
3695         (decf count surplus)))
3696
3697     ;; If folding is disallowed, make sure the total length (including
3698     ;; the spaces between) will be less than MAXSIZE characters.
3699     ;;
3700     ;; Only disallow folding for News messages. At this point the headers
3701     ;; have not been generated, thus we use message-this-is-news directly.
3702     (when (and message-this-is-news message-cater-to-broken-inn)
3703       (let ((maxsize 988)
3704             (totalsize (+ (apply #'+ (mapcar #'length refs))
3705                           (1- count)))
3706             (surplus 0)
3707             (ptr (nthcdr (1- cut) refs)))
3708         ;; Decide how many elements to cut off...
3709         (while (> totalsize maxsize)
3710           (decf totalsize (1+ (length (car ptr))))
3711           (incf surplus)
3712           (setq ptr (cdr ptr)))
3713         ;; ...and do it.
3714         (when (> surplus 0)
3715           (message-shorten-1 refs cut surplus))))
3716
3717     ;; Finally, collect the references back into a string and insert
3718     ;; it into the buffer.
3719     (let ((refstring (mapconcat #'identity refs " ")))
3720       (if (and message-this-is-news message-cater-to-broken-inn)
3721           (insert (capitalize (symbol-name header)) ": "
3722                   refstring "\n")
3723         (message-fill-header header refstring)))))
3724
3725 (defun message-position-point ()
3726   "Move point to where the user probably wants to find it."
3727   (message-narrow-to-headers)
3728   (cond
3729    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3730     (search-backward ":" )
3731     (widen)
3732     (forward-char 1)
3733     (if (eq (char-after) ? )
3734         (forward-char 1)
3735       (insert " ")))
3736    (t
3737     (goto-char (point-max))
3738     (widen)
3739     (forward-line 1)
3740     (unless (looking-at "$")
3741       (forward-line 2)))
3742    (sit-for 0)))
3743
3744 (defun message-buffer-name (type &optional to group)
3745   "Return a new (unique) buffer name based on TYPE and TO."
3746   (cond
3747    ;; Generate a new buffer name The Message Way.
3748    ((eq message-generate-new-buffers 'unique)
3749     (generate-new-buffer-name
3750      (concat "*" type
3751              (if to
3752                  (concat " to "
3753                          (or (car (mail-extract-address-components to))
3754                              to) "")
3755                "")
3756              (if (and group (not (string= group ""))) (concat " on " group) "")
3757              "*")))
3758    ;; Check whether `message-generate-new-buffers' is a function,
3759    ;; and if so, call it.
3760    ((message-functionp message-generate-new-buffers)
3761     (funcall message-generate-new-buffers type to group))
3762    ((eq message-generate-new-buffers 'unsent)
3763     (generate-new-buffer-name
3764      (concat "*unsent " type
3765              (if to
3766                  (concat " to "
3767                          (or (car (mail-extract-address-components to))
3768                              to) "")
3769                "")
3770              (if (and group (not (string= group ""))) (concat " on " group) "")
3771              "*")))
3772    ;; Use standard name.
3773    (t
3774     (format "*%s message*" type))))
3775
3776 (defun message-pop-to-buffer (name)
3777   "Pop to buffer NAME, and warn if it already exists and is modified."
3778   (let ((buffer (get-buffer name)))
3779     (if (and buffer
3780              (buffer-name buffer))
3781         (progn
3782           (set-buffer (pop-to-buffer buffer))
3783           (when (and (buffer-modified-p)
3784                      (not (y-or-n-p
3785                            "Message already being composed; erase? ")))
3786             (error "Message being composed")))
3787       (set-buffer (pop-to-buffer name)))
3788     (erase-buffer)
3789     (message-mode)))
3790
3791 (defun message-do-send-housekeeping ()
3792   "Kill old message buffers."
3793   ;; We might have sent this buffer already.  Delete it from the
3794   ;; list of buffers.
3795   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3796   (while (and message-max-buffers
3797               message-buffer-list
3798               (>= (length message-buffer-list) message-max-buffers))
3799     ;; Kill the oldest buffer -- unless it has been changed.
3800     (let ((buffer (pop message-buffer-list)))
3801       (when (and (buffer-name buffer)
3802                  (not (buffer-modified-p buffer)))
3803         (kill-buffer buffer))))
3804   ;; Rename the buffer.
3805   (if message-send-rename-function
3806       (funcall message-send-rename-function)
3807     ;; Note: mail-abbrevs of XEmacs renames buffer name behind Gnus.
3808     (when (string-match
3809            "\\`\\*\\(sent \\|unsent \\)?\\(.+\\)\\*[^\\*]*\\|\\`mail to "
3810            (buffer-name))
3811       (let ((name (match-string 2 (buffer-name)))
3812             to group)
3813         (if (not (or (null name)
3814                      (string-equal name "mail")
3815                      (string-equal name "news")))
3816             (setq name (concat "*sent " name "*"))
3817           (setq to (message-fetch-field "to"))
3818           (setq group (message-fetch-field "newsgroups"))
3819           (setq name
3820                 (cond
3821                  (to (concat "*sent mail to "
3822                              (or (car (mail-extract-address-components to))
3823                                  to) "*"))
3824                  ((and group (not (string= group "")))
3825                   (concat "*sent news on " group "*"))
3826                  (t "*sent mail*"))))
3827         (unless (string-equal name (buffer-name))
3828           (rename-buffer name t)))))
3829   ;; Push the current buffer onto the list.
3830   (when message-max-buffers
3831     (setq message-buffer-list
3832           (nconc message-buffer-list (list (current-buffer))))))
3833
3834 (defun message-mail-user-agent ()
3835   (let ((mua (cond
3836               ((not message-mail-user-agent) nil)
3837               ((eq message-mail-user-agent t) mail-user-agent)
3838               (t message-mail-user-agent))))
3839     (if (memq mua '(message-user-agent gnus-user-agent))
3840         nil
3841       mua)))
3842
3843 (defun message-setup (headers &optional replybuffer actions switch-function)
3844   (let ((mua (message-mail-user-agent))
3845         subject to field yank-action)
3846     (if (not (and message-this-is-mail mua))
3847         (message-setup-1 headers replybuffer actions)
3848       (if replybuffer
3849           (setq yank-action (list 'insert-buffer replybuffer)))
3850       (setq headers (copy-sequence headers))
3851       (setq field (assq 'Subject headers))
3852       (when field
3853         (setq subject (cdr field))
3854         (setq headers (delq field headers)))
3855       (setq field (assq 'To headers))
3856       (when field
3857         (setq to (cdr field))
3858         (setq headers (delq field headers)))
3859       (let ((mail-user-agent mua))
3860         (compose-mail to subject
3861                       (mapcar (lambda (item)
3862                                 (cons
3863                                  (format "%s" (car item))
3864                                  (cdr item)))
3865                               headers)
3866                       nil switch-function yank-action actions)))))
3867
3868 ;;;(defvar mc-modes-alist)
3869 (defun message-setup-1 (headers &optional replybuffer actions)
3870 ;;;   (when (and (boundp 'mc-modes-alist)
3871 ;;;          (not (assq 'message-mode mc-modes-alist)))
3872 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3873 ;;;                      (sign . mc-sign-message))
3874 ;;;       mc-modes-alist))
3875   (when actions
3876     (setq message-send-actions actions))
3877   (setq message-reply-buffer replybuffer)
3878   (goto-char (point-min))
3879   ;; Insert all the headers.
3880   (mail-header-format
3881    (let ((h headers)
3882          (alist message-header-format-alist))
3883      (while h
3884        (unless (assq (caar h) message-header-format-alist)
3885          (push (list (caar h)) alist))
3886        (pop h))
3887      alist)
3888    headers)
3889   (delete-region (point) (progn (forward-line -1) (point)))
3890   (when message-default-headers
3891     (insert message-default-headers)
3892     (or (bolp) (insert ?\n)))
3893   (put-text-property
3894    (point)
3895    (progn
3896      (insert mail-header-separator "\n")
3897      (1- (point)))
3898    'read-only nil)
3899   (forward-line -1)
3900   (when (message-news-p)
3901     (when message-default-news-headers
3902       (insert message-default-news-headers)
3903       (or (bolp) (insert ?\n)))
3904     (when message-generate-headers-first
3905       (message-generate-headers
3906        (delq 'Lines
3907              (delq 'Subject
3908                    (copy-sequence message-required-news-headers))))))
3909   (when (message-mail-p)
3910     (when message-default-mail-headers
3911       (insert message-default-mail-headers)
3912       (or (bolp) (insert ?\n)))
3913     (when message-generate-headers-first
3914       (message-generate-headers
3915        (delq 'Lines
3916              (delq 'Subject
3917                    (copy-sequence message-required-mail-headers))))))
3918   (run-hooks 'message-signature-setup-hook)
3919   (message-insert-signature)
3920   (save-restriction
3921     (message-narrow-to-headers)
3922     (if message-alternative-emails
3923         (message-use-alternative-email-as-from))
3924     (run-hooks 'message-header-setup-hook))
3925   (set-buffer-modified-p nil)
3926   (setq buffer-undo-list nil)
3927   (run-hooks 'message-setup-hook)
3928   (message-position-point)
3929   (undo-boundary))
3930
3931 (defun message-set-auto-save-file-name ()
3932   "Associate the message buffer with a file in the drafts directory."
3933   (when message-auto-save-directory
3934     (unless (file-directory-p
3935              (directory-file-name message-auto-save-directory))
3936       (gnus-make-directory message-auto-save-directory))
3937     (if (gnus-alive-p)
3938         (setq message-draft-article
3939               (nndraft-request-associate-buffer "drafts"))
3940       (setq buffer-file-name (expand-file-name
3941                               (if (eq system-type 'windows-nt)
3942                                   "message"
3943                                 "*message*")
3944                               message-auto-save-directory))
3945       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3946     (clear-visited-file-modtime)
3947     (setq buffer-file-coding-system message-draft-coding-system)))
3948
3949 (defun message-disassociate-draft ()
3950   "Disassociate the message buffer from the drafts directory."
3951   (when message-draft-article
3952     (nndraft-request-expire-articles
3953      (list message-draft-article) "drafts" nil t)))
3954
3955 (defun message-insert-headers ()
3956   "Generate the headers for the article."
3957   (interactive)
3958   (save-excursion
3959     (save-restriction
3960       (message-narrow-to-headers)
3961       (when (message-news-p)
3962         (message-generate-headers
3963          (delq 'Lines
3964                (delq 'Subject
3965                      (copy-sequence message-required-news-headers)))))
3966       (when (message-mail-p)
3967         (message-generate-headers
3968          (delq 'Lines
3969                (delq 'Subject
3970                      (copy-sequence message-required-mail-headers))))))))
3971
3972 \f
3973
3974 ;;;
3975 ;;; Commands for interfacing with message
3976 ;;;
3977
3978 ;;;###autoload
3979 (defun message-mail (&optional to subject
3980                                other-headers continue switch-function
3981                                yank-action send-actions)
3982   "Start editing a mail message to be sent.
3983 OTHER-HEADERS is an alist of header/value pairs."
3984   (interactive)
3985   (let ((message-this-is-mail t) replybuffer)
3986     (unless (message-mail-user-agent)
3987       (message-pop-to-buffer (message-buffer-name "mail" to)))
3988     ;; FIXME: message-mail should do something if YANK-ACTION is not
3989     ;; insert-buffer.
3990     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
3991          (setq replybuffer (nth 1 yank-action)))
3992     (message-setup
3993      (nconc
3994       `((To . ,(or to "")) (Subject . ,(or subject "")))
3995       (when other-headers other-headers))
3996      replybuffer send-actions)
3997     ;; FIXME: Should return nil if failure.
3998     t))
3999
4000 ;;;###autoload
4001 (defun message-news (&optional newsgroups subject)
4002   "Start editing a news article to be sent."
4003   (interactive)
4004   (let ((message-this-is-news t))
4005     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
4006     (message-setup `((Newsgroups . ,(or newsgroups ""))
4007                      (Subject . ,(or subject ""))))))
4008
4009 (defun message-get-reply-headers (wide &optional to-address)
4010   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
4011     ;; Find all relevant headers we need.
4012     (setq from (message-fetch-field "from")
4013           to (message-fetch-field "to")
4014           cc (message-fetch-field "cc")
4015           mct (message-fetch-field "mail-copies-to")
4016           reply-to (message-fetch-field "reply-to")
4017           mrt (message-fetch-field "mail-reply-to")
4018           mft (and message-use-followup-to
4019                    (message-fetch-field "mail-followup-to")))
4020
4021     ;; Handle special values of Mail-Copies-To.
4022     (when mct
4023       (cond ((or (equal (downcase mct) "never")
4024                  (equal (downcase mct) "nobody"))
4025              (setq never-mct t)
4026              (setq mct nil))
4027             ((or (equal (downcase mct) "always")
4028                  (equal (downcase mct) "poster"))
4029              (setq mct (or mrt reply-to from)))))
4030
4031     (if (and (not mft)
4032              (or (not wide)
4033                  to-address))
4034         (progn
4035           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
4036           (when (and (and wide mct)
4037                      (not (member (cons 'To mct) follow-to)))
4038             (push (cons 'Cc mct) follow-to)))
4039       (let (ccalist)
4040         (save-excursion
4041           (message-set-work-buffer)
4042           (if (and mft
4043                    message-use-followup-to
4044                    wide
4045                    (or (not (eq message-use-followup-to 'ask))
4046                        (message-y-or-n-p
4047                         (concat "Obey Mail-Followup-To? ") t "\
4048 You should normally obey the Mail-Followup-To: header.  In this
4049 article, it has the value of
4050
4051 " mft "
4052
4053 which directs your response to " (if (string-match "," mft)
4054                                "the specified addresses"
4055                              "that address only") ".
4056
4057 If a message is posted to several mailing lists, Mail-Followup-To is
4058 often used to direct the following discussion to one list only,
4059 because discussions that are spread over several lists tend to be
4060 fragmented and very difficult to follow.
4061
4062 Also, some source/announcement lists are not intended for discussion;
4063 responses here are directed to other addresses.")))
4064               (insert mft)
4065             (unless never-mct
4066               (insert (or mrt reply-to from "")))
4067             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
4068             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
4069             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
4070           (goto-char (point-min))
4071           (while (re-search-forward "[ \t]+" nil t)
4072             (replace-match " " t t))
4073           ;; Remove addresses that match `rmail-dont-reply-to-names'.
4074           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
4075             (insert (prog1 (rmail-dont-reply-to (buffer-string))
4076                       (erase-buffer))))
4077           (goto-char (point-min))
4078           ;; Perhaps "Mail-Copies-To: never" removed the only address?
4079           (when (eobp)
4080             (insert (or mrt reply-to from "")))
4081           (setq ccalist
4082                 (mapcar
4083                  (lambda (addr)
4084                    (cons (mail-strip-quoted-names addr) addr))
4085                  (message-tokenize-header (buffer-string))))
4086           (let ((s ccalist))
4087             (while s
4088               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
4089         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
4090         (when ccalist
4091           (let ((ccs (cons 'Cc (mapconcat
4092                                 (lambda (addr) (cdr addr)) ccalist ", "))))
4093             (when (string-match "^ +" (cdr ccs))
4094               (setcdr ccs (substring (cdr ccs) (match-end 0))))
4095             (push ccs follow-to)))
4096         ;; Allow the user to be asked whether or not to reply to all
4097         ;; recipients in a wide reply.
4098         (if (and ccalist wide message-wide-reply-confirm-recipients
4099                  (not (y-or-n-p "Reply to all recipients?")))
4100             (setq follow-to (delq (assoc 'Cc follow-to) follow-to)))))
4101     follow-to))
4102
4103
4104 ;;;###autoload
4105 (defun message-reply (&optional to-address wide)
4106   "Start editing a reply to the article in the current buffer."
4107   (interactive)
4108   (require 'gnus-sum)                   ; for gnus-list-identifiers
4109   (let ((cur (current-buffer))
4110         from subject date reply-to to cc
4111         references message-id follow-to
4112         (inhibit-point-motion-hooks t)
4113         (message-this-is-mail t)
4114         gnus-warning)
4115     (save-restriction
4116       (message-narrow-to-head-1)
4117       ;; Allow customizations to have their say.
4118       (if (not wide)
4119           ;; This is a regular reply.
4120           (when (message-functionp message-reply-to-function)
4121             (save-excursion
4122               (setq follow-to (funcall message-reply-to-function))))
4123         ;; This is a followup.
4124         (when (message-functionp message-wide-reply-to-function)
4125           (save-excursion
4126             (setq follow-to
4127                   (funcall message-wide-reply-to-function)))))
4128       (setq message-id (message-fetch-field "message-id" t)
4129             references (message-fetch-field "references")
4130             date (message-fetch-field "date")
4131             from (message-fetch-field "from")
4132             subject (or (message-fetch-field "subject") "none"))
4133     (when gnus-list-identifiers
4134       (setq subject (message-strip-list-identifiers subject)))
4135     (setq subject (concat "Re: " (message-strip-subject-re subject)))
4136
4137     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4138                (string-match "<[^>]+>" gnus-warning))
4139       (setq message-id (match-string 0 gnus-warning)))
4140
4141     (unless follow-to
4142       (setq follow-to (message-get-reply-headers wide to-address))))
4143
4144     (unless (message-mail-user-agent)
4145       (message-pop-to-buffer
4146        (message-buffer-name
4147         (if wide "wide reply" "reply") from
4148         (if wide to-address nil))))
4149
4150     (setq message-reply-headers
4151           (vector 0 subject from date message-id references 0 0 ""))
4152
4153     (message-setup
4154      `((Subject . ,subject)
4155        ,@follow-to
4156        ,@(if (or references message-id)
4157              `((References . ,(concat (or references "") (and references " ")
4158                                       (or message-id ""))))
4159            nil))
4160      cur)))
4161
4162 ;;;###autoload
4163 (defun message-wide-reply (&optional to-address)
4164   "Make a \"wide\" reply to the message in the current buffer."
4165   (interactive)
4166   (message-reply to-address t))
4167
4168 ;;;###autoload
4169 (defun message-followup (&optional to-newsgroups)
4170   "Follow up to the message in the current buffer.
4171 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4172   (interactive)
4173   (require 'gnus-sum)                   ; for gnus-list-identifiers
4174   (let ((cur (current-buffer))
4175         from subject date reply-to mrt mct
4176         references message-id follow-to
4177         (inhibit-point-motion-hooks t)
4178         (message-this-is-news t)
4179         followup-to distribution newsgroups gnus-warning posted-to)
4180     (save-restriction
4181       (narrow-to-region
4182        (goto-char (point-min))
4183        (if (search-forward "\n\n" nil t)
4184            (1- (point))
4185          (point-max)))
4186       (when (message-functionp message-followup-to-function)
4187         (setq follow-to
4188               (funcall message-followup-to-function)))
4189       (setq from (message-fetch-field "from")
4190             date (message-fetch-field "date")
4191             subject (or (message-fetch-field "subject") "none")
4192             references (message-fetch-field "references")
4193             message-id (message-fetch-field "message-id" t)
4194             followup-to (message-fetch-field "followup-to")
4195             newsgroups (message-fetch-field "newsgroups")
4196             posted-to (message-fetch-field "posted-to")
4197             reply-to (message-fetch-field "reply-to")
4198             mrt (message-fetch-field "mail-reply-to")
4199             distribution (message-fetch-field "distribution")
4200             mct (message-fetch-field "mail-copies-to"))
4201       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4202                  (string-match "<[^>]+>" gnus-warning))
4203         (setq message-id (match-string 0 gnus-warning)))
4204       ;; Remove bogus distribution.
4205       (when (and (stringp distribution)
4206                  (let ((case-fold-search t))
4207                    (string-match "world" distribution)))
4208         (setq distribution nil))
4209       (if gnus-list-identifiers
4210           (setq subject (message-strip-list-identifiers subject)))
4211       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4212       (widen))
4213
4214     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4215
4216     (message-setup
4217      `((Subject . ,subject)
4218        ,@(cond
4219           (to-newsgroups
4220            (list (cons 'Newsgroups to-newsgroups)))
4221           (follow-to follow-to)
4222           ((and followup-to message-use-followup-to)
4223            (list
4224             (cond
4225              ((equal (downcase followup-to) "poster")
4226               (if (or (eq message-use-followup-to 'use)
4227                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4228 You should normally obey the Followup-To: header.
4229
4230 `Followup-To: poster' sends your response via e-mail instead of news.
4231
4232 A typical situation where `Followup-To: poster' is used is when the poster
4233 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4234                   (progn
4235                     (setq message-this-is-news nil)
4236                     (cons 'To (or mrt reply-to from "")))
4237                 (cons 'Newsgroups newsgroups)))
4238              (t
4239               (if (or (equal followup-to newsgroups)
4240                       (not (eq message-use-followup-to 'ask))
4241                       (message-y-or-n-p
4242                        (concat "Obey Followup-To: " followup-to "? ") t "\
4243 You should normally obey the Followup-To: header.
4244
4245         `Followup-To: " followup-to "'
4246 directs your response to " (if (string-match "," followup-to)
4247                                "the specified newsgroups"
4248                              "that newsgroup only") ".
4249
4250 If a message is posted to several newsgroups, Followup-To is often
4251 used to direct the following discussion to one newsgroup only,
4252 because discussions that are spread over several newsgroup tend to
4253 be fragmented and very difficult to follow.
4254
4255 Also, some source/announcement newsgroups are not intended for discussion;
4256 responses here are directed to other newsgroups."))
4257                   (cons 'Newsgroups followup-to)
4258                 (cons 'Newsgroups newsgroups))))))
4259           (posted-to
4260            `((Newsgroups . ,posted-to)))
4261           (t
4262            `((Newsgroups . ,newsgroups))))
4263        ,@(and distribution (list (cons 'Distribution distribution)))
4264        ,@(if (or references message-id)
4265              `((References . ,(concat (or references "") (and references " ")
4266                                       (or message-id "")))))
4267        ,@(when (and mct
4268                     (not (or (equal (downcase mct) "never")
4269                              (equal (downcase mct) "nobody"))))
4270            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4271                                    (equal (downcase mct) "poster"))
4272                                (or mrt reply-to from "")
4273                              mct)))))
4274
4275      cur)
4276
4277     (setq message-reply-headers
4278           (vector 0 subject from date message-id references 0 0 ""))))
4279
4280
4281 ;;;###autoload
4282 (defun message-cancel-news (&optional arg)
4283   "Cancel an article you posted.
4284 If ARG, allow editing of the cancellation message."
4285   (interactive "P")
4286   (unless (message-news-p)
4287     (error "This is not a news article; canceling is impossible"))
4288   (let (from newsgroups message-id distribution buf sender)
4289     (save-excursion
4290       ;; Get header info from original article.
4291       (save-restriction
4292         (message-narrow-to-head-1)
4293         (setq from (message-fetch-field "from")
4294               sender (message-fetch-field "sender")
4295               newsgroups (message-fetch-field "newsgroups")
4296               message-id (message-fetch-field "message-id" t)
4297               distribution (message-fetch-field "distribution")))
4298       ;; Make sure that this article was written by the user.
4299       (unless (or (message-gnksa-enable-p 'cancel-messages)
4300                   (and sender
4301                        (string-equal
4302                         (downcase sender)
4303                         (downcase (message-make-sender))))
4304                   (string-equal
4305                    (downcase (cadr (mail-extract-address-components from)))
4306                    (downcase (cadr (mail-extract-address-components
4307                                     (message-make-from))))))
4308         (error "This article is not yours"))
4309       (when (yes-or-no-p "Do you really want to cancel this article? ")
4310         ;; Make control message.
4311         (if arg
4312             (message-news)
4313           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4314         (erase-buffer)
4315         (insert "Newsgroups: " newsgroups "\n"
4316                 "From: " from "\n"
4317                 "Subject: cmsg cancel " message-id "\n"
4318                 "Control: cancel " message-id "\n"
4319                 (if distribution
4320                     (concat "Distribution: " distribution "\n")
4321                   "")
4322                 mail-header-separator "\n"
4323                 message-cancel-message)
4324         (run-hooks 'message-cancel-hook)
4325         (unless arg
4326           (message "Canceling your article...")
4327           (if (let ((message-syntax-checks
4328                      'dont-check-for-anything-just-trust-me))
4329                 (funcall message-send-news-function))
4330               (message "Canceling your article...done"))
4331           (kill-buffer buf))))))
4332
4333 ;;;###autoload
4334 (defun message-supersede ()
4335   "Start composing a message to supersede the current message.
4336 This is done simply by taking the old article and adding a Supersedes
4337 header line with the old Message-ID."
4338   (interactive)
4339   (let ((cur (current-buffer))
4340         (sender (message-fetch-field "sender"))
4341         (from (message-fetch-field "from")))
4342     ;; Check whether the user owns the article that is to be superseded.
4343     (unless (or (message-gnksa-enable-p 'cancel-messages)
4344                 (and sender
4345                      (string-equal
4346                       (downcase sender)
4347                       (downcase (message-make-sender))))
4348                 (string-equal
4349                  (downcase (cadr (mail-extract-address-components from)))
4350                  (downcase (cadr (mail-extract-address-components
4351                                   (message-make-from))))))
4352       (error "This article is not yours"))
4353     ;; Get a normal message buffer.
4354     (message-pop-to-buffer (message-buffer-name "supersede"))
4355     (insert-buffer-substring cur)
4356     (mime-to-mml)
4357     (message-narrow-to-head-1)
4358     ;; Remove unwanted headers.
4359     (when message-ignored-supersedes-headers
4360       (message-remove-header message-ignored-supersedes-headers t))
4361     (goto-char (point-min))
4362     (if (not (re-search-forward "^Message-ID: " nil t))
4363         (error "No Message-ID in this article")
4364       (replace-match "Supersedes: " t t))
4365     (goto-char (point-max))
4366     (insert mail-header-separator)
4367     (widen)
4368     (forward-line 1)))
4369
4370 ;;;###autoload
4371 (defun message-recover ()
4372   "Reread contents of current buffer from its last auto-save file."
4373   (interactive)
4374   (let ((file-name (make-auto-save-file-name)))
4375     (cond ((save-window-excursion
4376              (if (not (eq system-type 'vax-vms))
4377                  (with-output-to-temp-buffer "*Directory*"
4378                    (with-current-buffer standard-output
4379                      (fundamental-mode)) ; for Emacs 20.4+
4380                    (buffer-disable-undo standard-output)
4381                    (let ((default-directory "/"))
4382                      (call-process
4383                       "ls" nil standard-output nil "-l" file-name))))
4384              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4385            (let ((buffer-read-only nil))
4386              (erase-buffer)
4387              (insert-file-contents file-name nil)))
4388           (t (error "message-recover cancelled")))))
4389
4390 ;;; Washing Subject:
4391
4392 (defun message-wash-subject (subject)
4393   "Remove junk like \"Re:\", \"(fwd)\", etc. added to subject string SUBJECT.
4394 Previous forwarders, replyers, etc. may add it."
4395   (with-temp-buffer
4396     (insert-string subject)
4397     (goto-char (point-min))
4398     ;; strip Re/Fwd stuff off the beginning
4399     (while (re-search-forward
4400             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4401       (replace-match ""))
4402
4403     ;; and gnus-style forwards [foo@bar.com] subject
4404     (goto-char (point-min))
4405     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4406       (replace-match ""))
4407
4408     ;; and off the end
4409     (goto-char (point-max))
4410     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4411       (replace-match ""))
4412
4413     ;; and finally, any whitespace that was left-over
4414     (goto-char (point-min))
4415     (while (re-search-forward "^[ \t]+" nil t)
4416       (replace-match ""))
4417     (goto-char (point-max))
4418     (while (re-search-backward "[ \t]+$" nil t)
4419       (replace-match ""))
4420
4421     (buffer-string)))
4422
4423 ;;; Forwarding messages.
4424
4425 (defvar message-forward-decoded-p nil
4426   "Non-nil means the original message is decoded.")
4427
4428 (defun message-forward-subject-author-subject (subject)
4429   "Generate a SUBJECT for a forwarded message.
4430 The form is: [Source] Subject, where if the original message was mail,
4431 Source is the sender, and if the original message was news, Source is
4432 the list of newsgroups is was posted to."
4433   (concat "["
4434            (let ((prefix
4435                   (or (message-fetch-field
4436                        (if (message-news-p) "newsgroups" "from"))
4437                       "(nowhere)")))
4438              (if message-forward-decoded-p
4439                  prefix
4440                (mail-decode-encoded-word-string prefix)))
4441           "] " subject))
4442
4443 (defun message-forward-subject-fwd (subject)
4444   "Generate a SUBJECT for a forwarded message.
4445 The form is: Fwd: Subject, where Subject is the original subject of
4446 the message."
4447   (concat "Fwd: " subject))
4448
4449 (defun message-make-forward-subject ()
4450   "Return a Subject header suitable for the message in the current buffer."
4451   (save-excursion
4452     (save-restriction
4453       (message-narrow-to-head-1)
4454       (let ((funcs message-make-forward-subject-function)
4455             (subject (message-fetch-field "Subject")))
4456         (setq subject
4457               (if subject
4458                   (if message-forward-decoded-p
4459                       subject
4460                     (mail-decode-encoded-word-string subject))
4461                 ""))
4462         (if message-wash-forwarded-subjects
4463             (setq subject (message-wash-subject subject)))
4464         ;; Make sure funcs is a list.
4465         (and funcs
4466              (not (listp funcs))
4467              (setq funcs (list funcs)))
4468         ;; Apply funcs in order, passing subject generated by previous
4469         ;; func to the next one.
4470         (while funcs
4471           (when (message-functionp (car funcs))
4472             (setq subject (funcall (car funcs) subject)))
4473           (setq funcs (cdr funcs)))
4474         subject))))
4475
4476 (eval-when-compile
4477   (defvar gnus-article-decoded-p))
4478
4479 ;;;###autoload
4480 (defun message-forward (&optional news digest)
4481   "Forward the current message via mail.
4482 Optional NEWS will use news to forward instead of mail.
4483 Optional DIGEST will use digest to forward."
4484   (interactive "P")
4485   (let* ((cur (current-buffer))
4486          (message-forward-decoded-p
4487           (if (local-variable-p 'gnus-article-decoded-p (current-buffer))
4488               gnus-article-decoded-p  ;; In an article buffer.
4489             message-forward-decoded-p))
4490          (subject (message-make-forward-subject))
4491          art-beg)
4492     (if news
4493         (message-news nil subject)
4494       (message-mail nil subject))
4495     ;; Put point where we want it before inserting the forwarded
4496     ;; message.
4497     (if message-forward-before-signature
4498         (message-goto-body)
4499       (goto-char (point-max)))
4500     (if message-forward-as-mime
4501         (if digest
4502             (insert "\n<#multipart type=digest>\n")
4503           (if message-forward-show-mml
4504               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4505             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4506       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4507     (let ((b (point)) e)
4508       (if digest
4509           (if message-forward-as-mime
4510               (insert-buffer-substring cur)
4511             (mml-insert-buffer cur))
4512         (if (and message-forward-show-mml
4513                  (not message-forward-decoded-p))
4514             (insert
4515              (with-temp-buffer
4516                (mm-disable-multibyte-mule4) ;; Must copy buffer in unibyte mode
4517                (insert
4518                 (with-current-buffer cur
4519                   (mm-string-as-unibyte (buffer-string))))
4520                (mm-enable-multibyte-mule4)
4521                (mime-to-mml)
4522                (goto-char (point-min))
4523                (when (looking-at "From ")
4524                  (replace-match "X-From-Line: "))
4525                (buffer-string)))
4526           (save-restriction
4527             (narrow-to-region (point) (point))
4528             (mml-insert-buffer cur)
4529             (goto-char (point-min))
4530             (when (looking-at "From ")
4531               (replace-match "X-From-Line: "))
4532             (goto-char (point-max)))))
4533       (setq e (point))
4534       (if message-forward-as-mime
4535           (if digest
4536               (insert "<#/multipart>\n")
4537             (if message-forward-show-mml
4538                 (insert "<#/mml>\n")
4539               (insert "<#/part>\n")))
4540         (insert "\n-------------------- End of forwarded message --------------------\n"))
4541       (if (and digest message-forward-as-mime)
4542           (save-restriction
4543             (narrow-to-region b e)
4544             (goto-char b)
4545             (narrow-to-region (point)
4546                               (or (search-forward "\n\n" nil t) (point)))
4547             (delete-region (point-min) (point-max)))
4548         (when (and (not current-prefix-arg)
4549                    message-forward-ignored-headers)
4550           (save-restriction
4551             (narrow-to-region b e)
4552             (goto-char b)
4553             (narrow-to-region (point)
4554                               (or (search-forward "\n\n" nil t) (point)))
4555             (message-remove-header message-forward-ignored-headers t)))))
4556     (message-position-point)))
4557
4558 ;;;###autoload
4559 (defun message-resend (address)
4560   "Resend the current article to ADDRESS."
4561   (interactive
4562    (list (message-read-from-minibuffer "Resend message to: ")))
4563   (message "Resending message to %s..." address)
4564   (save-excursion
4565     (let ((cur (current-buffer))
4566           beg)
4567       ;; We first set up a normal mail buffer.
4568       (unless (message-mail-user-agent)
4569         (set-buffer (get-buffer-create " *message resend*"))
4570         (erase-buffer))
4571       (let ((message-this-is-mail t))
4572         (message-setup `((To . ,address))))
4573       ;; Insert our usual headers.
4574       (message-generate-headers '(From Date To))
4575       (message-narrow-to-headers)
4576       ;; Rename them all to "Resent-*".
4577       (while (re-search-forward "^[A-Za-z]" nil t)
4578         (forward-char -1)
4579         (insert "Resent-"))
4580       (widen)
4581       (forward-line)
4582       (delete-region (point) (point-max))
4583       (setq beg (point))
4584       ;; Insert the message to be resent.
4585       (insert-buffer-substring cur)
4586       (goto-char (point-min))
4587       (search-forward "\n\n")
4588       (forward-char -1)
4589       (save-restriction
4590         (narrow-to-region beg (point))
4591         (message-remove-header message-ignored-resent-headers t)
4592         (goto-char (point-max)))
4593       (insert mail-header-separator)
4594       ;; Rename all old ("Also-")Resent headers.
4595       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4596         (beginning-of-line)
4597         (insert "Also-"))
4598       ;; Quote any "From " lines at the beginning.
4599       (goto-char beg)
4600       (when (looking-at "From ")
4601         (replace-match "X-From-Line: "))
4602       ;; Send it.
4603       (let ((message-inhibit-body-encoding t)
4604             message-required-mail-headers)
4605         (message-send-mail))
4606       (kill-buffer (current-buffer)))
4607     (message "Resending message to %s...done" address)))
4608
4609 ;;;###autoload
4610 (defun message-bounce ()
4611   "Re-mail the current message.
4612 This only makes sense if the current message is a bounce message that
4613 contains some mail you have written which has been bounced back to
4614 you."
4615   (interactive)
4616   (let ((handles (mm-dissect-buffer t))
4617         boundary)
4618     (message-pop-to-buffer (message-buffer-name "bounce"))
4619     (if (stringp (car handles))
4620         ;; This is a MIME bounce.
4621         (mm-insert-part (car (last handles)))
4622       ;; This is a non-MIME bounce, so we try to remove things
4623       ;; manually.
4624       (mm-insert-part handles)
4625       (undo-boundary)
4626       (goto-char (point-min))
4627       (search-forward "\n\n" nil t)
4628       (or (and (re-search-forward message-unsent-separator nil t)
4629                (forward-line 1))
4630           (re-search-forward "^Return-Path:.*\n" nil t))
4631       ;; We remove everything before the bounced mail.
4632       (delete-region
4633        (point-min)
4634        (if (re-search-forward "^[^ \n\t]+:" nil t)
4635            (match-beginning 0)
4636          (point))))
4637     (mm-enable-multibyte)
4638     (mime-to-mml)
4639     (save-restriction
4640       (message-narrow-to-head-1)
4641       (message-remove-header message-ignored-bounced-headers t)
4642       (goto-char (point-max))
4643       (insert mail-header-separator))
4644     (message-position-point)))
4645
4646 ;;;
4647 ;;; Interactive entry points for new message buffers.
4648 ;;;
4649
4650 ;;;###autoload
4651 (defun message-mail-other-window (&optional to subject)
4652   "Like `message-mail' command, but display mail buffer in another window."
4653   (interactive)
4654   (unless (message-mail-user-agent)
4655     (let ((pop-up-windows t)
4656           (special-display-buffer-names nil)
4657           (special-display-regexps nil)
4658           (same-window-buffer-names nil)
4659           (same-window-regexps nil))
4660       (message-pop-to-buffer (message-buffer-name "mail" to))))
4661   (let ((message-this-is-mail t))
4662     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4663                    nil nil 'switch-to-buffer-other-window)))
4664
4665 ;;;###autoload
4666 (defun message-mail-other-frame (&optional to subject)
4667   "Like `message-mail' command, but display mail buffer in another frame."
4668   (interactive)
4669   (unless (message-mail-user-agent)
4670     (let ((pop-up-frames t)
4671           (special-display-buffer-names nil)
4672           (special-display-regexps nil)
4673           (same-window-buffer-names nil)
4674           (same-window-regexps nil))
4675       (message-pop-to-buffer (message-buffer-name "mail" to))))
4676   (let ((message-this-is-mail t))
4677     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4678                    nil nil 'switch-to-buffer-other-frame)))
4679
4680 ;;;###autoload
4681 (defun message-news-other-window (&optional newsgroups subject)
4682   "Start editing a news article to be sent."
4683   (interactive)
4684   (let ((pop-up-windows t)
4685         (special-display-buffer-names nil)
4686         (special-display-regexps nil)
4687         (same-window-buffer-names nil)
4688         (same-window-regexps nil))
4689     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4690   (let ((message-this-is-news t))
4691     (message-setup `((Newsgroups . ,(or newsgroups ""))
4692                      (Subject . ,(or subject ""))))))
4693
4694 ;;;###autoload
4695 (defun message-news-other-frame (&optional newsgroups subject)
4696   "Start editing a news article to be sent."
4697   (interactive)
4698   (let ((pop-up-frames t)
4699         (special-display-buffer-names nil)
4700         (special-display-regexps nil)
4701         (same-window-buffer-names nil)
4702         (same-window-regexps nil))
4703     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4704   (let ((message-this-is-news t))
4705     (message-setup `((Newsgroups . ,(or newsgroups ""))
4706                      (Subject . ,(or subject ""))))))
4707
4708 ;;; underline.el
4709
4710 ;; This code should be moved to underline.el (from which it is stolen).
4711
4712 ;;;###autoload
4713 (defun bold-region (start end)
4714   "Bold all nonblank characters in the region.
4715 Works by overstriking characters.
4716 Called from program, takes two arguments START and END
4717 which specify the range to operate on."
4718   (interactive "r")
4719   (save-excursion
4720     (let ((end1 (make-marker)))
4721       (move-marker end1 (max start end))
4722       (goto-char (min start end))
4723       (while (< (point) end1)
4724         (or (looking-at "[_\^@- ]")
4725             (insert (char-after) "\b"))
4726         (forward-char 1)))))
4727
4728 ;;;###autoload
4729 (defun unbold-region (start end)
4730   "Remove all boldness (overstruck characters) in the region.
4731 Called from program, takes two arguments START and END
4732 which specify the range to operate on."
4733   (interactive "r")
4734   (save-excursion
4735     (let ((end1 (make-marker)))
4736       (move-marker end1 (max start end))
4737       (goto-char (min start end))
4738       (while (re-search-forward "\b" end1 t)
4739         (if (eq (char-after) (char-after (- (point) 2)))
4740             (delete-char -2))))))
4741
4742 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4743
4744 ;; Support for toolbar
4745 (eval-when-compile
4746   (defvar tool-bar-map)
4747   (defvar tool-bar-mode))
4748
4749 (defun message-tool-bar-map ()
4750   (or message-tool-bar-map
4751       (setq message-tool-bar-map
4752             (and (fboundp 'tool-bar-add-item-from-menu)
4753                  tool-bar-mode
4754                  (let ((tool-bar-map (copy-keymap tool-bar-map))
4755                        (load-path (mm-image-load-path)))
4756                    ;; Zap some items which aren't so relevant and take
4757                    ;; up space.
4758                    (dolist (key '(print-buffer kill-buffer save-buffer
4759                                                write-file dired open-file))
4760                      (define-key tool-bar-map (vector key) nil))
4761                    (tool-bar-add-item-from-menu
4762                     'message-send-and-exit "mail_send" message-mode-map)
4763                    (tool-bar-add-item-from-menu
4764                     'message-kill-buffer "close" message-mode-map)
4765                    (tool-bar-add-item-from-menu
4766                     'message-dont-send "cancel" message-mode-map)
4767                    (tool-bar-add-item-from-menu
4768                     'mml-attach-file "attach" message-mode-map)
4769                    (tool-bar-add-item-from-menu
4770                     'ispell-message "spell" message-mode-map)
4771                    tool-bar-map)))))
4772
4773 ;;; Group name completion.
4774
4775 (defvar message-newgroups-header-regexp
4776   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4777   "Regexp that match headers that lists groups.")
4778
4779 (defun message-tab ()
4780   "Expand group names in Newsgroups and Followup-To headers.
4781 Do a `tab-to-tab-stop' if not in those headers."
4782   (interactive)
4783   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4784         (mail-abbrev-in-expansion-header-p))
4785       (message-expand-group)
4786     (tab-to-tab-stop)))
4787
4788 (defun message-expand-group ()
4789   "Expand the group name under point."
4790   (let* ((b (save-excursion
4791               (save-restriction
4792                 (narrow-to-region
4793                  (save-excursion
4794                    (beginning-of-line)
4795                    (skip-chars-forward "^:")
4796                    (1+ (point)))
4797                  (point))
4798                 (skip-chars-backward "^, \t\n") (point))))
4799          (completion-ignore-case t)
4800          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4801                                             (point))))
4802          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4803          (completions (all-completions string hashtb))
4804          comp)
4805     (delete-region b (point))
4806     (cond
4807      ((= (length completions) 1)
4808       (if (string= (car completions) string)
4809           (progn
4810             (insert string)
4811             (message "Only matching group"))
4812         (insert (car completions))))
4813      ((and (setq comp (try-completion string hashtb))
4814            (not (string= comp string)))
4815       (insert comp))
4816      (t
4817       (insert string)
4818       (if (not comp)
4819           (message "No matching groups")
4820         (save-selected-window
4821           (pop-to-buffer "*Completions*")
4822           (buffer-disable-undo)
4823           (let ((buffer-read-only nil))
4824             (erase-buffer)
4825             (let ((standard-output (current-buffer)))
4826               (display-completion-list (sort completions 'string<)))
4827             (goto-char (point-min))
4828             (delete-region (point) (progn (forward-line 3) (point))))))))))
4829
4830 ;;; Help stuff.
4831
4832 (defun message-talkative-question (ask question show &rest text)
4833   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4834 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4835 The following arguments may contain lists of values."
4836   (if (and show
4837            (setq text (message-flatten-list text)))
4838       (save-window-excursion
4839         (save-excursion
4840           (with-output-to-temp-buffer " *MESSAGE information message*"
4841             (set-buffer " *MESSAGE information message*")
4842             (fundamental-mode)          ; for Emacs 20.4+
4843             (mapcar 'princ text)
4844             (goto-char (point-min))))
4845         (funcall ask question))
4846     (funcall ask question)))
4847
4848 (defun message-flatten-list (list)
4849   "Return a new, flat list that contains all elements of LIST.
4850
4851 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4852 => (1 2 3 4 5 6 7)"
4853   (cond ((consp list)
4854          (apply 'append (mapcar 'message-flatten-list list)))
4855         (list
4856          (list list))))
4857
4858 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4859   "Create and return a buffer with name based on NAME using `generate-new-buffer.'
4860 Then clone the local variables and values from the old buffer to the
4861 new one, cloning only the locals having a substring matching the
4862 regexp varstr."
4863   (let ((oldbuf (current-buffer)))
4864     (save-excursion
4865       (set-buffer (generate-new-buffer name))
4866       (message-clone-locals oldbuf varstr)
4867       (current-buffer))))
4868
4869 (defun message-clone-locals (buffer &optional varstr)
4870   "Clone the local variables from BUFFER to the current buffer."
4871   (let ((locals (save-excursion
4872                   (set-buffer buffer)
4873                   (buffer-local-variables)))
4874         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4875     (mapcar
4876      (lambda (local)
4877        (when (and (consp local)
4878                   (car local)
4879                   (string-match regexp (symbol-name (car local)))
4880                   (or (null varstr)
4881                       (string-match varstr (symbol-name (car local)))))
4882          (ignore-errors
4883            (set (make-local-variable (car local))
4884                 (cdr local)))))
4885      locals)))
4886
4887 ;;; Miscellaneous functions
4888
4889 (defsubst message-replace-chars-in-string (string from to)
4890   (mm-subst-char-in-string from to string))
4891
4892 ;;;
4893 ;;; MIME functions
4894 ;;;
4895
4896 (defvar message-inhibit-body-encoding nil)
4897
4898 (defun message-encode-message-body ()
4899   (unless message-inhibit-body-encoding
4900     (let ((mail-parse-charset (or mail-parse-charset
4901                                   message-default-charset))
4902           (case-fold-search t)
4903           lines content-type-p)
4904       (message-goto-body)
4905       (save-restriction
4906         (narrow-to-region (point) (point-max))
4907         (let ((new (mml-generate-mime)))
4908           (when new
4909             (delete-region (point-min) (point-max))
4910             (insert new)
4911             (goto-char (point-min))
4912             (if (eq (aref new 0) ?\n)
4913                 (delete-char 1)
4914               (search-forward "\n\n")
4915               (setq lines (buffer-substring (point-min) (1- (point))))
4916               (delete-region (point-min) (point))))))
4917       (save-restriction
4918         (message-narrow-to-headers-or-head)
4919         (message-remove-header "Mime-Version")
4920         (goto-char (point-max))
4921         (insert "MIME-Version: 1.0\n")
4922         (when lines
4923           (insert lines))
4924         (setq content-type-p
4925               (or mml-boundary
4926                   (re-search-backward "^Content-Type:" nil t))))
4927       (save-restriction
4928         (message-narrow-to-headers-or-head)
4929         (message-remove-first-header "Content-Type")
4930         (message-remove-first-header "Content-Transfer-Encoding"))
4931       ;; We always make sure that the message has a Content-Type header.
4932       ;; This is because some broken MTAs and MUAs get awfully confused
4933       ;; when confronted with a message with a MIME-Version header and
4934       ;; without a Content-Type header.  For instance, Solaris'
4935       ;; /usr/bin/mail.
4936       (unless content-type-p
4937         (goto-char (point-min))
4938         (re-search-forward "^MIME-Version:")
4939         (forward-line 1)
4940         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4941
4942 (defun message-read-from-minibuffer (prompt)
4943   "Read from the minibuffer while providing abbrev expansion."
4944   (if (fboundp 'mail-abbrevs-setup)
4945       (let ((mail-abbrev-mode-regexp "")
4946             (minibuffer-setup-hook 'mail-abbrevs-setup)
4947             (minibuffer-local-map message-minibuffer-local-map))
4948         (read-from-minibuffer prompt))
4949     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook)
4950           (minibuffer-local-map message-minibuffer-local-map))
4951       (read-string prompt))))
4952
4953 (defun message-use-alternative-email-as-from ()
4954   (require 'mail-utils)
4955   (let* ((fields '("To" "Cc"))
4956          (emails
4957           (split-string
4958            (mail-strip-quoted-names
4959             (mapconcat 'message-fetch-reply-field fields ","))
4960            "[ \f\t\n\r\v,]+"))
4961          email)
4962     (while emails
4963       (if (string-match message-alternative-emails (car emails))
4964           (setq email (car emails)
4965                 emails nil))
4966       (pop emails))
4967     (unless (or (not email) (equal email user-mail-address))
4968       (goto-char (point-max))
4969       (insert "From: " email "\n"))))
4970
4971 (defun message-options-get (symbol)
4972   (cdr (assq symbol message-options)))
4973
4974 (defun message-options-set (symbol value)
4975   (let ((the-cons (assq symbol message-options)))
4976     (if the-cons
4977         (if value
4978             (setcdr the-cons value)
4979           (setq message-options (delq the-cons message-options)))
4980       (and value
4981            (push (cons symbol value) message-options))))
4982   value)
4983
4984 (defun message-options-set-recipient ()
4985   (save-restriction
4986     (message-narrow-to-headers-or-head)
4987     (message-options-set 'message-sender
4988                          (mail-strip-quoted-names
4989                           (message-fetch-field "from")))
4990     (message-options-set 'message-recipients
4991                          (mail-strip-quoted-names
4992                           (let ((to (message-fetch-field "to"))
4993                                 (cc (message-fetch-field "cc"))
4994                                 (bcc (message-fetch-field "bcc")))
4995                             (concat
4996                              (or to "")
4997                              (if (and to cc) ", ")
4998                              (or cc "")
4999                              (if (and (or to cc) bcc) ", ")
5000                              (or bcc "")))))))
5001
5002 (when (featurep 'xemacs)
5003   (require 'messagexmas)
5004   (message-xmas-redefine))
5005
5006 (provide 'message)
5007
5008 (run-hooks 'message-load-hook)
5009
5010 ;; Local Variables:
5011 ;; coding: iso-8859-1
5012 ;; End:
5013
5014 ;;; message.el ends here