Importing Gnus v5.8.6.
[elisp/gnus.git-] / 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 'rmail-output "rmail"))
1016
1017 \f
1018
1019 ;;;
1020 ;;; Utility functions.
1021 ;;;
1022
1023 (defmacro message-y-or-n-p (question show &rest text)
1024   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1025   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1026
1027 ;; Delete the current line (and the next N lines.);
1028 (defmacro message-delete-line (&optional n)
1029   `(delete-region (progn (beginning-of-line) (point))
1030                   (progn (forward-line ,(or n 1)) (point))))
1031
1032 (defun message-tokenize-header (header &optional separator)
1033   "Split HEADER into a list of header elements.
1034 \",\" is used as the separator."
1035   (if (not header)
1036       nil
1037     (let ((regexp (format "[%s]+" (or separator ",")))
1038           (beg 1)
1039           (first t)
1040           quoted elems paren)
1041       (save-excursion
1042         (message-set-work-buffer)
1043         (insert header)
1044         (goto-char (point-min))
1045         (while (not (eobp))
1046           (if first
1047               (setq first nil)
1048             (forward-char 1))
1049           (cond ((and (> (point) beg)
1050                       (or (eobp)
1051                           (and (looking-at regexp)
1052                                (not quoted)
1053                                (not paren))))
1054                  (push (buffer-substring beg (point)) elems)
1055                  (setq beg (match-end 0)))
1056                 ((eq (char-after) ?\")
1057                  (setq quoted (not quoted)))
1058                 ((and (eq (char-after) ?\()
1059                       (not quoted))
1060                  (setq paren t))
1061                 ((and (eq (char-after) ?\))
1062                       (not quoted))
1063                  (setq paren nil))))
1064         (nreverse elems)))))
1065
1066 (defun message-mail-file-mbox-p (file)
1067   "Say whether FILE looks like a Unix mbox file."
1068   (when (and (file-exists-p file)
1069              (file-readable-p file)
1070              (file-regular-p file))
1071     (with-temp-buffer
1072       (nnheader-insert-file-contents file)
1073       (goto-char (point-min))
1074       (looking-at message-unix-mail-delimiter))))
1075
1076 (defun message-fetch-field (header &optional not-all)
1077   "The same as `mail-fetch-field', only remove all newlines."
1078   (let* ((inhibit-point-motion-hooks t)
1079          (case-fold-search t)
1080          (value (mail-fetch-field header nil (not not-all))))
1081     (when value
1082       (while (string-match "\n[\t ]+" value)
1083         (setq value (replace-match " " t t value)))
1084       ;; We remove all text props.
1085       (format "%s" value))))
1086
1087 (defun message-narrow-to-field ()
1088   "Narrow the buffer to the header on the current line."
1089   (beginning-of-line)
1090   (narrow-to-region
1091    (point)
1092    (progn
1093      (forward-line 1)
1094      (if (re-search-forward "^[^ \n\t]" nil t)
1095          (progn
1096            (beginning-of-line)
1097            (point))
1098        (point-max))))
1099   (goto-char (point-min)))
1100
1101 (defun message-add-header (&rest headers)
1102   "Add the HEADERS to the message header, skipping those already present."
1103   (while headers
1104     (let (hclean)
1105       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1106         (error "Invalid header `%s'" (car headers)))
1107       (setq hclean (match-string 1 (car headers)))
1108       (save-restriction
1109         (message-narrow-to-headers)
1110         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1111           (insert (car headers) ?\n))))
1112     (setq headers (cdr headers))))
1113
1114
1115 (defun message-fetch-reply-field (header)
1116   "Fetch FIELD from the message we're replying to."
1117   (when (and message-reply-buffer
1118              (buffer-name message-reply-buffer))
1119     (save-excursion
1120       (set-buffer message-reply-buffer)
1121       (message-fetch-field header))))
1122
1123 (defun message-set-work-buffer ()
1124   (if (get-buffer " *message work*")
1125       (progn
1126         (set-buffer " *message work*")
1127         (erase-buffer))
1128     (set-buffer (get-buffer-create " *message work*"))
1129     (kill-all-local-variables)
1130     (mm-enable-multibyte)))
1131
1132 (defun message-functionp (form)
1133   "Return non-nil if FORM is funcallable."
1134   (or (and (symbolp form) (fboundp form))
1135       (and (listp form) (eq (car form) 'lambda))
1136       (byte-code-function-p form)))
1137
1138 (defun message-strip-subject-re (subject)
1139   "Remove \"Re:\" from subject lines."
1140   (if (string-match message-subject-re-regexp subject)
1141       (substring subject (match-end 0))
1142     subject))
1143
1144 (defun message-remove-header (header &optional is-regexp first reverse)
1145   "Remove HEADER in the narrowed buffer.
1146 If REGEXP, HEADER is a regular expression.
1147 If FIRST, only remove the first instance of the header.
1148 Return the number of headers removed."
1149   (goto-char (point-min))
1150   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1151         (number 0)
1152         (case-fold-search t)
1153         last)
1154     (while (and (not (eobp))
1155                 (not last))
1156       (if (if reverse
1157               (not (looking-at regexp))
1158             (looking-at regexp))
1159           (progn
1160             (incf number)
1161             (when first
1162               (setq last t))
1163             (delete-region
1164              (point)
1165              ;; There might be a continuation header, so we have to search
1166              ;; until we find a new non-continuation line.
1167              (progn
1168                (forward-line 1)
1169                (if (re-search-forward "^[^ \t]" nil t)
1170                    (goto-char (match-beginning 0))
1171                  (point-max)))))
1172         (forward-line 1)
1173         (if (re-search-forward "^[^ \t]" nil t)
1174             (goto-char (match-beginning 0))
1175           (goto-char (point-max)))))
1176     number))
1177
1178 (defun message-remove-first-header (header)
1179   "Remove the first instance of HEADER if there is more than one."
1180   (let ((count 0)
1181         (regexp (concat "^" (regexp-quote header) ":")))
1182     (save-excursion
1183       (goto-char (point-min))
1184       (while (re-search-forward regexp nil t)
1185         (incf count)))
1186     (while (> count 1)
1187       (message-remove-header header nil t)
1188       (decf count))))
1189
1190 (defun message-narrow-to-headers ()
1191   "Narrow the buffer to the head of the message."
1192   (widen)
1193   (narrow-to-region
1194    (goto-char (point-min))
1195    (if (re-search-forward
1196         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1197        (match-beginning 0)
1198      (point-max)))
1199   (goto-char (point-min)))
1200
1201 (defun message-narrow-to-head ()
1202   "Narrow the buffer to the head of the message.
1203 Point is left at the beginning of the narrowed-to region."
1204   (widen)
1205   (narrow-to-region
1206    (goto-char (point-min))
1207    (if (search-forward "\n\n" nil 1)
1208        (1- (point))
1209      (point-max)))
1210   (goto-char (point-min)))
1211
1212 (defun message-narrow-to-headers-or-head ()
1213   "Narrow the buffer to the head of the message."
1214   (widen)
1215   (narrow-to-region
1216    (goto-char (point-min))
1217    (cond
1218     ((re-search-forward
1219       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1220      (match-beginning 0))
1221     ((search-forward "\n\n" nil t)
1222      (1- (point)))
1223     (t
1224      (point-max))))
1225   (goto-char (point-min)))
1226
1227 (defun message-news-p ()
1228   "Say whether the current buffer contains a news message."
1229   (and (not message-this-is-mail)
1230        (or message-this-is-news
1231            (save-excursion
1232              (save-restriction
1233                (message-narrow-to-headers)
1234                (and (message-fetch-field "newsgroups")
1235                     (not (message-fetch-field "posted-to"))))))))
1236
1237 (defun message-mail-p ()
1238   "Say whether the current buffer contains a mail message."
1239   (and (not message-this-is-news)
1240        (or message-this-is-mail
1241            (save-excursion
1242              (save-restriction
1243                (message-narrow-to-headers)
1244                (or (message-fetch-field "to")
1245                    (message-fetch-field "cc")
1246                    (message-fetch-field "bcc")))))))
1247
1248 (defun message-next-header ()
1249   "Go to the beginning of the next header."
1250   (beginning-of-line)
1251   (or (eobp) (forward-char 1))
1252   (not (if (re-search-forward "^[^ \t]" nil t)
1253            (beginning-of-line)
1254          (goto-char (point-max)))))
1255
1256 (defun message-sort-headers-1 ()
1257   "Sort the buffer as headers using `message-rank' text props."
1258   (goto-char (point-min))
1259   (require 'sort)
1260   (sort-subr
1261    nil 'message-next-header
1262    (lambda ()
1263      (message-next-header)
1264      (unless (bobp)
1265        (forward-char -1)))
1266    (lambda ()
1267      (or (get-text-property (point) 'message-rank)
1268          10000))))
1269
1270 (defun message-sort-headers ()
1271   "Sort the headers of the current message according to `message-header-format-alist'."
1272   (interactive)
1273   (save-excursion
1274     (save-restriction
1275       (let ((max (1+ (length message-header-format-alist)))
1276             rank)
1277         (message-narrow-to-headers)
1278         (while (re-search-forward "^[^ \n]+:" nil t)
1279           (put-text-property
1280            (match-beginning 0) (1+ (match-beginning 0))
1281            'message-rank
1282            (if (setq rank (length (memq (assq (intern (buffer-substring
1283                                                        (match-beginning 0)
1284                                                        (1- (match-end 0))))
1285                                               message-header-format-alist)
1286                                         message-header-format-alist)))
1287                (- max rank)
1288              (1+ max)))))
1289       (message-sort-headers-1))))
1290
1291 \f
1292
1293 ;;;
1294 ;;; Message mode
1295 ;;;
1296
1297 ;;; Set up keymap.
1298
1299 (defvar message-mode-map nil)
1300
1301 (unless message-mode-map
1302   (setq message-mode-map (make-keymap))
1303   (set-keymap-parent message-mode-map text-mode-map)
1304   (define-key message-mode-map "\C-c?" 'describe-mode)
1305
1306   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1307   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1308   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1309   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1310   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1311   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1312   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1313   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1314   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1315   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1316   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1317   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1318   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1319
1320   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1321   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1322
1323   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1324   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1325   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1326   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1327   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1328   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1329   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1330   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1331
1332   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1333   (define-key message-mode-map "\C-c\C-s" 'message-send)
1334   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1335   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1336
1337   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1338   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1339   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1340   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1341
1342   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1343
1344   (define-key message-mode-map "\t" 'message-tab))
1345
1346 (easy-menu-define
1347  message-mode-menu message-mode-map "Message Menu."
1348  '("Message"
1349    ["Sort Headers" message-sort-headers t]
1350    ["Yank Original" message-yank-original t]
1351    ["Fill Yanked Message" message-fill-yanked-message t]
1352    ["Insert Signature" message-insert-signature t]
1353    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1354    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1355    ["Elide Region" message-elide-region (mark t)]
1356    ["Delete Outside Region" message-delete-not-region (mark t)]
1357    ["Kill To Signature" message-kill-to-signature t]
1358    ["Newline and Reformat" message-newline-and-reformat t]
1359    ["Rename buffer" message-rename-buffer t]
1360    ["Spellcheck" ispell-message t]
1361    ["Attach file as MIME" mml-attach-file t]
1362    "----"
1363    ["Send Message" message-send-and-exit t]
1364    ["Abort Message" message-dont-send t]
1365    ["Kill Message" message-kill-buffer t]))
1366
1367 (easy-menu-define
1368  message-mode-field-menu message-mode-map ""
1369  '("Field"
1370    ["Fetch To" message-insert-to t]
1371    ["Fetch Newsgroups" message-insert-newsgroups t]
1372    "----"
1373    ["To" message-goto-to t]
1374    ["Subject" message-goto-subject t]
1375    ["Cc" message-goto-cc t]
1376    ["Reply-To" message-goto-reply-to t]
1377    ["Summary" message-goto-summary t]
1378    ["Keywords" message-goto-keywords t]
1379    ["Newsgroups" message-goto-newsgroups t]
1380    ["Followup-To" message-goto-followup-to t]
1381    ["Distribution" message-goto-distribution t]
1382    ["Body" message-goto-body t]
1383    ["Signature" message-goto-signature t]))
1384
1385 (defvar facemenu-add-face-function)
1386 (defvar facemenu-remove-face-function)
1387
1388 ;;;###autoload
1389 (defun message-mode ()
1390   "Major mode for editing mail and news to be sent.
1391 Like Text Mode but with these additional commands:
1392 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1393 C-c C-d  Pospone sending the message        C-c C-k  Kill the message
1394 C-c C-f  move to a header field (and create it if there isn't):
1395          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1396          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1397          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1398          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1399          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1400          C-c C-f C-f  move to Followup-To
1401 C-c C-t  message-insert-to (add a To header to a news followup)
1402 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1403 C-c C-b  message-goto-body (move to beginning of message text).
1404 C-c C-i  message-goto-signature (move to the beginning of the signature).
1405 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1406 C-c C-y  message-yank-original (insert current message, if any).
1407 C-c C-q  message-fill-yanked-message (fill what was yanked).
1408 C-c C-e  message-elide-region (elide the text between point and mark).
1409 C-c C-v  message-delete-not-region (remove the text outside the region).
1410 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1411 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1412 C-c C-a  mml-attach-file (attach a file as MIME).
1413 M-RET    message-newline-and-reformat (break the line and reformat)."
1414   (interactive)
1415   (kill-all-local-variables)
1416   (set (make-local-variable 'message-reply-buffer) nil)
1417   (make-local-variable 'message-send-actions)
1418   (make-local-variable 'message-exit-actions)
1419   (make-local-variable 'message-kill-actions)
1420   (make-local-variable 'message-postpone-actions)
1421   (make-local-variable 'message-draft-article)
1422   (make-local-hook 'kill-buffer-hook)
1423   (set-syntax-table message-mode-syntax-table)
1424   (use-local-map message-mode-map)
1425   (setq local-abbrev-table message-mode-abbrev-table)
1426   (setq major-mode 'message-mode)
1427   (setq mode-name "Message")
1428   (setq buffer-offer-save t)
1429   (make-local-variable 'facemenu-add-face-function)
1430   (make-local-variable 'facemenu-remove-face-function)
1431   (setq facemenu-add-face-function
1432         (lambda (face end)
1433           (let ((face-fun (cdr (assq face message-face-alist))))
1434             (if face-fun
1435                 (funcall face-fun (point) end)
1436               (error "Face %s not configured for %s mode" face mode-name)))
1437           "")
1438         facemenu-remove-face-function t)
1439   (make-local-variable 'paragraph-separate)
1440   (make-local-variable 'paragraph-start)
1441   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1442   ;; lines that delimit forwarded messages.
1443   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1444   ;; are also sometimes used and should be separators.
1445   (setq paragraph-start
1446         (concat (regexp-quote mail-header-separator)
1447                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1448                 "-- $\\|---+$\\|"
1449                 page-delimiter
1450                 ;;!!! Uhm... shurely this can't be right?
1451                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1452   (setq paragraph-separate paragraph-start)
1453   (make-local-variable 'message-reply-headers)
1454   (setq message-reply-headers nil)
1455   (make-local-variable 'message-newsreader)
1456   (make-local-variable 'message-mailer)
1457   (make-local-variable 'message-post-method)
1458   (set (make-local-variable 'message-sent-message-via) nil)
1459   (set (make-local-variable 'message-checksum) nil)
1460   (set (make-local-variable 'message-mime-part) 0)
1461   ;;(when (fboundp 'mail-hist-define-keys)
1462   ;;  (mail-hist-define-keys))
1463   (when (string-match "XEmacs\\|Lucid" emacs-version)
1464     (message-setup-toolbar))
1465   (easy-menu-add message-mode-menu message-mode-map)
1466   (easy-menu-add message-mode-field-menu message-mode-map)
1467   ;; Allow mail alias things.
1468   (when (eq message-mail-alias-type 'abbrev)
1469     (if (fboundp 'mail-abbrevs-setup)
1470         (mail-abbrevs-setup)
1471       (mail-aliases-setup)))
1472   (message-set-auto-save-file-name)
1473   (unless (string-match "XEmacs" emacs-version)
1474     (set (make-local-variable 'font-lock-defaults)
1475          '(message-font-lock-keywords t)))
1476   (make-local-variable 'adaptive-fill-regexp)
1477   (setq adaptive-fill-regexp
1478         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|" adaptive-fill-regexp))
1479   (unless (boundp 'adaptive-fill-first-line-regexp)
1480     (setq adaptive-fill-first-line-regexp nil))
1481   (make-local-variable 'adaptive-fill-first-line-regexp)
1482   (setq adaptive-fill-first-line-regexp
1483         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1484                 adaptive-fill-first-line-regexp))
1485   (make-local-variable 'auto-fill-inhibit-regexp)
1486   (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1487   (mm-enable-multibyte)
1488   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1489   (setq indent-tabs-mode nil)
1490   (mml-mode)
1491   (run-hooks 'text-mode-hook 'message-mode-hook))
1492
1493 \f
1494
1495 ;;;
1496 ;;; Message mode commands
1497 ;;;
1498
1499 ;;; Movement commands
1500
1501 (defun message-goto-to ()
1502   "Move point to the To header."
1503   (interactive)
1504   (message-position-on-field "To"))
1505
1506 (defun message-goto-subject ()
1507   "Move point to the Subject header."
1508   (interactive)
1509   (message-position-on-field "Subject"))
1510
1511 (defun message-goto-cc ()
1512   "Move point to the Cc header."
1513   (interactive)
1514   (message-position-on-field "Cc" "To"))
1515
1516 (defun message-goto-bcc ()
1517   "Move point to the Bcc  header."
1518   (interactive)
1519   (message-position-on-field "Bcc" "Cc" "To"))
1520
1521 (defun message-goto-fcc ()
1522   "Move point to the Fcc header."
1523   (interactive)
1524   (message-position-on-field "Fcc" "To" "Newsgroups"))
1525
1526 (defun message-goto-reply-to ()
1527   "Move point to the Reply-To header."
1528   (interactive)
1529   (message-position-on-field "Reply-To" "Subject"))
1530
1531 (defun message-goto-newsgroups ()
1532   "Move point to the Newsgroups header."
1533   (interactive)
1534   (message-position-on-field "Newsgroups"))
1535
1536 (defun message-goto-distribution ()
1537   "Move point to the Distribution header."
1538   (interactive)
1539   (message-position-on-field "Distribution"))
1540
1541 (defun message-goto-followup-to ()
1542   "Move point to the Followup-To header."
1543   (interactive)
1544   (message-position-on-field "Followup-To" "Newsgroups"))
1545
1546 (defun message-goto-keywords ()
1547   "Move point to the Keywords header."
1548   (interactive)
1549   (message-position-on-field "Keywords" "Subject"))
1550
1551 (defun message-goto-summary ()
1552   "Move point to the Summary header."
1553   (interactive)
1554   (message-position-on-field "Summary" "Subject"))
1555
1556 (defun message-goto-body ()
1557   "Move point to the beginning of the message body."
1558   (interactive)
1559   (if (looking-at "[ \t]*\n") (expand-abbrev))
1560   (goto-char (point-min))
1561   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1562       (search-forward "\n\n" nil t)))
1563
1564 (defun message-goto-eoh ()
1565   "Move point to the end of the headers."
1566   (interactive)
1567   (message-goto-body)
1568   (forward-line -1))
1569
1570 (defun message-goto-signature ()
1571   "Move point to the beginning of the message signature.
1572 If there is no signature in the article, go to the end and
1573 return nil."
1574   (interactive)
1575   (goto-char (point-min))
1576   (if (re-search-forward message-signature-separator nil t)
1577       (forward-line 1)
1578     (goto-char (point-max))
1579     nil))
1580
1581 \f
1582
1583 (defun message-insert-to (&optional force)
1584   "Insert a To header that points to the author of the article being replied to.
1585 If the original author requested not to be sent mail, the function signals
1586 an error.
1587 With the prefix argument FORCE, insert the header anyway."
1588   (interactive "P")
1589   (let ((co (message-fetch-reply-field "mail-copies-to")))
1590     (when (and (null force)
1591                co
1592                (or (equal (downcase co) "never")
1593                    (equal (downcase co) "nobody")))
1594       (error "The user has requested not to have copies sent via mail")))
1595   (when (and (message-position-on-field "To")
1596              (mail-fetch-field "to")
1597              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1598     (insert ", "))
1599   (insert (or (message-fetch-reply-field "reply-to")
1600               (message-fetch-reply-field "from") "")))
1601
1602 (defun message-widen-reply ()
1603   "Widen the reply to include maximum recipients."
1604   (interactive)
1605   (let ((follow-to
1606          (and message-reply-buffer
1607               (buffer-name message-reply-buffer)
1608               (save-excursion
1609                 (set-buffer message-reply-buffer)
1610                 (message-get-reply-headers t)))))
1611     (save-excursion
1612       (save-restriction
1613         (message-narrow-to-headers)
1614         (dolist (elem follow-to)
1615           (message-remove-header (symbol-name (car elem)))
1616           (goto-char (point-min))
1617           (insert (symbol-name (car elem)) ": "
1618                   (cdr elem) "\n"))))))
1619
1620 (defun message-insert-newsgroups ()
1621   "Insert the Newsgroups header from the article being replied to."
1622   (interactive)
1623   (when (and (message-position-on-field "Newsgroups")
1624              (mail-fetch-field "newsgroups")
1625              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1626     (insert ","))
1627   (insert (or (message-fetch-reply-field "newsgroups") "")))
1628
1629 \f
1630
1631 ;;; Various commands
1632
1633 (defun message-delete-not-region (beg end)
1634   "Delete everything in the body of the current message that is outside of the region."
1635   (interactive "r")
1636   (save-excursion
1637     (goto-char end)
1638     (delete-region (point) (if (not (message-goto-signature))
1639                                (point)
1640                              (forward-line -2)
1641                              (point)))
1642     (insert "\n")
1643     (goto-char beg)
1644     (delete-region beg (progn (message-goto-body)
1645                               (forward-line 2)
1646                               (point))))
1647   (when (message-goto-signature)
1648     (forward-line -2)))
1649
1650 (defun message-kill-to-signature ()
1651   "Deletes all text up to the signature."
1652   (interactive)
1653   (let ((point (point)))
1654     (message-goto-signature)
1655     (unless (eobp)
1656       (forward-line -2))
1657     (kill-region point (point))
1658     (unless (bolp)
1659       (insert "\n"))))
1660
1661 (defun message-newline-and-reformat ()
1662   "Insert four newlines, and then reformat if inside quoted text."
1663   (interactive)
1664   (let ((prefix "[]>»|:}+ \t]*")
1665         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
1666         quoted point)
1667     (unless (bolp)
1668       (save-excursion
1669         (beginning-of-line)
1670         (when (looking-at (concat prefix
1671                                   supercite-thing))
1672           (setq quoted (match-string 0))))
1673       (insert "\n"))
1674     (setq point (point))
1675     (insert "\n\n\n")
1676     (delete-region (point) (re-search-forward "[ \t]*"))
1677     (when quoted
1678       (insert quoted))
1679     (fill-paragraph nil)
1680     (goto-char point)
1681     (forward-line 1)))
1682
1683 (defun message-insert-signature (&optional force)
1684   "Insert a signature.  See documentation for the `message-signature' variable."
1685   (interactive (list 0))
1686   (let* ((signature
1687           (cond
1688            ((and (null message-signature)
1689                  (eq force 0))
1690             (save-excursion
1691               (goto-char (point-max))
1692               (not (re-search-backward message-signature-separator nil t))))
1693            ((and (null message-signature)
1694                  force)
1695             t)
1696            ((message-functionp message-signature)
1697             (funcall message-signature))
1698            ((listp message-signature)
1699             (eval message-signature))
1700            (t message-signature)))
1701          (signature
1702           (cond ((stringp signature)
1703                  signature)
1704                 ((and (eq t signature)
1705                       message-signature-file
1706                       (file-exists-p message-signature-file))
1707                  signature))))
1708     (when signature
1709       (goto-char (point-max))
1710       ;; Insert the signature.
1711       (unless (bolp)
1712         (insert "\n"))
1713       (insert "\n-- \n")
1714       (if (eq signature t)
1715           (insert-file-contents message-signature-file)
1716         (insert signature))
1717       (goto-char (point-max))
1718       (or (bolp) (insert "\n")))))
1719
1720 (defun message-elide-region (b e)
1721   "Elide the text between point and mark.
1722 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1723 text was killed."
1724   (interactive "r")
1725   (kill-region b e)
1726   (insert message-elide-ellipsis))
1727
1728 (defvar message-caesar-translation-table nil)
1729
1730 (defun message-caesar-region (b e &optional n)
1731   "Caesar rotation of region by N, default 13, for decrypting netnews."
1732   (interactive
1733    (list
1734     (min (point) (or (mark t) (point)))
1735     (max (point) (or (mark t) (point)))
1736     (when current-prefix-arg
1737       (prefix-numeric-value current-prefix-arg))))
1738
1739   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1740   (unless (or (zerop n)                 ; no action needed for a rot of 0
1741               (= b e))                  ; no region to rotate
1742     ;; We build the table, if necessary.
1743     (when (or (not message-caesar-translation-table)
1744               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1745       (setq message-caesar-translation-table
1746             (message-make-caesar-translation-table n)))
1747     (translate-region b e message-caesar-translation-table)))
1748
1749 (defun message-make-caesar-translation-table (n)
1750   "Create a rot table with offset N."
1751   (let ((i -1)
1752         (table (make-string 256 0)))
1753     (while (< (incf i) 256)
1754       (aset table i i))
1755     (concat
1756      (substring table 0 ?A)
1757      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1758      (substring table ?A (+ ?A n))
1759      (substring table (+ ?A 26) ?a)
1760      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1761      (substring table ?a (+ ?a n))
1762      (substring table (+ ?a 26) 255))))
1763
1764 (defun message-caesar-buffer-body (&optional rotnum)
1765   "Caesar rotates all letters in the current buffer by 13 places.
1766 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1767 With prefix arg, specifies the number of places to rotate each letter forward.
1768 Mail and USENET news headers are not rotated."
1769   (interactive (if current-prefix-arg
1770                    (list (prefix-numeric-value current-prefix-arg))
1771                  (list nil)))
1772   (save-excursion
1773     (save-restriction
1774       (when (message-goto-body)
1775         (narrow-to-region (point) (point-max)))
1776       (message-caesar-region (point-min) (point-max) rotnum))))
1777
1778 (defun message-pipe-buffer-body (program)
1779   "Pipe the message body in the current buffer through PROGRAM."
1780   (save-excursion
1781     (save-restriction
1782       (when (message-goto-body)
1783         (narrow-to-region (point) (point-max)))
1784       (shell-command-on-region
1785        (point-min) (point-max) program nil t))))
1786
1787 (defun message-rename-buffer (&optional enter-string)
1788   "Rename the *message* buffer to \"*message* RECIPIENT\".
1789 If the function is run with a prefix, it will ask for a new buffer
1790 name, rather than giving an automatic name."
1791   (interactive "Pbuffer name: ")
1792   (save-excursion
1793     (save-restriction
1794       (goto-char (point-min))
1795       (narrow-to-region (point)
1796                         (search-forward mail-header-separator nil 'end))
1797       (let* ((mail-to (or
1798                        (if (message-news-p) (message-fetch-field "Newsgroups")
1799                          (message-fetch-field "To"))
1800                        ""))
1801              (mail-trimmed-to
1802               (if (string-match "," mail-to)
1803                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1804                 mail-to))
1805              (name-default (concat "*message* " mail-trimmed-to))
1806              (name (if enter-string
1807                        (read-string "New buffer name: " name-default)
1808                      name-default)))
1809         (rename-buffer name t)))))
1810
1811 (defun message-fill-yanked-message (&optional justifyp)
1812   "Fill the paragraphs of a message yanked into this one.
1813 Numeric argument means justify as well."
1814   (interactive "P")
1815   (save-excursion
1816     (goto-char (point-min))
1817     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1818     (let ((fill-prefix message-yank-prefix))
1819       (fill-individual-paragraphs (point) (point-max) justifyp))))
1820
1821 (defun message-indent-citation ()
1822   "Modify text just inserted from a message to be cited.
1823 The inserted text should be the region.
1824 When this function returns, the region is again around the modified text.
1825
1826 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1827 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1828   (let ((start (point)))
1829     ;; Remove unwanted headers.
1830     (when message-ignored-cited-headers
1831       (let (all-removed)
1832         (save-restriction
1833           (narrow-to-region
1834            (goto-char start)
1835            (if (search-forward "\n\n" nil t)
1836                (1- (point))
1837              (point)))
1838           (message-remove-header message-ignored-cited-headers t)
1839           (when (= (point-min) (point-max))
1840             (setq all-removed t))
1841           (goto-char (point-max)))
1842         (if all-removed
1843             (goto-char start)
1844           (forward-line 1))))
1845     ;; Delete blank lines at the start of the buffer.
1846     (while (and (point-min)
1847                 (eolp)
1848                 (not (eobp)))
1849       (message-delete-line))
1850     ;; Delete blank lines at the end of the buffer.
1851     (goto-char (point-max))
1852     (unless (eolp)
1853       (insert "\n"))
1854     (while (and (zerop (forward-line -1))
1855                 (looking-at "$"))
1856       (message-delete-line))
1857     ;; Do the indentation.
1858     (if (null message-yank-prefix)
1859         (indent-rigidly start (mark t) message-indentation-spaces)
1860       (save-excursion
1861         (goto-char start)
1862         (while (< (point) (mark t))
1863           (insert message-yank-prefix)
1864           (forward-line 1))))
1865     (goto-char start)))
1866
1867 (defun message-yank-original (&optional arg)
1868   "Insert the message being replied to, if any.
1869 Puts point before the text and mark after.
1870 Normally indents each nonblank line ARG spaces (default 3).  However,
1871 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1872
1873 This function uses `message-cite-function' to do the actual citing.
1874
1875 Just \\[universal-argument] as argument means don't indent, insert no
1876 prefix, and don't delete any headers."
1877   (interactive "P")
1878   (let ((modified (buffer-modified-p)))
1879     (when (and message-reply-buffer
1880                message-cite-function)
1881       (delete-windows-on message-reply-buffer t)
1882       (insert-buffer message-reply-buffer)
1883       (funcall message-cite-function)
1884       (message-exchange-point-and-mark)
1885       (unless (bolp)
1886         (insert ?\n))
1887       (unless modified
1888         (setq message-checksum (message-checksum))))))
1889
1890 (defun message-yank-buffer (buffer)
1891   "Insert BUFFER into the current buffer and quote it."
1892   (interactive "bYank buffer: ")
1893   (let ((message-reply-buffer buffer))
1894     (save-window-excursion
1895       (message-yank-original))))
1896
1897 (defun message-buffers ()
1898   "Return a list of active message buffers."
1899   (let (buffers)
1900     (save-excursion
1901       (dolist (buffer (buffer-list t))
1902         (set-buffer buffer)
1903         (when (and (eq major-mode 'message-mode)
1904                    (null message-sent-message-via))
1905           (push (buffer-name buffer) buffers))))
1906     (nreverse buffers)))
1907
1908 (defun message-cite-original-without-signature ()
1909   "Cite function in the standard Message manner."
1910   (let ((start (point))
1911         (end (mark t))
1912         (functions
1913          (when message-indent-citation-function
1914            (if (listp message-indent-citation-function)
1915                message-indent-citation-function
1916              (list message-indent-citation-function)))))
1917     (mml-quote-region start end)
1918     ;; Allow undoing.
1919     (undo-boundary)
1920     (goto-char end)
1921     (when (re-search-backward message-signature-separator start t)
1922       ;; Also peel off any blank lines before the signature.
1923       (forward-line -1)
1924       (while (looking-at "^[ \t]*$")
1925         (forward-line -1))
1926       (forward-line 1)
1927       (delete-region (point) end))
1928     (goto-char start)
1929     (while functions
1930       (funcall (pop functions)))
1931     (when message-citation-line-function
1932       (unless (bolp)
1933         (insert "\n"))
1934       (funcall message-citation-line-function))))
1935
1936 (defvar mail-citation-hook)             ;Compiler directive
1937 (defun message-cite-original ()
1938   "Cite function in the standard Message manner."
1939   (if (and (boundp 'mail-citation-hook)
1940            mail-citation-hook)
1941       (run-hooks 'mail-citation-hook)
1942     (let ((start (point))
1943           (end (mark t))
1944           (functions
1945            (when message-indent-citation-function
1946              (if (listp message-indent-citation-function)
1947                  message-indent-citation-function
1948                (list message-indent-citation-function)))))
1949       (mml-quote-region start end)
1950       (goto-char start)
1951       (while functions
1952         (funcall (pop functions)))
1953       (when message-citation-line-function
1954         (unless (bolp)
1955           (insert "\n"))
1956         (funcall message-citation-line-function)))))
1957
1958 (defun message-insert-citation-line ()
1959   "Function that inserts a simple citation line."
1960   (when message-reply-headers
1961     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1962
1963 (defun message-position-on-field (header &rest afters)
1964   (let ((case-fold-search t))
1965     (save-restriction
1966       (narrow-to-region
1967        (goto-char (point-min))
1968        (progn
1969          (re-search-forward
1970           (concat "^" (regexp-quote mail-header-separator) "$"))
1971          (match-beginning 0)))
1972       (goto-char (point-min))
1973       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1974           (progn
1975             (re-search-forward "^[^ \t]" nil 'move)
1976             (beginning-of-line)
1977             (skip-chars-backward "\n")
1978             t)
1979         (while (and afters
1980                     (not (re-search-forward
1981                           (concat "^" (regexp-quote (car afters)) ":")
1982                           nil t)))
1983           (pop afters))
1984         (when afters
1985           (re-search-forward "^[^ \t]" nil 'move)
1986           (beginning-of-line))
1987         (insert header ": \n")
1988         (forward-char -1)
1989         nil))))
1990
1991 (defun message-remove-signature ()
1992   "Remove the signature from the text between point and mark.
1993 The text will also be indented the normal way."
1994   (save-excursion
1995     (let ((start (point))
1996           mark)
1997       (if (not (re-search-forward message-signature-separator (mark t) t))
1998           ;; No signature here, so we just indent the cited text.
1999           (message-indent-citation)
2000         ;; Find the last non-empty line.
2001         (forward-line -1)
2002         (while (looking-at "[ \t]*$")
2003           (forward-line -1))
2004         (forward-line 1)
2005         (setq mark (set-marker (make-marker) (point)))
2006         (goto-char start)
2007         (message-indent-citation)
2008         ;; Enable undoing the deletion.
2009         (undo-boundary)
2010         (delete-region mark (mark t))
2011         (set-marker mark nil)))))
2012
2013 \f
2014
2015 ;;;
2016 ;;; Sending messages
2017 ;;;
2018
2019 (defun message-send-and-exit (&optional arg)
2020   "Send message like `message-send', then, if no errors, exit from mail buffer."
2021   (interactive "P")
2022   (let ((buf (current-buffer))
2023         (actions message-exit-actions))
2024     (when (and (message-send arg)
2025                (buffer-name buf))
2026       (if message-kill-buffer-on-exit
2027           (kill-buffer buf)
2028         (bury-buffer buf)
2029         (when (eq buf (current-buffer))
2030           (message-bury buf)))
2031       (message-do-actions actions)
2032       t)))
2033
2034 (defun message-dont-send ()
2035   "Don't send the message you have been editing."
2036   (interactive)
2037   (set-buffer-modified-p t)
2038   (save-buffer)
2039   (let ((actions message-postpone-actions))
2040     (message-bury (current-buffer))
2041     (message-do-actions actions)))
2042
2043 (defun message-kill-buffer ()
2044   "Kill the current buffer."
2045   (interactive)
2046   (when (or (not (buffer-modified-p))
2047             (yes-or-no-p "Message modified; kill anyway? "))
2048     (let ((actions message-kill-actions))
2049       (setq buffer-file-name nil)
2050       (kill-buffer (current-buffer))
2051       (message-do-actions actions))))
2052
2053 (defun message-bury (buffer)
2054   "Bury this mail buffer."
2055   (let ((newbuf (other-buffer buffer)))
2056     (bury-buffer buffer)
2057     (if (and (fboundp 'frame-parameters)
2058              (cdr (assq 'dedicated (frame-parameters)))
2059              (not (null (delq (selected-frame) (visible-frame-list)))))
2060         (delete-frame (selected-frame))
2061       (switch-to-buffer newbuf))))
2062
2063 (defun message-send (&optional arg)
2064   "Send the message in the current buffer.
2065 If `message-interactive' is non-nil, wait for success indication or
2066 error messages, and inform user.
2067 Otherwise any failure is reported in a message back to the user from
2068 the mailer.
2069 The usage of ARG is defined by the instance that called Message.
2070 It should typically alter the sending method in some way or other."
2071   (interactive "P")
2072   ;; Make it possible to undo the coming changes.
2073   (undo-boundary)
2074   (let ((inhibit-read-only t))
2075     (put-text-property (point-min) (point-max) 'read-only nil))
2076   (message-fix-before-sending)
2077   (run-hooks 'message-send-hook)
2078   (message "Sending...")
2079   (let ((alist message-send-method-alist)
2080         (success t)
2081         elem sent)
2082     (while (and success
2083                 (setq elem (pop alist)))
2084       (when (or (not (funcall (cadr elem)))
2085                 (and (or (not (memq (car elem)
2086                                     message-sent-message-via))
2087                          (y-or-n-p
2088                           (format
2089                            "Already sent message via %s; resend? "
2090                            (car elem))))
2091                      (setq success (funcall (caddr elem) arg))))
2092         (setq sent t)))
2093     (unless (or sent (not success))
2094       (error "No methods specified to send by"))
2095     (when (and success sent)
2096       (message-do-fcc)
2097       (save-excursion
2098         (run-hooks 'message-sent-hook))
2099       (message "Sending...done")
2100       ;; Mark the buffer as unmodified and delete auto-save.
2101       (set-buffer-modified-p nil)
2102       (delete-auto-save-file-if-necessary t)
2103       (message-disassociate-draft)
2104       ;; Delete other mail buffers and stuff.
2105       (message-do-send-housekeeping)
2106       (message-do-actions message-send-actions)
2107       ;; Return success.
2108       t)))
2109
2110 (defun message-send-via-mail (arg)
2111   "Send the current message via mail."
2112   (message-send-mail arg))
2113
2114 (defun message-send-via-news (arg)
2115   "Send the current message via news."
2116   (funcall message-send-news-function arg))
2117
2118 (defmacro message-check (type &rest forms)
2119   "Eval FORMS if TYPE is to be checked."
2120   `(or (message-check-element ,type)
2121        (save-excursion
2122          ,@forms)))
2123
2124 (put 'message-check 'lisp-indent-function 1)
2125 (put 'message-check 'edebug-form-spec '(form body))
2126
2127 (defun message-fix-before-sending ()
2128   "Do various things to make the message nice before sending it."
2129   ;; Make sure there's a newline at the end of the message.
2130   (goto-char (point-max))
2131   (unless (bolp)
2132     (insert "\n"))
2133   ;; Delete all invisible text.
2134   (message-check 'invisible-text
2135     (when (text-property-any (point-min) (point-max) 'invisible t)
2136       (put-text-property (point-min) (point-max) 'invisible nil)
2137       (unless (yes-or-no-p
2138                "Invisible text found and made visible; continue posting? ")
2139         (error "Invisible text found and made visible")))))
2140
2141 (defun message-add-action (action &rest types)
2142   "Add ACTION to be performed when doing an exit of type TYPES."
2143   (let (var)
2144     (while types
2145       (set (setq var (intern (format "message-%s-actions" (pop types))))
2146            (nconc (symbol-value var) (list action))))))
2147
2148 (defun message-do-actions (actions)
2149   "Perform all actions in ACTIONS."
2150   ;; Now perform actions on successful sending.
2151   (while actions
2152     (ignore-errors
2153       (cond
2154        ;; A simple function.
2155        ((message-functionp (car actions))
2156         (funcall (car actions)))
2157        ;; Something to be evaled.
2158        (t
2159         (eval (car actions)))))
2160     (pop actions)))
2161
2162 (defun message-send-mail-partially ()
2163   "Sendmail as message/partial."
2164   (let ((p (goto-char (point-min)))
2165         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2166         (curbuf (current-buffer))
2167         (id (message-make-message-id)) (n 1)
2168         plist total  header required-mail-headers)
2169     (while (not (eobp))
2170       (if (< (point-max) (+ p message-send-mail-partially-limit))
2171           (goto-char (point-max))
2172         (goto-char (+ p message-send-mail-partially-limit))
2173         (beginning-of-line)
2174         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2175       (push p plist)
2176       (setq p (point)))
2177     (setq total (length plist))
2178     (push (point-max) plist)
2179     (setq plist (nreverse plist))
2180     (unwind-protect
2181         (save-excursion
2182           (setq p (pop plist))
2183           (while plist
2184             (set-buffer curbuf)
2185             (copy-to-buffer tembuf p (car plist))
2186             (set-buffer tembuf)
2187             (goto-char (point-min))
2188             (if header
2189                 (progn
2190                   (goto-char (point-min))
2191                   (narrow-to-region (point) (point))
2192                   (insert header))
2193               (message-goto-eoh)
2194               (setq header (buffer-substring (point-min) (point)))
2195               (goto-char (point-min))
2196               (narrow-to-region (point) (point))
2197               (insert header)
2198               (message-remove-header "Mime-Version")
2199               (message-remove-header "Content-Type")
2200               (message-remove-header "Content-Transfer-Encoding")
2201               (message-remove-header "Message-ID")
2202               (message-remove-header "Lines")
2203               (goto-char (point-max))
2204               (insert "Mime-Version: 1.0\n")
2205               (setq header (buffer-substring (point-min) (point-max))))
2206             (goto-char (point-max))
2207             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2208                             id n total))
2209             (let ((mail-header-separator ""))
2210               (when (memq 'Message-ID message-required-mail-headers)
2211                 (insert "Message-ID: " (message-make-message-id) "\n"))
2212               (when (memq 'Lines message-required-mail-headers)
2213                 (let ((mail-header-separator ""))
2214                   (insert "Lines: " (message-make-lines) "\n")))
2215               (message-goto-subject)
2216               (end-of-line)
2217               (insert (format " (%d/%d)" n total))
2218               (goto-char (point-max))
2219               (insert "\n")
2220               (widen)
2221               (funcall message-send-mail-function))
2222             (setq n (+ n 1))
2223             (setq p (pop plist))
2224             (erase-buffer)))
2225       (kill-buffer tembuf))))
2226
2227 (defun message-send-mail (&optional arg)
2228   (require 'mail-utils)
2229   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2230          (case-fold-search nil)
2231          (news (message-news-p))
2232          (mailbuf (current-buffer))
2233          (message-this-is-mail t)
2234          (message-posting-charset
2235           (if (fboundp 'gnus-setup-posting-charset)
2236               (gnus-setup-posting-charset nil)
2237             message-posting-charset)))
2238     (save-restriction
2239       (message-narrow-to-headers)
2240       ;; Insert some headers.
2241       (let ((message-deletable-headers
2242              (if news nil message-deletable-headers)))
2243         (message-generate-headers message-required-mail-headers))
2244       ;; Let the user do all of the above.
2245       (run-hooks 'message-header-hook))
2246     (unwind-protect
2247         (save-excursion
2248           (set-buffer tembuf)
2249           (erase-buffer)
2250           ;; Avoid copying text props.
2251           (insert (format
2252                    "%s" (save-excursion
2253                           (set-buffer mailbuf)
2254                           (buffer-string))))
2255           ;; Remove some headers.
2256           (message-encode-message-body)
2257           (save-restriction
2258             (message-narrow-to-headers)
2259             ;; We (re)generate the Lines header.
2260             (when (memq 'Lines message-required-mail-headers)
2261               (message-generate-headers '(Lines)))
2262             ;; Remove some headers.
2263             (message-remove-header message-ignored-mail-headers t)
2264             (mail-encode-encoded-word-buffer))
2265           (goto-char (point-max))
2266           ;; require one newline at the end.
2267           (or (= (preceding-char) ?\n)
2268               (insert ?\n))
2269           (when (and news
2270                      (or (message-fetch-field "cc")
2271                          (message-fetch-field "to")))
2272             (message-insert-courtesy-copy))
2273           (if (or (not message-send-mail-partially-limit)
2274                   (< (point-max) message-send-mail-partially-limit)
2275                   (not (y-or-n-p "The message size is too large, should it be sent partially?")))
2276               (funcall message-send-mail-function)
2277             (message-send-mail-partially)))
2278       (kill-buffer tembuf))
2279     (set-buffer mailbuf)
2280     (push 'mail message-sent-message-via)))
2281
2282 (defun message-send-mail-with-sendmail ()
2283   "Send off the prepared buffer with sendmail."
2284   (let ((errbuf (if message-interactive
2285                     (message-generate-new-buffer-clone-locals
2286                      " sendmail errors")
2287                   0))
2288         resend-to-addresses delimline)
2289     (let ((case-fold-search t))
2290       (save-restriction
2291         (message-narrow-to-headers)
2292         (setq resend-to-addresses (message-fetch-field "resent-to")))
2293       ;; Change header-delimiter to be what sendmail expects.
2294       (goto-char (point-min))
2295       (re-search-forward
2296        (concat "^" (regexp-quote mail-header-separator) "\n"))
2297       (replace-match "\n")
2298       (backward-char 1)
2299       (setq delimline (point-marker))
2300       (run-hooks 'message-send-mail-hook)
2301       ;; Insert an extra newline if we need it to work around
2302       ;; Sun's bug that swallows newlines.
2303       (goto-char (1+ delimline))
2304       (when (eval message-mailer-swallows-blank-line)
2305         (newline))
2306       (when message-interactive
2307         (save-excursion
2308           (set-buffer errbuf)
2309           (erase-buffer))))
2310     (let ((default-directory "/")
2311           (coding-system-for-write message-send-coding-system))
2312       (apply 'call-process-region
2313              (append (list (point-min) (point-max)
2314                            (if (boundp 'sendmail-program)
2315                                sendmail-program
2316                              "/usr/lib/sendmail")
2317                            nil errbuf nil "-oi")
2318                      ;; Always specify who from,
2319                      ;; since some systems have broken sendmails.
2320                      ;; But some systems are more broken with -f, so
2321                      ;; we'll let users override this.
2322                      (if (null message-sendmail-f-is-evil)
2323                          (list "-f" (message-make-address)))
2324                      ;; These mean "report errors by mail"
2325                      ;; and "deliver in background".
2326                      (if (null message-interactive) '("-oem" "-odb"))
2327                      ;; Get the addresses from the message
2328                      ;; unless this is a resend.
2329                      ;; We must not do that for a resend
2330                      ;; because we would find the original addresses.
2331                      ;; For a resend, include the specific addresses.
2332                      (if resend-to-addresses
2333                          (list resend-to-addresses)
2334                        '("-t")))))
2335     (when message-interactive
2336       (save-excursion
2337         (set-buffer errbuf)
2338         (goto-char (point-min))
2339         (while (re-search-forward "\n\n* *" nil t)
2340           (replace-match "; "))
2341         (if (not (zerop (buffer-size)))
2342             (error "Sending...failed to %s"
2343                    (buffer-substring (point-min) (point-max)))))
2344       (when (bufferp errbuf)
2345         (kill-buffer errbuf)))))
2346
2347 (defun message-send-mail-with-qmail ()
2348   "Pass the prepared message buffer to qmail-inject.
2349 Refer to the documentation for the variable `message-send-mail-function'
2350 to find out how to use this."
2351   ;; replace the header delimiter with a blank line
2352   (goto-char (point-min))
2353   (re-search-forward
2354    (concat "^" (regexp-quote mail-header-separator) "\n"))
2355   (replace-match "\n")
2356   (run-hooks 'message-send-mail-hook)
2357   ;; send the message
2358   (case
2359       (let ((coding-system-for-write message-send-coding-system))
2360         (apply
2361          'call-process-region 1 (point-max) message-qmail-inject-program
2362          nil nil nil
2363          ;; qmail-inject's default behaviour is to look for addresses on the
2364          ;; command line; if there're none, it scans the headers.
2365          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2366          ;;
2367          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2368          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2369          ;; message from stdin.
2370          ;;
2371          ;; qmail also has the advantage of not having been raped by
2372          ;; various vendors, so we don't have to allow for that, either --
2373          ;; compare this with message-send-mail-with-sendmail and weep
2374          ;; for sendmail's lost innocence.
2375          ;;
2376          ;; all this is way cool coz it lets us keep the arguments entirely
2377          ;; free for -inject-arguments -- a big win for the user and for us
2378          ;; since we don't have to play that double-guessing game and the user
2379          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2380          message-qmail-inject-args))
2381     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2382     ;; we have to look at the retval instead
2383     (0 nil)
2384     (1   (error "qmail-inject reported permanent failure"))
2385     (111 (error "qmail-inject reported transient failure"))
2386     ;; should never happen
2387     (t   (error "qmail-inject reported unknown failure"))))
2388
2389 (defun message-send-mail-with-mh ()
2390   "Send the prepared message buffer with mh."
2391   (let ((mh-previous-window-config nil)
2392         (name (mh-new-draft-name)))
2393     (setq buffer-file-name name)
2394     ;; MH wants to generate these headers itself.
2395     (when message-mh-deletable-headers
2396       (let ((headers message-mh-deletable-headers))
2397         (while headers
2398           (goto-char (point-min))
2399           (and (re-search-forward
2400                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2401                (message-delete-line))
2402           (pop headers))))
2403     (run-hooks 'message-send-mail-hook)
2404     ;; Pass it on to mh.
2405     (mh-send-letter)))
2406
2407 (defun message-send-news (&optional arg)
2408   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2409          (case-fold-search nil)
2410          (method (if (message-functionp message-post-method)
2411                      (funcall message-post-method arg)
2412                    message-post-method))
2413          (messbuf (current-buffer))
2414          (message-syntax-checks
2415           (if arg
2416               (cons '(existing-newsgroups . disabled)
2417                     message-syntax-checks)
2418             message-syntax-checks))
2419          (message-this-is-news t)
2420          (message-posting-charset (gnus-setup-posting-charset 
2421                                    (message-fetch-field "Newsgroups")))
2422          result)
2423     (if (not (message-check-news-body-syntax))
2424         nil
2425       (save-restriction
2426         (message-narrow-to-headers)
2427         ;; Insert some headers.
2428         (message-generate-headers message-required-news-headers)
2429         ;; Let the user do all of the above.
2430         (run-hooks 'message-header-hook))
2431       (message-cleanup-headers)
2432       (if (not (message-check-news-syntax))
2433           nil
2434         (unwind-protect
2435             (save-excursion
2436               (set-buffer tembuf)
2437               (buffer-disable-undo)
2438               (erase-buffer)
2439               ;; Avoid copying text props.
2440               (insert (format
2441                        "%s" (save-excursion
2442                               (set-buffer messbuf)
2443                               (buffer-string))))
2444               (message-encode-message-body)
2445               ;; Remove some headers.
2446               (save-restriction
2447                 (message-narrow-to-headers)
2448                 ;; We (re)generate the Lines header.
2449                 (when (memq 'Lines message-required-mail-headers)
2450                   (message-generate-headers '(Lines)))
2451                 ;; Remove some headers.
2452                 (message-remove-header message-ignored-news-headers t)
2453                 (let ((mail-parse-charset (car message-posting-charset)))
2454                   (mail-encode-encoded-word-buffer)))
2455               (goto-char (point-max))
2456               ;; require one newline at the end.
2457               (or (= (preceding-char) ?\n)
2458                   (insert ?\n))
2459               (let ((case-fold-search t))
2460                 ;; Remove the delimiter.
2461                 (goto-char (point-min))
2462                 (re-search-forward
2463                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2464                 (replace-match "\n")
2465                 (backward-char 1))
2466               (run-hooks 'message-send-news-hook)
2467               (gnus-open-server method)
2468               (setq result (let ((mail-header-separator ""))
2469                              (gnus-request-post method))))
2470           (kill-buffer tembuf))
2471         (set-buffer messbuf)
2472         (if result
2473             (push 'news message-sent-message-via)
2474           (message "Couldn't send message via news: %s"
2475                    (nnheader-get-report (car method)))
2476           nil)))))
2477
2478 ;;;
2479 ;;; Header generation & syntax checking.
2480 ;;;
2481
2482 (defun message-check-element (type)
2483   "Returns non-nil if this type is not to be checked."
2484   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2485       t
2486     (let ((able (assq type message-syntax-checks)))
2487       (and (consp able)
2488            (eq (cdr able) 'disabled)))))
2489
2490 (defun message-check-news-syntax ()
2491   "Check the syntax of the message."
2492   (save-excursion
2493     (save-restriction
2494       (widen)
2495       ;; We narrow to the headers and check them first.
2496       (save-excursion
2497         (save-restriction
2498           (message-narrow-to-headers)
2499           (message-check-news-header-syntax))))))
2500
2501 (defun message-check-news-header-syntax ()
2502   (and
2503    ;; Check Newsgroups header.
2504    (message-check 'newsgroups
2505      (let ((group (message-fetch-field "newsgroups")))
2506        (or
2507         (and group
2508              (not (string-match "\\`[ \t]*\\'" group)))
2509         (ignore
2510          (message
2511           "The newsgroups field is empty or missing.  Posting is denied.")))))
2512    ;; Check the Subject header.
2513    (message-check 'subject
2514      (let* ((case-fold-search t)
2515             (subject (message-fetch-field "subject")))
2516        (or
2517         (and subject
2518              (not (string-match "\\`[ \t]*\\'" subject)))
2519         (ignore
2520          (message
2521           "The subject field is empty or missing.  Posting is denied.")))))
2522    ;; Check for commands in Subject.
2523    (message-check 'subject-cmsg
2524      (if (string-match "^cmsg " (message-fetch-field "subject"))
2525          (y-or-n-p
2526           "The control code \"cmsg\" is in the subject.  Really post? ")
2527        t))
2528    ;; Check for multiple identical headers.
2529    (message-check 'multiple-headers
2530      (let (found)
2531        (while (and (not found)
2532                    (re-search-forward "^[^ \t:]+: " nil t))
2533          (save-excursion
2534            (or (re-search-forward
2535                 (concat "^"
2536                         (regexp-quote
2537                          (setq found
2538                                (buffer-substring
2539                                 (match-beginning 0) (- (match-end 0) 2))))
2540                         ":")
2541                 nil t)
2542                (setq found nil))))
2543        (if found
2544            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2545          t)))
2546    ;; Check for Version and Sendsys.
2547    (message-check 'sendsys
2548      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2549          (y-or-n-p
2550           (format "The article contains a %s command.  Really post? "
2551                   (buffer-substring (match-beginning 0)
2552                                     (1- (match-end 0)))))
2553        t))
2554    ;; See whether we can shorten Followup-To.
2555    (message-check 'shorten-followup-to
2556      (let ((newsgroups (message-fetch-field "newsgroups"))
2557            (followup-to (message-fetch-field "followup-to"))
2558            to)
2559        (when (and newsgroups
2560                   (string-match "," newsgroups)
2561                   (not followup-to)
2562                   (not
2563                    (zerop
2564                     (length
2565                      (setq to (completing-read
2566                                "Followups to: (default all groups) "
2567                                (mapcar (lambda (g) (list g))
2568                                        (cons "poster"
2569                                              (message-tokenize-header
2570                                               newsgroups)))))))))
2571          (goto-char (point-min))
2572          (insert "Followup-To: " to "\n"))
2573        t))
2574    ;; Check "Shoot me".
2575    (message-check 'shoot
2576      (if (re-search-forward
2577           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2578          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2579        t))
2580    ;; Check for Approved.
2581    (message-check 'approved
2582      (if (re-search-forward "^Approved:" nil t)
2583          (y-or-n-p "The article contains an Approved header.  Really post? ")
2584        t))
2585    ;; Check the Message-ID header.
2586    (message-check 'message-id
2587      (let* ((case-fold-search t)
2588             (message-id (message-fetch-field "message-id" t)))
2589        (or (not message-id)
2590            ;; Is there an @ in the ID?
2591            (and (string-match "@" message-id)
2592                 ;; Is there a dot in the ID?
2593                 (string-match "@[^.]*\\." message-id)
2594                 ;; Does the ID end with a dot?
2595                 (not (string-match "\\.>" message-id)))
2596            (y-or-n-p
2597             (format "The Message-ID looks strange: \"%s\".  Really post? "
2598                     message-id)))))
2599    ;; Check the Newsgroups & Followup-To headers.
2600    (message-check 'existing-newsgroups
2601      (let* ((case-fold-search t)
2602             (newsgroups (message-fetch-field "newsgroups"))
2603             (followup-to (message-fetch-field "followup-to"))
2604             (groups (message-tokenize-header
2605                      (if followup-to
2606                          (concat newsgroups "," followup-to)
2607                        newsgroups)))
2608             (hashtb (and (boundp 'gnus-active-hashtb)
2609                          gnus-active-hashtb))
2610             errors)
2611        (if (or (not hashtb)
2612                (not (boundp 'gnus-read-active-file))
2613                (not gnus-read-active-file)
2614                (eq gnus-read-active-file 'some))
2615            t
2616          (while groups
2617            (when (and (not (boundp (intern (car groups) hashtb)))
2618                       (not (equal (car groups) "poster")))
2619              (push (car groups) errors))
2620            (pop groups))
2621          (if (not errors)
2622              t
2623            (y-or-n-p
2624             (format
2625              "Really post to %s unknown group%s: %s "
2626              (if (= (length errors) 1) "this" "these")
2627              (if (= (length errors) 1) "" "s")
2628              (mapconcat 'identity errors ", ")))))))
2629    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2630    (message-check 'valid-newsgroups
2631      (let ((case-fold-search t)
2632            (headers '("Newsgroups" "Followup-To"))
2633            header error)
2634        (while (and headers (not error))
2635          (when (setq header (mail-fetch-field (car headers)))
2636            (if (or
2637                 (not
2638                  (string-match
2639                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2640                   header))
2641                 (memq
2642                  nil (mapcar
2643                       (lambda (g)
2644                         (not (string-match "\\.\\'\\|\\.\\." g)))
2645                       (message-tokenize-header header ","))))
2646                (setq error t)))
2647          (unless error
2648            (pop headers)))
2649        (if (not error)
2650            t
2651          (y-or-n-p
2652           (format "The %s header looks odd: \"%s\".  Really post? "
2653                   (car headers) header)))))
2654    (message-check 'repeated-newsgroups
2655      (let ((case-fold-search t)
2656            (headers '("Newsgroups" "Followup-To"))
2657            header error groups group)
2658        (while (and headers
2659                    (not error))
2660          (when (setq header (mail-fetch-field (pop headers)))
2661            (setq groups (message-tokenize-header header ","))
2662            (while (setq group (pop groups))
2663              (when (member group groups)
2664                (setq error group
2665                      groups nil)))))
2666        (if (not error)
2667            t
2668          (y-or-n-p
2669           (format "Group %s is repeated in headers.  Really post? " error)))))
2670    ;; Check the From header.
2671    (message-check 'from
2672      (let* ((case-fold-search t)
2673             (from (message-fetch-field "from"))
2674             ad)
2675        (cond
2676         ((not from)
2677          (message "There is no From line.  Posting is denied.")
2678          nil)
2679         ((or (not (string-match
2680                    "@[^\\.]*\\."
2681                    (setq ad (nth 1 (mail-extract-address-components
2682                                     from))))) ;larsi@ifi
2683              (string-match "\\.\\." ad) ;larsi@ifi..uio
2684              (string-match "@\\." ad)   ;larsi@.ifi.uio
2685              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2686              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2687              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2688          (message
2689           "Denied posting -- the From looks strange: \"%s\"." from)
2690          nil)
2691         (t t))))))
2692
2693 (defun message-check-news-body-syntax ()
2694   (and
2695    ;; Check for long lines.
2696    (message-check 'long-lines
2697      (goto-char (point-min))
2698      (re-search-forward
2699       (concat "^" (regexp-quote mail-header-separator) "$"))
2700      (while (and
2701              (progn
2702                (end-of-line)
2703                (< (current-column) 80))
2704              (zerop (forward-line 1))))
2705      (or (bolp)
2706          (eobp)
2707          (y-or-n-p
2708           "You have lines longer than 79 characters.  Really post? ")))
2709    ;; Check whether the article is empty.
2710    (message-check 'empty
2711      (goto-char (point-min))
2712      (re-search-forward
2713       (concat "^" (regexp-quote mail-header-separator) "$"))
2714      (forward-line 1)
2715      (let ((b (point)))
2716        (goto-char (point-max))
2717        (re-search-backward message-signature-separator nil t)
2718        (beginning-of-line)
2719        (or (re-search-backward "[^ \n\t]" b t)
2720            (y-or-n-p "Empty article.  Really post? "))))
2721    ;; Check for control characters.
2722    (message-check 'control-chars
2723      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2724          (y-or-n-p
2725           "The article contains control characters.  Really post? ")
2726        t))
2727    ;; Check excessive size.
2728    (message-check 'size
2729      (if (> (buffer-size) 60000)
2730          (y-or-n-p
2731           (format "The article is %d octets long.  Really post? "
2732                   (buffer-size)))
2733        t))
2734    ;; Check whether any new text has been added.
2735    (message-check 'new-text
2736      (or
2737       (not message-checksum)
2738       (not (eq (message-checksum) message-checksum))
2739       (y-or-n-p
2740        "It looks like no new text has been added.  Really post? ")))
2741    ;; Check the length of the signature.
2742    (message-check 'signature
2743      (goto-char (point-max))
2744      (if (> (count-lines (point) (point-max)) 5)
2745          (y-or-n-p
2746           (format
2747            "Your .sig is %d lines; it should be max 4.  Really post? "
2748            (1- (count-lines (point) (point-max)))))
2749        t))))
2750
2751 (defun message-checksum ()
2752   "Return a \"checksum\" for the current buffer."
2753   (let ((sum 0))
2754     (save-excursion
2755       (goto-char (point-min))
2756       (re-search-forward
2757        (concat "^" (regexp-quote mail-header-separator) "$"))
2758       (while (not (eobp))
2759         (when (not (looking-at "[ \t\n]"))
2760           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2761                             (char-after))))
2762         (forward-char 1)))
2763     sum))
2764
2765 (defun message-do-fcc ()
2766   "Process Fcc headers in the current buffer."
2767   (let ((case-fold-search t)
2768         (buf (current-buffer))
2769         list file)
2770     (save-excursion
2771       (set-buffer (get-buffer-create " *message temp*"))
2772       (erase-buffer)
2773       (insert-buffer-substring buf)
2774       (save-restriction
2775         (message-narrow-to-headers)
2776         (while (setq file (message-fetch-field "fcc"))
2777           (push file list)
2778           (message-remove-header "fcc" nil t)))
2779       (goto-char (point-min))
2780       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2781       (replace-match "" t t)
2782       ;; Process FCC operations.
2783       (while list
2784         (setq file (pop list))
2785         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2786             ;; Pipe the article to the program in question.
2787             (call-process-region (point-min) (point-max) shell-file-name
2788                                  nil nil nil shell-command-switch
2789                                  (match-string 1 file))
2790           ;; Save the article.
2791           (setq file (expand-file-name file))
2792           (unless (file-exists-p (file-name-directory file))
2793             (make-directory (file-name-directory file) t))
2794           (if (and message-fcc-handler-function
2795                    (not (eq message-fcc-handler-function 'rmail-output)))
2796               (funcall message-fcc-handler-function file)
2797             (if (and (file-readable-p file) (mail-file-babyl-p file))
2798                 (rmail-output file 1 nil t)
2799               (let ((mail-use-rfc822 t))
2800                 (rmail-output file 1 t t))))))
2801
2802       (kill-buffer (current-buffer)))))
2803
2804 (defun message-output (filename)
2805   "Append this article to Unix/babyl mail file.."
2806   (if (and (file-readable-p filename)
2807            (mail-file-babyl-p filename))
2808       (rmail-output-to-rmail-file filename t)
2809     (gnus-output-to-mail filename t)))
2810
2811 (defun message-cleanup-headers ()
2812   "Do various automatic cleanups of the headers."
2813   ;; Remove empty lines in the header.
2814   (save-restriction
2815     (message-narrow-to-headers)
2816     ;; Remove blank lines.
2817     (while (re-search-forward "^[ \t]*\n" nil t)
2818       (replace-match "" t t))
2819
2820     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2821     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2822     ;; embedded line breaks.
2823     (goto-char (point-min))
2824     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2825       (save-restriction
2826         (narrow-to-region
2827          (point)
2828          (if (re-search-forward "^[^ \t]" nil t)
2829              (match-beginning 0)
2830            (forward-line 1)
2831            (point)))
2832         (goto-char (point-min))
2833         (while (re-search-forward "\n[ \t]+" nil t)
2834           (replace-match " " t t))      ;No line breaks (too confusing)
2835         (goto-char (point-min))
2836         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2837           (replace-match "," t t))
2838         (goto-char (point-min))
2839         ;; Remove trailing commas.
2840         (when (re-search-forward ",+$" nil t)
2841           (replace-match "" t t))))))
2842
2843 (defun message-make-date (&optional now)
2844   "Make a valid data header.
2845 If NOW, use that time instead."
2846   (let* ((now (or now (current-time)))
2847          (zone (nth 8 (decode-time now)))
2848          (sign "+"))
2849     (when (< zone 0)
2850       (setq sign "-")
2851       (setq zone (- zone)))
2852     (concat
2853      (format-time-string "%d" now)
2854      ;; The month name of the %b spec is locale-specific.  Pfff.
2855      (format " %s "
2856              (capitalize (car (rassoc (nth 4 (decode-time now))
2857                                       parse-time-months))))
2858      (format-time-string "%Y %H:%M:%S " now)
2859      ;; We do all of this because XEmacs doesn't have the %z spec.
2860      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
2861
2862 (defun message-make-message-id ()
2863   "Make a unique Message-ID."
2864   (concat "<" (message-unique-id)
2865           (let ((psubject (save-excursion (message-fetch-field "subject")))
2866                 (psupersedes
2867                  (save-excursion (message-fetch-field "supersedes"))))
2868             (if (or
2869                  (and message-reply-headers
2870                       (mail-header-references message-reply-headers)
2871                       (mail-header-subject message-reply-headers)
2872                       psubject
2873                       (mail-header-subject message-reply-headers)
2874                       (not (string=
2875                             (message-strip-subject-re
2876                              (mail-header-subject message-reply-headers))
2877                             (message-strip-subject-re psubject))))
2878                  (and psupersedes
2879                       (string-match "_-_@" psupersedes)))
2880                 "_-_" ""))
2881           "@" (message-make-fqdn) ">"))
2882
2883 (defvar message-unique-id-char nil)
2884
2885 ;; If you ever change this function, make sure the new version
2886 ;; cannot generate IDs that the old version could.
2887 ;; You might for example insert a "." somewhere (not next to another dot
2888 ;; or string boundary), or modify the "fsf" string.
2889 (defun message-unique-id ()
2890   ;; Don't use microseconds from (current-time), they may be unsupported.
2891   ;; Instead we use this randomly inited counter.
2892   (setq message-unique-id-char
2893         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2894            ;; (current-time) returns 16-bit ints,
2895            ;; and 2^16*25 just fits into 4 digits i base 36.
2896            (* 25 25)))
2897   (let ((tm (current-time)))
2898     (concat
2899      (if (memq system-type '(ms-dos emx vax-vms))
2900          (let ((user (downcase (user-login-name))))
2901            (while (string-match "[^a-z0-9_]" user)
2902              (aset user (match-beginning 0) ?_))
2903            user)
2904        (message-number-base36 (user-uid) -1))
2905      (message-number-base36 (+ (car   tm)
2906                                (lsh (% message-unique-id-char 25) 16)) 4)
2907      (message-number-base36 (+ (nth 1 tm)
2908                                (lsh (/ message-unique-id-char 25) 16)) 4)
2909      ;; Append the newsreader name, because while the generated
2910      ;; ID is unique to this newsreader, other newsreaders might
2911      ;; otherwise generate the same ID via another algorithm.
2912      ".fsf")))
2913
2914 (defun message-number-base36 (num len)
2915   (if (if (< len 0)
2916           (<= num 0)
2917         (= len 0))
2918       ""
2919     (concat (message-number-base36 (/ num 36) (1- len))
2920             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2921                                   (% num 36))))))
2922
2923 (defun message-make-organization ()
2924   "Make an Organization header."
2925   (let* ((organization
2926           (when message-user-organization
2927             (if (message-functionp message-user-organization)
2928                 (funcall message-user-organization)
2929               message-user-organization))))
2930     (save-excursion
2931       (message-set-work-buffer)
2932       (cond ((stringp organization)
2933              (insert organization))
2934             ((and (eq t organization)
2935                   message-user-organization-file
2936                   (file-exists-p message-user-organization-file))
2937              (insert-file-contents message-user-organization-file)))
2938       (goto-char (point-min))
2939       (while (re-search-forward "[\t\n]+" nil t)
2940         (replace-match "" t t))
2941       (unless (zerop (buffer-size))
2942         (buffer-string)))))
2943
2944 (defun message-make-lines ()
2945   "Count the number of lines and return numeric string."
2946   (save-excursion
2947     (save-restriction
2948       (widen)
2949       (goto-char (point-min))
2950       (re-search-forward
2951        (concat "^" (regexp-quote mail-header-separator) "$"))
2952       (forward-line 1)
2953       (int-to-string (count-lines (point) (point-max))))))
2954
2955 (defun message-make-in-reply-to ()
2956   "Return the In-Reply-To header for this message."
2957   (when message-reply-headers
2958     (let ((from (mail-header-from message-reply-headers))
2959           (date (mail-header-date message-reply-headers)))
2960       (when from
2961         (let ((stop-pos
2962                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2963           (concat (if (and stop-pos
2964                            (not (zerop stop-pos)))
2965                       (substring from 0 stop-pos) from)
2966                   "'s message of \""
2967                   (if (or (not date) (string= date ""))
2968                       "(unknown date)" date)
2969                   "\""))))))
2970
2971 (defun message-make-distribution ()
2972   "Make a Distribution header."
2973   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2974     (cond ((message-functionp message-distribution-function)
2975            (funcall message-distribution-function))
2976           (t orig-distribution))))
2977
2978 (defun message-make-expires ()
2979   "Return an Expires header based on `message-expires'."
2980   (let ((current (current-time))
2981         (future (* 1.0 message-expires 60 60 24)))
2982     ;; Add the future to current.
2983     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2984     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2985     (message-make-date current)))
2986
2987 (defun message-make-path ()
2988   "Return uucp path."
2989   (let ((login-name (user-login-name)))
2990     (cond ((null message-user-path)
2991            (concat (system-name) "!" login-name))
2992           ((stringp message-user-path)
2993            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2994            (concat message-user-path "!" login-name))
2995           (t login-name))))
2996
2997 (defun message-make-from ()
2998   "Make a From header."
2999   (let* ((style message-from-style)
3000          (login (message-make-address))
3001          (fullname
3002           (or (and (boundp 'user-full-name)
3003                    user-full-name)
3004               (user-full-name))))
3005     (when (string= fullname "&")
3006       (setq fullname (user-login-name)))
3007     (save-excursion
3008       (message-set-work-buffer)
3009       (cond
3010        ((or (null style)
3011             (equal fullname ""))
3012         (insert login))
3013        ((or (eq style 'angles)
3014             (and (not (eq style 'parens))
3015                  ;; Use angles if no quoting is needed, or if parens would
3016                  ;; need quoting too.
3017                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3018                      (let ((tmp (concat fullname nil)))
3019                        (while (string-match "([^()]*)" tmp)
3020                          (aset tmp (match-beginning 0) ?-)
3021                          (aset tmp (1- (match-end 0)) ?-))
3022                        (string-match "[\\()]" tmp)))))
3023         (insert fullname)
3024         (goto-char (point-min))
3025         ;; Look for a character that cannot appear unquoted
3026         ;; according to RFC 822.
3027         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3028           ;; Quote fullname, escaping specials.
3029           (goto-char (point-min))
3030           (insert "\"")
3031           (while (re-search-forward "[\"\\]" nil 1)
3032             (replace-match "\\\\\\&" t))
3033           (insert "\""))
3034         (insert " <" login ">"))
3035        (t                               ; 'parens or default
3036         (insert login " (")
3037         (let ((fullname-start (point)))
3038           (insert fullname)
3039           (goto-char fullname-start)
3040           ;; RFC 822 says \ and nonmatching parentheses
3041           ;; must be escaped in comments.
3042           ;; Escape every instance of ()\ ...
3043           (while (re-search-forward "[()\\]" nil 1)
3044             (replace-match "\\\\\\&" t))
3045           ;; ... then undo escaping of matching parentheses,
3046           ;; including matching nested parentheses.
3047           (goto-char fullname-start)
3048           (while (re-search-forward
3049                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3050                   nil 1)
3051             (replace-match "\\1(\\3)" t)
3052             (goto-char fullname-start)))
3053         (insert ")")))
3054       (buffer-string))))
3055
3056 (defun message-make-sender ()
3057   "Return the \"real\" user address.
3058 This function tries to ignore all user modifications, and
3059 give as trustworthy answer as possible."
3060   (concat (user-login-name) "@" (system-name)))
3061
3062 (defun message-make-address ()
3063   "Make the address of the user."
3064   (or (message-user-mail-address)
3065       (concat (user-login-name) "@" (message-make-domain))))
3066
3067 (defun message-user-mail-address ()
3068   "Return the pertinent part of `user-mail-address'."
3069   (when user-mail-address
3070     (if (string-match " " user-mail-address)
3071         (nth 1 (mail-extract-address-components user-mail-address))
3072       user-mail-address)))
3073
3074 (defun message-make-fqdn ()
3075   "Return user's fully qualified domain name."
3076   (let ((system-name (system-name))
3077         (user-mail (message-user-mail-address)))
3078     (cond
3079      ((string-match "[^.]\\.[^.]" system-name)
3080       ;; `system-name' returned the right result.
3081       system-name)
3082      ;; Try `mail-host-address'.
3083      ((and (boundp 'mail-host-address)
3084            (stringp mail-host-address)
3085            (string-match "\\." mail-host-address))
3086       mail-host-address)
3087      ;; We try `user-mail-address' as a backup.
3088      ((and user-mail
3089            (string-match "\\." user-mail)
3090            (string-match "@\\(.*\\)\\'" user-mail))
3091       (match-string 1 user-mail))
3092      ;; Default to this bogus thing.
3093      (t
3094       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3095
3096 (defun message-make-host-name ()
3097   "Return the name of the host."
3098   (let ((fqdn (message-make-fqdn)))
3099     (string-match "^[^.]+\\." fqdn)
3100     (substring fqdn 0 (1- (match-end 0)))))
3101
3102 (defun message-make-domain ()
3103   "Return the domain name."
3104   (or mail-host-address
3105       (message-make-fqdn)))
3106
3107 (defun message-generate-headers (headers)
3108   "Prepare article HEADERS.
3109 Headers already prepared in the buffer are not modified."
3110   (save-restriction
3111     (message-narrow-to-headers)
3112     (let* ((Date (message-make-date))
3113            (Message-ID (message-make-message-id))
3114            (Organization (message-make-organization))
3115            (From (message-make-from))
3116            (Path (message-make-path))
3117            (Subject nil)
3118            (Newsgroups nil)
3119            (In-Reply-To (message-make-in-reply-to))
3120            (To nil)
3121            (Distribution (message-make-distribution))
3122            (Lines (message-make-lines))
3123            (User-Agent message-newsreader)
3124            (Expires (message-make-expires))
3125            (case-fold-search t)
3126            header value elem)
3127       ;; First we remove any old generated headers.
3128       (let ((headers message-deletable-headers))
3129         (unless (buffer-modified-p)
3130           (setq headers (delq 'Message-ID (copy-sequence headers))))
3131         (while headers
3132           (goto-char (point-min))
3133           (and (re-search-forward
3134                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3135                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3136                (message-delete-line))
3137           (pop headers)))
3138       ;; Go through all the required headers and see if they are in the
3139       ;; articles already.  If they are not, or are empty, they are
3140       ;; inserted automatically - except for Subject, Newsgroups and
3141       ;; Distribution.
3142       (while headers
3143         (goto-char (point-min))
3144         (setq elem (pop headers))
3145         (if (consp elem)
3146             (if (eq (car elem) 'optional)
3147                 (setq header (cdr elem))
3148               (setq header (car elem)))
3149           (setq header elem))
3150         (when (or (not (re-search-forward
3151                         (concat "^"
3152                                 (regexp-quote
3153                                  (downcase
3154                                   (if (stringp header)
3155                                       header
3156                                     (symbol-name header))))
3157                                 ":")
3158                         nil t))
3159                   (progn
3160                     ;; The header was found.  We insert a space after the
3161                     ;; colon, if there is none.
3162                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3163                     ;; Find out whether the header is empty...
3164                     (looking-at "[ \t]*\n[^ \t]")))
3165           ;; So we find out what value we should insert.
3166           (setq value
3167                 (cond
3168                  ((and (consp elem) (eq (car elem) 'optional))
3169                   ;; This is an optional header.  If the cdr of this
3170                   ;; is something that is nil, then we do not insert
3171                   ;; this header.
3172                   (setq header (cdr elem))
3173                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3174                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3175                  ((consp elem)
3176                   ;; The element is a cons.  Either the cdr is a
3177                   ;; string to be inserted verbatim, or it is a
3178                   ;; function, and we insert the value returned from
3179                   ;; this function.
3180                   (or (and (stringp (cdr elem)) (cdr elem))
3181                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3182                  ((and (boundp header) (symbol-value header))
3183                   ;; The element is a symbol.  We insert the value
3184                   ;; of this symbol, if any.
3185                   (symbol-value header))
3186                  ((not (message-check-element header))
3187                   ;; We couldn't generate a value for this header,
3188                   ;; so we just ask the user.
3189                   (read-from-minibuffer
3190                    (format "Empty header for %s; enter value: " header)))))
3191           ;; Finally insert the header.
3192           (when (and value
3193                      (not (equal value "")))
3194             (save-excursion
3195               (if (bolp)
3196                   (progn
3197                     ;; This header didn't exist, so we insert it.
3198                     (goto-char (point-max))
3199                     (insert (if (stringp header) header (symbol-name header))
3200                             ": " value "\n")
3201                     (forward-line -1))
3202                 ;; The value of this header was empty, so we clear
3203                 ;; totally and insert the new value.
3204                 (delete-region (point) (gnus-point-at-eol))
3205                 (insert value))
3206               ;; Add the deletable property to the headers that require it.
3207               (and (memq header message-deletable-headers)
3208                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3209                    (add-text-properties
3210                     (point) (match-end 0)
3211                     '(message-deletable t face italic) (current-buffer)))))))
3212       ;; Insert new Sender if the From is strange.
3213       (let ((from (message-fetch-field "from"))
3214             (sender (message-fetch-field "sender"))
3215             (secure-sender (message-make-sender)))
3216         (when (and from
3217                    (not (message-check-element 'sender))
3218                    (not (string=
3219                          (downcase
3220                           (cadr (mail-extract-address-components from)))
3221                          (downcase secure-sender)))
3222                    (or (null sender)
3223                        (not
3224                         (string=
3225                          (downcase
3226                           (cadr (mail-extract-address-components sender)))
3227                          (downcase secure-sender)))))
3228           (goto-char (point-min))
3229           ;; Rename any old Sender headers to Original-Sender.
3230           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3231             (beginning-of-line)
3232             (insert "Original-")
3233             (beginning-of-line))
3234           (when (or (message-news-p)
3235                     (string-match "@.+\\.." secure-sender))
3236             (insert "Sender: " secure-sender "\n")))))))
3237
3238 (defun message-insert-courtesy-copy ()
3239   "Insert a courtesy message in mail copies of combined messages."
3240   (let (newsgroups)
3241     (save-excursion
3242       (save-restriction
3243         (message-narrow-to-headers)
3244         (when (setq newsgroups (message-fetch-field "newsgroups"))
3245           (goto-char (point-max))
3246           (insert "Posted-To: " newsgroups "\n")))
3247       (forward-line 1)
3248       (when message-courtesy-message
3249         (cond
3250          ((string-match "%s" message-courtesy-message)
3251           (insert (format message-courtesy-message newsgroups)))
3252          (t
3253           (insert message-courtesy-message)))))))
3254
3255 ;;;
3256 ;;; Setting up a message buffer
3257 ;;;
3258
3259 (defun message-fill-address (header value)
3260   (save-restriction
3261     (narrow-to-region (point) (point))
3262     (insert (capitalize (symbol-name header))
3263             ": "
3264             (if (consp value) (car value) value)
3265             "\n")
3266     (narrow-to-region (point-min) (1- (point-max)))
3267     (let (quoted last)
3268       (goto-char (point-min))
3269       (while (not (eobp))
3270         (skip-chars-forward "^,\"" (point-max))
3271         (if (or (eq (char-after) ?,)
3272                 (eobp))
3273             (when (not quoted)
3274               (if (and (> (current-column) 78)
3275                        last)
3276                   (progn
3277                     (save-excursion
3278                       (goto-char last)
3279                       (insert "\n\t"))
3280                     (setq last (1+ (point))))
3281                 (setq last (1+ (point)))))
3282           (setq quoted (not quoted)))
3283         (unless (eobp)
3284           (forward-char 1))))
3285     (goto-char (point-max))
3286     (widen)
3287     (forward-line 1)))
3288
3289 (defun message-fill-header (header value)
3290   (let ((begin (point))
3291         (fill-column 78)
3292         (fill-prefix "\t"))
3293     (insert (capitalize (symbol-name header))
3294             ": "
3295             (if (consp value) (car value) value)
3296             "\n")
3297     (save-restriction
3298       (narrow-to-region begin (point))
3299       (fill-region-as-paragraph begin (point))
3300       ;; Tapdance around looong Message-IDs.
3301       (forward-line -1)
3302       (when (looking-at "[ \t]*$")
3303         (message-delete-line))
3304       (goto-char begin)
3305       (re-search-forward ":" nil t)
3306       (when (looking-at "\n[ \t]+")
3307         (replace-match " " t t))
3308       (goto-char (point-max)))))
3309
3310 (defun message-shorten-1 (list cut surplus)
3311   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3312   (setcdr (nthcdr (- cut 2) list)
3313           (nthcdr (+ (- cut 2) surplus 1) list)))
3314
3315 (defun message-shorten-references (header references)
3316   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3317 If folding is disallowed, also check that the REFERENCES are less
3318 than 988 characters long, and if they are not, trim them until they are."
3319   (let ((maxcount 31)
3320         (count 0)
3321         (cut 6)
3322         refs)
3323     (with-temp-buffer
3324       (insert references)
3325       (goto-char (point-min))
3326       ;; Cons a list of valid references.
3327       (while (re-search-forward "<[^>]+>" nil t)
3328         (push (match-string 0) refs))
3329       (setq refs (nreverse refs)
3330             count (length refs)))
3331
3332     ;; If the list has more than MAXCOUNT elements, trim it by
3333     ;; removing the CUTth element and the required number of
3334     ;; elements that follow.
3335     (when (> count maxcount)
3336       (let ((surplus (- count maxcount)))
3337         (message-shorten-1 refs cut surplus)
3338         (decf count surplus)))
3339
3340     ;; If folding is disallowed, make sure the total length (including
3341     ;; the spaces between) will be less than MAXSIZE characters.
3342     ;;
3343     ;; Only disallow folding for News messages. At this point the headers
3344     ;; have not been generated, thus we use message-this-is-news directly.
3345     (when (and message-this-is-news message-cater-to-broken-inn)
3346       (let ((maxsize 988)
3347             (totalsize (+ (apply #'+ (mapcar #'length refs))
3348                           (1- count)))
3349             (surplus 0)
3350             (ptr (nthcdr (1- cut) refs)))
3351         ;; Decide how many elements to cut off...
3352         (while (> totalsize maxsize)
3353           (decf totalsize (1+ (length (car ptr))))
3354           (incf surplus)
3355           (setq ptr (cdr ptr)))
3356         ;; ...and do it.
3357         (when (> surplus 0)
3358           (message-shorten-1 refs cut surplus))))
3359
3360     ;; Finally, collect the references back into a string and insert
3361     ;; it into the buffer.
3362     (let ((refstring (mapconcat #'identity refs " ")))
3363       (if (and message-this-is-news message-cater-to-broken-inn)
3364           (insert (capitalize (symbol-name header)) ": "
3365                   refstring "\n")
3366         (message-fill-header header refstring)))))
3367
3368 (defun message-position-point ()
3369   "Move point to where the user probably wants to find it."
3370   (message-narrow-to-headers)
3371   (cond
3372    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3373     (search-backward ":" )
3374     (widen)
3375     (forward-char 1)
3376     (if (eq (char-after) ? )
3377         (forward-char 1)
3378       (insert " ")))
3379    (t
3380     (goto-char (point-max))
3381     (widen)
3382     (forward-line 1)
3383     (unless (looking-at "$")
3384       (forward-line 2)))
3385    (sit-for 0)))
3386
3387 (defun message-buffer-name (type &optional to group)
3388   "Return a new (unique) buffer name based on TYPE and TO."
3389   (cond
3390    ;; Generate a new buffer name The Message Way.
3391    ((eq message-generate-new-buffers 'unique)
3392     (generate-new-buffer-name
3393      (concat "*" type
3394              (if to
3395                  (concat " to "
3396                          (or (car (mail-extract-address-components to))
3397                              to) "")
3398                "")
3399              (if (and group (not (string= group ""))) (concat " on " group) "")
3400              "*")))
3401    ;; Check whether `message-generate-new-buffers' is a function,
3402    ;; and if so, call it.
3403    ((message-functionp message-generate-new-buffers)
3404     (funcall message-generate-new-buffers type to group))
3405    ((eq message-generate-new-buffers 'unsent)
3406     (generate-new-buffer-name
3407      (concat "*unsent " type
3408              (if to
3409                  (concat " to "
3410                          (or (car (mail-extract-address-components to))
3411                              to) "")
3412                "")
3413              (if (and group (not (string= group ""))) (concat " on " group) "")
3414              "*")))
3415    ;; Use standard name.
3416    (t
3417     (format "*%s message*" type))))
3418
3419 (defun message-pop-to-buffer (name)
3420   "Pop to buffer NAME, and warn if it already exists and is modified."
3421   (let ((buffer (get-buffer name)))
3422     (if (and buffer
3423              (buffer-name buffer))
3424         (progn
3425           (set-buffer (pop-to-buffer buffer))
3426           (when (and (buffer-modified-p)
3427                      (not (y-or-n-p
3428                            "Message already being composed; erase? ")))
3429             (error "Message being composed")))
3430       (set-buffer (pop-to-buffer name)))
3431     (erase-buffer)
3432     (message-mode)))
3433
3434 (defun message-do-send-housekeeping ()
3435   "Kill old message buffers."
3436   ;; We might have sent this buffer already.  Delete it from the
3437   ;; list of buffers.
3438   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3439   (while (and message-max-buffers
3440               message-buffer-list
3441               (>= (length message-buffer-list) message-max-buffers))
3442     ;; Kill the oldest buffer -- unless it has been changed.
3443     (let ((buffer (pop message-buffer-list)))
3444       (when (and (buffer-name buffer)
3445                  (not (buffer-modified-p buffer)))
3446         (kill-buffer buffer))))
3447   ;; Rename the buffer.
3448   (if message-send-rename-function
3449       (funcall message-send-rename-function)
3450     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3451       (rename-buffer
3452        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3453   ;; Push the current buffer onto the list.
3454   (when message-max-buffers
3455     (setq message-buffer-list
3456           (nconc message-buffer-list (list (current-buffer))))))
3457
3458 (defvar mc-modes-alist)
3459 (defun message-setup (headers &optional replybuffer actions)
3460   (when (and (boundp 'mc-modes-alist)
3461              (not (assq 'message-mode mc-modes-alist)))
3462     (push '(message-mode (encrypt . mc-encrypt-message)
3463                          (sign . mc-sign-message))
3464           mc-modes-alist))
3465   (when actions
3466     (setq message-send-actions actions))
3467   (setq message-reply-buffer replybuffer)
3468   (goto-char (point-min))
3469   ;; Insert all the headers.
3470   (mail-header-format
3471    (let ((h headers)
3472          (alist message-header-format-alist))
3473      (while h
3474        (unless (assq (caar h) message-header-format-alist)
3475          (push (list (caar h)) alist))
3476        (pop h))
3477      alist)
3478    headers)
3479   (delete-region (point) (progn (forward-line -1) (point)))
3480   (when message-default-headers
3481     (insert message-default-headers)
3482     (or (bolp) (insert ?\n)))
3483   (put-text-property
3484    (point)
3485    (progn
3486      (insert mail-header-separator "\n")
3487      (1- (point)))
3488    'read-only nil)
3489   (forward-line -1)
3490   (when (message-news-p)
3491     (when message-default-news-headers
3492       (insert message-default-news-headers)
3493       (or (bolp) (insert ?\n)))
3494     (when message-generate-headers-first
3495       (message-generate-headers
3496        (delq 'Lines
3497              (delq 'Subject
3498                    (copy-sequence message-required-news-headers))))))
3499   (when (message-mail-p)
3500     (when message-default-mail-headers
3501       (insert message-default-mail-headers)
3502       (or (bolp) (insert ?\n)))
3503     (when message-generate-headers-first
3504       (message-generate-headers
3505        (delq 'Lines
3506              (delq 'Subject
3507                    (copy-sequence message-required-mail-headers))))))
3508   (run-hooks 'message-signature-setup-hook)
3509   (message-insert-signature)
3510   (save-restriction
3511     (message-narrow-to-headers)
3512     (run-hooks 'message-header-setup-hook))
3513   (set-buffer-modified-p nil)
3514   (setq buffer-undo-list nil)
3515   (run-hooks 'message-setup-hook)
3516   (message-position-point)
3517   (undo-boundary))
3518
3519 (defun message-set-auto-save-file-name ()
3520   "Associate the message buffer with a file in the drafts directory."
3521   (when message-auto-save-directory
3522     (if (gnus-alive-p)
3523         (setq message-draft-article
3524               (nndraft-request-associate-buffer "drafts"))
3525       (setq buffer-file-name (expand-file-name "*message*"
3526                                                message-auto-save-directory))
3527       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3528     (clear-visited-file-modtime)
3529     (setq buffer-file-coding-system message-draft-coding-system)))
3530
3531 (defun message-disassociate-draft ()
3532   "Disassociate the message buffer from the drafts directory."
3533   (when message-draft-article
3534     (nndraft-request-expire-articles
3535      (list message-draft-article) "drafts" nil t)))
3536
3537 (defun message-insert-headers ()
3538   "Generate the headers for the article."
3539   (interactive)
3540   (save-excursion
3541     (save-restriction
3542       (message-narrow-to-headers)
3543       (when (message-news-p)
3544         (message-generate-headers
3545          (delq 'Lines
3546                (delq 'Subject
3547                      (copy-sequence message-required-news-headers)))))
3548       (when (message-mail-p)
3549         (message-generate-headers
3550          (delq 'Lines
3551                (delq 'Subject
3552                      (copy-sequence message-required-mail-headers))))))))
3553
3554 \f
3555
3556 ;;;
3557 ;;; Commands for interfacing with message
3558 ;;;
3559
3560 ;;;###autoload
3561 (defun message-mail (&optional to subject
3562                                other-headers continue switch-function
3563                                yank-action send-actions)
3564   "Start editing a mail message to be sent.
3565 OTHER-HEADERS is an alist of header/value pairs."
3566   (interactive)
3567   (let ((message-this-is-mail t))
3568     (message-pop-to-buffer (message-buffer-name "mail" to))
3569     (message-setup
3570      (nconc
3571       `((To . ,(or to "")) (Subject . ,(or subject "")))
3572       (when other-headers other-headers)))))
3573
3574 ;;;###autoload
3575 (defun message-news (&optional newsgroups subject)
3576   "Start editing a news article to be sent."
3577   (interactive)
3578   (let ((message-this-is-news t))
3579     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3580     (message-setup `((Newsgroups . ,(or newsgroups ""))
3581                      (Subject . ,(or subject ""))))))
3582
3583 (defun message-get-reply-headers (wide &optional to-address)
3584   (let (follow-to mct never-mct from to cc reply-to ccalist)
3585     ;; Find all relevant headers we need.
3586     (setq from (message-fetch-field "from")
3587           to (message-fetch-field "to")
3588           cc (message-fetch-field "cc")
3589           mct (message-fetch-field "mail-copies-to")
3590           reply-to (message-fetch-field "reply-to"))
3591
3592     ;; Handle special values of Mail-Copies-To.
3593     (when mct
3594       (cond ((or (equal (downcase mct) "never")
3595                  (equal (downcase mct) "nobody"))
3596              (setq never-mct t)
3597              (setq mct nil))
3598             ((or (equal (downcase mct) "always")
3599                  (equal (downcase mct) "poster"))
3600              (setq mct (or reply-to from)))))
3601
3602     (if (or (not wide)
3603             to-address)
3604         (progn
3605           (setq follow-to (list (cons 'To (or to-address reply-to from))))
3606           (when (and wide mct)
3607             (push (cons 'Cc mct) follow-to)))
3608       (let (ccalist)
3609         (save-excursion
3610           (message-set-work-buffer)
3611           (unless never-mct
3612             (insert (or reply-to from "")))
3613           (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3614           (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3615           (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3616           (goto-char (point-min))
3617           (while (re-search-forward "[ \t]+" nil t)
3618             (replace-match " " t t))
3619           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3620           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3621             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3622                       (erase-buffer))))
3623           (goto-char (point-min))
3624           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3625           (when (eobp)
3626             (insert (or reply-to from "")))
3627           (setq ccalist
3628                 (mapcar
3629                  (lambda (addr)
3630                    (cons (mail-strip-quoted-names addr) addr))
3631                  (message-tokenize-header (buffer-string))))
3632           (let ((s ccalist))
3633             (while s
3634               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3635         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3636         (when ccalist
3637           (let ((ccs (cons 'Cc (mapconcat
3638                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3639             (when (string-match "^ +" (cdr ccs))
3640               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3641             (push ccs follow-to)))))
3642     follow-to))
3643
3644
3645 ;;;###autoload
3646 (defun message-reply (&optional to-address wide)
3647   "Start editing a reply to the article in the current buffer."
3648   (interactive)
3649   (let ((cur (current-buffer))
3650         from subject date reply-to to cc
3651         references message-id follow-to
3652         (inhibit-point-motion-hooks t)
3653         (message-this-is-mail t)
3654         gnus-warning)
3655     (save-restriction
3656       (message-narrow-to-head)
3657       ;; Allow customizations to have their say.
3658       (if (not wide)
3659           ;; This is a regular reply.
3660           (if (message-functionp message-reply-to-function)
3661               (setq follow-to (funcall message-reply-to-function)))
3662         ;; This is a followup.
3663         (if (message-functionp message-wide-reply-to-function)
3664             (save-excursion
3665               (setq follow-to
3666                     (funcall message-wide-reply-to-function)))))
3667       (setq message-id (message-fetch-field "message-id" t)
3668             references (message-fetch-field "references")
3669             date (message-fetch-field "date")
3670             from (message-fetch-field "from")
3671             subject (or (message-fetch-field "subject") "none"))
3672     ;; Remove any (buggy) Re:'s that are present and make a
3673     ;; proper one.
3674     (when (string-match message-subject-re-regexp subject)
3675       (setq subject (substring subject (match-end 0))))
3676     (setq subject (concat "Re: " subject))
3677
3678     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3679                (string-match "<[^>]+>" gnus-warning))
3680       (setq message-id (match-string 0 gnus-warning)))
3681
3682     (unless follow-to
3683       (setq follow-to (message-get-reply-headers wide to-address))))
3684
3685     (message-pop-to-buffer
3686      (message-buffer-name
3687       (if wide "wide reply" "reply") from
3688       (if wide to-address nil)))
3689
3690     (setq message-reply-headers
3691           (vector 0 subject from date message-id references 0 0 ""))
3692
3693     (message-setup
3694      `((Subject . ,subject)
3695        ,@follow-to
3696        ,@(if (or references message-id)
3697              `((References . ,(concat (or references "") (and references " ")
3698                                       (or message-id ""))))
3699            nil))
3700      cur)))
3701
3702 ;;;###autoload
3703 (defun message-wide-reply (&optional to-address)
3704   "Make a \"wide\" reply to the message in the current buffer."
3705   (interactive)
3706   (message-reply to-address t))
3707
3708 ;;;###autoload
3709 (defun message-followup (&optional to-newsgroups)
3710   "Follow up to the message in the current buffer.
3711 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3712   (interactive)
3713   (let ((cur (current-buffer))
3714         from subject date reply-to mct
3715         references message-id follow-to
3716         (inhibit-point-motion-hooks t)
3717         (message-this-is-news t)
3718         followup-to distribution newsgroups gnus-warning posted-to)
3719     (save-restriction
3720       (narrow-to-region
3721        (goto-char (point-min))
3722        (if (search-forward "\n\n" nil t)
3723            (1- (point))
3724          (point-max)))
3725       (when (message-functionp message-followup-to-function)
3726         (setq follow-to
3727               (funcall message-followup-to-function)))
3728       (setq from (message-fetch-field "from")
3729             date (message-fetch-field "date")
3730             subject (or (message-fetch-field "subject") "none")
3731             references (message-fetch-field "references")
3732             message-id (message-fetch-field "message-id" t)
3733             followup-to (message-fetch-field "followup-to")
3734             newsgroups (message-fetch-field "newsgroups")
3735             posted-to (message-fetch-field "posted-to")
3736             reply-to (message-fetch-field "reply-to")
3737             distribution (message-fetch-field "distribution")
3738             mct (message-fetch-field "mail-copies-to"))
3739       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3740                  (string-match "<[^>]+>" gnus-warning))
3741         (setq message-id (match-string 0 gnus-warning)))
3742       ;; Remove bogus distribution.
3743       (when (and (stringp distribution)
3744                  (let ((case-fold-search t))
3745                    (string-match "world" distribution)))
3746         (setq distribution nil))
3747       ;; Remove any (buggy) Re:'s that are present and make a
3748       ;; proper one.
3749       (when (string-match message-subject-re-regexp subject)
3750         (setq subject (substring subject (match-end 0))))
3751       (setq subject (concat "Re: " subject))
3752       (widen))
3753
3754     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3755
3756     (message-setup
3757      `((Subject . ,subject)
3758        ,@(cond
3759           (to-newsgroups
3760            (list (cons 'Newsgroups to-newsgroups)))
3761           (follow-to follow-to)
3762           ((and followup-to message-use-followup-to)
3763            (list
3764             (cond
3765              ((equal (downcase followup-to) "poster")
3766               (if (or (eq message-use-followup-to 'use)
3767                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3768 You should normally obey the Followup-To: header.
3769
3770 `Followup-To: poster' sends your response via e-mail instead of news.
3771
3772 A typical situation where `Followup-To: poster' is used is when the poster
3773 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3774                   (progn
3775                     (setq message-this-is-news nil)
3776                     (cons 'To (or reply-to from "")))
3777                 (cons 'Newsgroups newsgroups)))
3778              (t
3779               (if (or (equal followup-to newsgroups)
3780                       (not (eq message-use-followup-to 'ask))
3781                       (message-y-or-n-p
3782                        (concat "Obey Followup-To: " followup-to "? ") t "\
3783 You should normally obey the Followup-To: header.
3784
3785         `Followup-To: " followup-to "'
3786 directs your response to " (if (string-match "," followup-to)
3787                                "the specified newsgroups"
3788                              "that newsgroup only") ".
3789
3790 If a message is posted to several newsgroups, Followup-To is often
3791 used to direct the following discussion to one newsgroup only,
3792 because discussions that are spread over several newsgroup tend to
3793 be fragmented and very difficult to follow.
3794
3795 Also, some source/announcement newsgroups are not indented for discussion;
3796 responses here are directed to other newsgroups."))
3797                   (cons 'Newsgroups followup-to)
3798                 (cons 'Newsgroups newsgroups))))))
3799           (posted-to
3800            `((Newsgroups . ,posted-to)))
3801           (t
3802            `((Newsgroups . ,newsgroups))))
3803        ,@(and distribution (list (cons 'Distribution distribution)))
3804        ,@(if (or references message-id)
3805              `((References . ,(concat (or references "") (and references " ")
3806                                       (or message-id "")))))
3807        ,@(when (and mct
3808                     (not (or (equal (downcase mct) "never")
3809                              (equal (downcase mct) "nobody"))))
3810            (list (cons 'Cc (if (or (equal (downcase mct) "always")
3811                                    (equal (downcase mct) "poster"))
3812                                (or reply-to from "")
3813                              mct)))))
3814
3815      cur)
3816
3817     (setq message-reply-headers
3818           (vector 0 subject from date message-id references 0 0 ""))))
3819
3820
3821 ;;;###autoload
3822 (defun message-cancel-news (&optional arg)
3823   "Cancel an article you posted.
3824 If ARG, allow editing of the cancellation message."
3825   (interactive "P")
3826   (unless (message-news-p)
3827     (error "This is not a news article; canceling is impossible"))
3828   (when (yes-or-no-p "Do you really want to cancel this article? ")
3829     (let (from newsgroups message-id distribution buf sender)
3830       (save-excursion
3831         ;; Get header info from original article.
3832         (save-restriction
3833           (message-narrow-to-head)
3834           (setq from (message-fetch-field "from")
3835                 sender (message-fetch-field "sender")
3836                 newsgroups (message-fetch-field "newsgroups")
3837                 message-id (message-fetch-field "message-id" t)
3838                 distribution (message-fetch-field "distribution")))
3839         ;; Make sure that this article was written by the user.
3840         (unless (or (and sender
3841                          (string-equal
3842                           (downcase sender)
3843                           (downcase (message-make-sender))))
3844                     (string-equal
3845                      (downcase (cadr (mail-extract-address-components from)))
3846                      (downcase (cadr (mail-extract-address-components
3847                                       (message-make-from))))))
3848           (error "This article is not yours"))
3849         ;; Make control message.
3850         (if arg
3851             (message-news)
3852           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
3853         (erase-buffer)
3854         (insert "Newsgroups: " newsgroups "\n"
3855                 "From: " (message-make-from) "\n"
3856                 "Subject: cmsg cancel " message-id "\n"
3857                 "Control: cancel " message-id "\n"
3858                 (if distribution
3859                     (concat "Distribution: " distribution "\n")
3860                   "")
3861                 mail-header-separator "\n"
3862                 message-cancel-message)
3863         (run-hooks 'message-cancel-hook)
3864         (unless arg
3865           (message "Canceling your article...")
3866           (if (let ((message-syntax-checks
3867                      'dont-check-for-anything-just-trust-me))
3868                 (funcall message-send-news-function))
3869               (message "Canceling your article...done"))
3870           (kill-buffer buf))))))
3871
3872 ;;;###autoload
3873 (defun message-supersede ()
3874   "Start composing a message to supersede the current message.
3875 This is done simply by taking the old article and adding a Supersedes
3876 header line with the old Message-ID."
3877   (interactive)
3878   (let ((cur (current-buffer))
3879         (sender (message-fetch-field "sender"))
3880         (from (message-fetch-field "from")))
3881     ;; Check whether the user owns the article that is to be superseded.
3882     (unless (or (and sender
3883                      (string-equal
3884                       (downcase sender)
3885                       (downcase (message-make-sender))))
3886                 (string-equal
3887                  (downcase (cadr (mail-extract-address-components from)))
3888                  (downcase (cadr (mail-extract-address-components
3889                                   (message-make-from))))))
3890       (error "This article is not yours"))
3891     ;; Get a normal message buffer.
3892     (message-pop-to-buffer (message-buffer-name "supersede"))
3893     (insert-buffer-substring cur)
3894     (message-narrow-to-head)
3895     ;; Remove unwanted headers.
3896     (when message-ignored-supersedes-headers
3897       (message-remove-header message-ignored-supersedes-headers t))
3898     (goto-char (point-min))
3899     (if (not (re-search-forward "^Message-ID: " nil t))
3900         (error "No Message-ID in this article")
3901       (replace-match "Supersedes: " t t))
3902     (goto-char (point-max))
3903     (insert mail-header-separator)
3904     (widen)
3905     (forward-line 1)))
3906
3907 ;;;###autoload
3908 (defun message-recover ()
3909   "Reread contents of current buffer from its last auto-save file."
3910   (interactive)
3911   (let ((file-name (make-auto-save-file-name)))
3912     (cond ((save-window-excursion
3913              (if (not (eq system-type 'vax-vms))
3914                  (with-output-to-temp-buffer "*Directory*"
3915                    (with-current-buffer standard-output
3916                      (fundamental-mode)) ; for Emacs 20.4+
3917                    (buffer-disable-undo standard-output)
3918                    (let ((default-directory "/"))
3919                      (call-process
3920                       "ls" nil standard-output nil "-l" file-name))))
3921              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3922            (let ((buffer-read-only nil))
3923              (erase-buffer)
3924              (insert-file-contents file-name nil)))
3925           (t (error "message-recover cancelled")))))
3926
3927 ;;; Washing Subject:
3928
3929 (defun message-wash-subject (subject)
3930   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3931   (with-temp-buffer
3932     (insert-string subject)
3933     (goto-char (point-min))
3934     ;; strip Re/Fwd stuff off the beginning
3935     (while (re-search-forward
3936             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3937       (replace-match ""))
3938
3939     ;; and gnus-style forwards [foo@bar.com] subject
3940     (goto-char (point-min))
3941     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3942       (replace-match ""))
3943
3944     ;; and off the end
3945     (goto-char (point-max))
3946     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3947       (replace-match ""))
3948
3949     ;; and finally, any whitespace that was left-over
3950     (goto-char (point-min))
3951     (while (re-search-forward "^[ \t]+" nil t)
3952       (replace-match ""))
3953     (goto-char (point-max))
3954     (while (re-search-backward "[ \t]+$" nil t)
3955       (replace-match ""))
3956
3957     (buffer-string)))
3958
3959 ;;; Forwarding messages.
3960
3961 (defun message-forward-subject-author-subject (subject)
3962   "Generate a subject for a forwarded message.
3963 The form is: [Source] Subject, where if the original message was mail,
3964 Source is the sender, and if the original message was news, Source is
3965 the list of newsgroups is was posted to."
3966   (concat "["
3967           (or (message-fetch-field
3968                (if (message-news-p) "newsgroups" "from"))
3969               "(nowhere)")
3970           "] " subject))
3971
3972 (defun message-forward-subject-fwd (subject)
3973   "Generate a subject for a forwarded message.
3974 The form is: Fwd: Subject, where Subject is the original subject of
3975 the message."
3976   (concat "Fwd: " subject))
3977
3978 (defun message-make-forward-subject ()
3979   "Return a Subject header suitable for the message in the current buffer."
3980   (save-excursion
3981     (save-restriction
3982       (current-buffer)
3983       (message-narrow-to-head)
3984       (let ((funcs message-make-forward-subject-function)
3985             (subject (if message-wash-forwarded-subjects
3986                          (message-wash-subject
3987                           (or (message-fetch-field "Subject") ""))
3988                        (or (message-fetch-field "Subject") ""))))
3989         ;; Make sure funcs is a list.
3990         (and funcs
3991              (not (listp funcs))
3992              (setq funcs (list funcs)))
3993         ;; Apply funcs in order, passing subject generated by previous
3994         ;; func to the next one.
3995         (while funcs
3996           (when (message-functionp (car funcs))
3997             (setq subject (funcall (car funcs) subject)))
3998           (setq funcs (cdr funcs)))
3999         subject))))
4000
4001 ;;;###autoload
4002 (defun message-forward (&optional news)
4003   "Forward the current message via mail.
4004 Optional NEWS will use news to forward instead of mail."
4005   (interactive "P")
4006   (let* ((cur (current-buffer))
4007          (subject (if message-forward-show-mml
4008                       (message-make-forward-subject)
4009                     (mail-decode-encoded-word-string
4010                      (message-make-forward-subject))))
4011          art-beg)
4012     (if news
4013         (message-news nil subject)
4014       (message-mail nil subject))
4015     ;; Put point where we want it before inserting the forwarded
4016     ;; message.
4017     (if message-forward-before-signature
4018         (message-goto-body)
4019       (goto-char (point-max)))
4020     (if message-forward-as-mime
4021         (if message-forward-show-mml
4022             (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4023           (insert "\n\n<#part type=message/rfc822 disposition=inline"
4024                   " buffer=\"" (buffer-name cur) "\">\n"))
4025       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4026     (let ((b (point))
4027           e)
4028       (if message-forward-show-mml
4029           (insert-buffer-substring cur)
4030         (unless message-forward-as-mime
4031           (mml-insert-buffer cur)))
4032       (setq e (point))
4033       (if message-forward-as-mime
4034           (if message-forward-show-mml
4035               (insert "<#/mml>\n")
4036             (insert "<#/part>\n"))
4037         (insert "\n-------------------- End of forwarded message --------------------\n"))
4038       (when (and (or message-forward-show-mml
4039                      (not message-forward-as-mime))
4040              (not current-prefix-arg)
4041              message-forward-ignored-headers)
4042         (save-restriction
4043           (narrow-to-region b e)
4044           (goto-char b)
4045           (narrow-to-region (point) (or (search-forward "\n\n" nil t) (point)))
4046           (message-remove-header message-forward-ignored-headers t))))
4047     (message-position-point)))
4048
4049 ;;;###autoload
4050 (defun message-resend (address)
4051   "Resend the current article to ADDRESS."
4052   (interactive
4053    (list (message-read-from-minibuffer "Resend message to: ")))
4054   (message "Resending message to %s..." address)
4055   (save-excursion
4056     (let ((cur (current-buffer))
4057           beg)
4058       ;; We first set up a normal mail buffer.
4059       (set-buffer (get-buffer-create " *message resend*"))
4060       (erase-buffer)
4061       (message-setup `((To . ,address)))
4062       ;; Insert our usual headers.
4063       (message-generate-headers '(From Date To))
4064       (message-narrow-to-headers)
4065       ;; Rename them all to "Resent-*".
4066       (while (re-search-forward "^[A-Za-z]" nil t)
4067         (forward-char -1)
4068         (insert "Resent-"))
4069       (widen)
4070       (forward-line)
4071       (delete-region (point) (point-max))
4072       (setq beg (point))
4073       ;; Insert the message to be resent.
4074       (insert-buffer-substring cur)
4075       (goto-char (point-min))
4076       (search-forward "\n\n")
4077       (forward-char -1)
4078       (save-restriction
4079         (narrow-to-region beg (point))
4080         (message-remove-header message-ignored-resent-headers t)
4081         (goto-char (point-max)))
4082       (insert mail-header-separator)
4083       ;; Rename all old ("Also-")Resent headers.
4084       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4085         (beginning-of-line)
4086         (insert "Also-"))
4087       ;; Quote any "From " lines at the beginning.
4088       (goto-char beg)
4089       (when (looking-at "From ")
4090         (replace-match "X-From-Line: "))
4091       ;; Send it.
4092       (let ((message-inhibit-body-encoding t)
4093             message-required-mail-headers)
4094         (message-send-mail))
4095       (kill-buffer (current-buffer)))
4096     (message "Resending message to %s...done" address)))
4097
4098 ;;;###autoload
4099 (defun message-bounce ()
4100   "Re-mail the current message.
4101 This only makes sense if the current message is a bounce message than
4102 contains some mail you have written which has been bounced back to
4103 you."
4104   (interactive)
4105   (let ((handles (mm-dissect-buffer t))
4106         boundary)
4107     (message-pop-to-buffer (message-buffer-name "bounce"))
4108     (if (stringp (car handles))
4109         ;; This is a MIME bounce.
4110         (mm-insert-part (car (last handles)))
4111       ;; This is a non-MIME bounce, so we try to remove things
4112       ;; manually.
4113       (mm-insert-part handles)
4114       (undo-boundary)
4115       (goto-char (point-min))
4116       (search-forward "\n\n" nil t)
4117       (or (and (re-search-forward message-unsent-separator nil t)
4118                (forward-line 1))
4119           (re-search-forward "^Return-Path:.*\n" nil t))
4120       ;; We remove everything before the bounced mail.
4121       (delete-region
4122        (point-min)
4123        (if (re-search-forward "^[^ \n\t]+:" nil t)
4124            (match-beginning 0)
4125          (point))))
4126     (save-restriction
4127       (message-narrow-to-head)
4128       (message-remove-header message-ignored-bounced-headers t)
4129       (goto-char (point-max))
4130       (insert mail-header-separator))
4131     (message-position-point)))
4132
4133 ;;;
4134 ;;; Interactive entry points for new message buffers.
4135 ;;;
4136
4137 ;;;###autoload
4138 (defun message-mail-other-window (&optional to subject)
4139   "Like `message-mail' command, but display mail buffer in another window."
4140   (interactive)
4141   (let ((pop-up-windows t)
4142         (special-display-buffer-names nil)
4143         (special-display-regexps nil)
4144         (same-window-buffer-names nil)
4145         (same-window-regexps nil))
4146     (message-pop-to-buffer (message-buffer-name "mail" to)))
4147   (let ((message-this-is-mail t))
4148     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4149
4150 ;;;###autoload
4151 (defun message-mail-other-frame (&optional to subject)
4152   "Like `message-mail' command, but display mail buffer in another frame."
4153   (interactive)
4154   (let ((pop-up-frames t)
4155         (special-display-buffer-names nil)
4156         (special-display-regexps nil)
4157         (same-window-buffer-names nil)
4158         (same-window-regexps nil))
4159     (message-pop-to-buffer (message-buffer-name "mail" to)))
4160   (let ((message-this-is-mail t))
4161     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4162
4163 ;;;###autoload
4164 (defun message-news-other-window (&optional newsgroups subject)
4165   "Start editing a news article to be sent."
4166   (interactive)
4167   (let ((pop-up-windows t)
4168         (special-display-buffer-names nil)
4169         (special-display-regexps nil)
4170         (same-window-buffer-names nil)
4171         (same-window-regexps nil))
4172     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4173   (let ((message-this-is-news t))
4174     (message-setup `((Newsgroups . ,(or newsgroups ""))
4175                      (Subject . ,(or subject ""))))))
4176
4177 ;;;###autoload
4178 (defun message-news-other-frame (&optional newsgroups subject)
4179   "Start editing a news article to be sent."
4180   (interactive)
4181   (let ((pop-up-frames t)
4182         (special-display-buffer-names nil)
4183         (special-display-regexps nil)
4184         (same-window-buffer-names nil)
4185         (same-window-regexps nil))
4186     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4187   (let ((message-this-is-news t))
4188     (message-setup `((Newsgroups . ,(or newsgroups ""))
4189                      (Subject . ,(or subject ""))))))
4190
4191 ;;; underline.el
4192
4193 ;; This code should be moved to underline.el (from which it is stolen).
4194
4195 ;;;###autoload
4196 (defun bold-region (start end)
4197   "Bold all nonblank characters in the region.
4198 Works by overstriking characters.
4199 Called from program, takes two arguments START and END
4200 which specify the range to operate on."
4201   (interactive "r")
4202   (save-excursion
4203     (let ((end1 (make-marker)))
4204       (move-marker end1 (max start end))
4205       (goto-char (min start end))
4206       (while (< (point) end1)
4207         (or (looking-at "[_\^@- ]")
4208             (insert (char-after) "\b"))
4209         (forward-char 1)))))
4210
4211 ;;;###autoload
4212 (defun unbold-region (start end)
4213   "Remove all boldness (overstruck characters) in the region.
4214 Called from program, takes two arguments START and END
4215 which specify the range to operate on."
4216   (interactive "r")
4217   (save-excursion
4218     (let ((end1 (make-marker)))
4219       (move-marker end1 (max start end))
4220       (goto-char (min start end))
4221       (while (re-search-forward "\b" end1 t)
4222         (if (eq (char-after) (char-after (- (point) 2)))
4223             (delete-char -2))))))
4224
4225 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4226
4227 ;; Support for toolbar
4228 (when (string-match "XEmacs\\|Lucid" emacs-version)
4229   (require 'messagexmas))
4230
4231 ;;; Group name completion.
4232
4233 (defvar message-newgroups-header-regexp
4234   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4235   "Regexp that match headers that lists groups.")
4236
4237 (defun message-tab ()
4238   "Expand group names in Newsgroups and Followup-To headers.
4239 Do a `tab-to-tab-stop' if not in those headers."
4240   (interactive)
4241   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4242         (mail-abbrev-in-expansion-header-p))
4243       (message-expand-group)
4244     (tab-to-tab-stop)))
4245
4246 (defvar gnus-active-hashtb)
4247 (defun message-expand-group ()
4248   "Expand the group name under point."
4249   (let* ((b (save-excursion
4250               (save-restriction
4251                 (narrow-to-region
4252                  (save-excursion
4253                    (beginning-of-line)
4254                    (skip-chars-forward "^:")
4255                    (1+ (point)))
4256                  (point))
4257                 (skip-chars-backward "^, \t\n") (point))))
4258          (completion-ignore-case t)
4259          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4260                                             (point))))
4261          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4262          (completions (all-completions string hashtb))
4263          comp)
4264     (delete-region b (point))
4265     (cond
4266      ((= (length completions) 1)
4267       (if (string= (car completions) string)
4268           (progn
4269             (insert string)
4270             (message "Only matching group"))
4271         (insert (car completions))))
4272      ((and (setq comp (try-completion string hashtb))
4273            (not (string= comp string)))
4274       (insert comp))
4275      (t
4276       (insert string)
4277       (if (not comp)
4278           (message "No matching groups")
4279         (save-selected-window
4280           (pop-to-buffer "*Completions*")
4281           (buffer-disable-undo)
4282           (let ((buffer-read-only nil))
4283             (erase-buffer)
4284             (let ((standard-output (current-buffer)))
4285               (display-completion-list (sort completions 'string<)))
4286             (goto-char (point-min))
4287             (delete-region (point) (progn (forward-line 3) (point))))))))))
4288
4289 ;;; Help stuff.
4290
4291 (defun message-talkative-question (ask question show &rest text)
4292   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4293 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4294 The following arguments may contain lists of values."
4295   (if (and show
4296            (setq text (message-flatten-list text)))
4297       (save-window-excursion
4298         (save-excursion
4299           (with-output-to-temp-buffer " *MESSAGE information message*"
4300             (set-buffer " *MESSAGE information message*")
4301             (fundamental-mode)          ; for Emacs 20.4+
4302             (mapcar 'princ text)
4303             (goto-char (point-min))))
4304         (funcall ask question))
4305     (funcall ask question)))
4306
4307 (defun message-flatten-list (list)
4308   "Return a new, flat list that contains all elements of LIST.
4309
4310 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4311 => (1 2 3 4 5 6 7)"
4312   (cond ((consp list)
4313          (apply 'append (mapcar 'message-flatten-list list)))
4314         (list
4315          (list list))))
4316
4317 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4318   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4319 Then clone the local variables and values from the old buffer to the
4320 new one, cloning only the locals having a substring matching the
4321 regexp varstr."
4322   (let ((oldbuf (current-buffer)))
4323     (save-excursion
4324       (set-buffer (generate-new-buffer name))
4325       (message-clone-locals oldbuf varstr)
4326       (current-buffer))))
4327
4328 (defun message-clone-locals (buffer &optional varstr)
4329   "Clone the local variables from BUFFER to the current buffer."
4330   (let ((locals (save-excursion
4331                   (set-buffer buffer)
4332                   (buffer-local-variables)))
4333         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4334     (mapcar
4335      (lambda (local)
4336        (when (and (consp local)
4337                   (car local)
4338                   (string-match regexp (symbol-name (car local)))
4339                   (or (null varstr)
4340                       (string-match varstr (symbol-name (car local)))))
4341          (ignore-errors
4342            (set (make-local-variable (car local))
4343                 (cdr local)))))
4344      locals)))
4345
4346 ;;; Miscellaneous functions
4347
4348 ;; stolen (and renamed) from nnheader.el
4349 (defun message-replace-chars-in-string (string from to)
4350   "Replace characters in STRING from FROM to TO."
4351   (let ((string (substring string 0))   ;Copy string.
4352         (len (length string))
4353         (idx 0))
4354     ;; Replace all occurrences of FROM with TO.
4355     (while (< idx len)
4356       (when (= (aref string idx) from)
4357         (aset string idx to))
4358       (setq idx (1+ idx)))
4359     string))
4360
4361 ;;;
4362 ;;; MIME functions
4363 ;;;
4364
4365 (defvar message-inhibit-body-encoding nil)
4366
4367 (defun message-encode-message-body ()
4368   (unless message-inhibit-body-encoding 
4369     (let ((mail-parse-charset (or mail-parse-charset
4370                                   message-default-charset))
4371           (case-fold-search t)
4372           lines content-type-p)
4373       (message-goto-body)
4374       (save-restriction
4375         (narrow-to-region (point) (point-max))
4376         (let ((new (mml-generate-mime)))
4377           (when new
4378             (delete-region (point-min) (point-max))
4379             (insert new)
4380             (goto-char (point-min))
4381             (if (eq (aref new 0) ?\n)
4382                 (delete-char 1)
4383               (search-forward "\n\n")
4384               (setq lines (buffer-substring (point-min) (1- (point))))
4385               (delete-region (point-min) (point))))))
4386       (save-restriction
4387         (message-narrow-to-headers-or-head)
4388         (message-remove-header "Mime-Version")
4389         (goto-char (point-max))
4390         (insert "MIME-Version: 1.0\n")
4391         (when lines
4392           (insert lines))
4393         (setq content-type-p
4394               (re-search-backward "^Content-Type:" nil t)))
4395       (save-restriction
4396         (message-narrow-to-headers-or-head)
4397         (message-remove-first-header "Content-Type")
4398         (message-remove-first-header "Content-Transfer-Encoding"))
4399       ;; We always make sure that the message has a Content-Type header.
4400       ;; This is because some broken MTAs and MUAs get awfully confused
4401       ;; when confronted with a message with a MIME-Version header and
4402       ;; without a Content-Type header.  For instance, Solaris'
4403       ;; /usr/bin/mail.
4404       (unless content-type-p
4405         (goto-char (point-min))
4406         (re-search-forward "^MIME-Version:")
4407         (forward-line 1)
4408         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4409
4410 (defun message-read-from-minibuffer (prompt)
4411   "Read from the minibuffer while providing abbrev expansion."
4412   (if (fboundp 'mail-abbrevs-setup)
4413       (let ((mail-abbrev-mode-regexp "")
4414             (minibuffer-setup-hook 'mail-abbrevs-setup))
4415         (read-from-minibuffer prompt)))
4416   (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4417     (read-string prompt)))
4418
4419 (provide 'message)
4420
4421 (run-hooks 'message-load-hook)
4422
4423 ;; Local Variables:
4424 ;; coding: iso-8859-1
4425 ;; End:
4426
4427 ;;; message.el ends here