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