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