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