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