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