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