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