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