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