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