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