6d2c19ed2c4f00bfcf8e8ca85689ce885a658328
[gnus] / 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 newsgroups."
174   :group 'message-news)
175
176 (defcustom message-required-news-headers
177   '(From Newsgroups Subject Date Message-ID
178          (optional . Organization) Lines
179          (optional . User-Agent))
180   "*Headers to be generated or prompted for when posting an article.
181 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
182 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
183 User-Agent are optional.  If don't you want message to insert some
184 header, remove it from this list."
185   :group 'message-news
186   :group 'message-headers
187   :type '(repeat sexp))
188
189 (defcustom message-required-mail-headers
190   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
191          (optional . User-Agent))
192   "*Headers to be generated or prompted for when mailing a message.
193 RFC822 required that From, Date, To, Subject and Message-ID be
194 included.  Organization, Lines and User-Agent are optional."
195   :group 'message-mail
196   :group 'message-headers
197   :type '(repeat sexp))
198
199 (defcustom message-deletable-headers '(Message-ID Date Lines)
200   "Headers to be deleted if they already exist and were generated by message previously."
201   :group 'message-headers
202   :type 'sexp)
203
204 (defcustom message-ignored-news-headers
205   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:"
206   "*Regexp of headers to be removed unconditionally before posting."
207   :group 'message-news
208   :group 'message-headers
209   :type 'regexp)
210
211 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
212   "*Regexp of headers to be removed unconditionally before mailing."
213   :group 'message-mail
214   :group 'message-headers
215   :type 'regexp)
216
217 (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:"
218   "*Header lines matching this regexp will be deleted before posting.
219 It's best to delete old Path and Date headers before posting to avoid
220 any confusion."
221   :group 'message-interface
222   :type 'regexp)
223
224 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
225   "*Regexp matching \"Re: \" in the subject line."
226   :group 'message-various
227   :type 'regexp)
228
229 ;;;###autoload
230 (defcustom message-signature-separator "^-- *$"
231   "Regexp matching the signature separator."
232   :type 'regexp
233   :group 'message-various)
234
235 (defcustom message-elide-elipsis "\n[...]\n\n"
236   "*The string which is inserted for elided text."
237   :type 'string
238   :group 'message-various)
239
240 (defcustom message-interactive nil
241   "Non-nil means when sending a message wait for and display errors.
242 nil means let mailer mail back a message to report errors."
243   :group 'message-sending
244   :group 'message-mail
245   :type 'boolean)
246
247 (defcustom message-generate-new-buffers 'unique
248   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
249 If this is a function, call that function with three parameters:  The type,
250 the to address and the group name.  (Any of these may be nil.)  The function
251 should return the new buffer name."
252   :group 'message-buffers
253   :type '(choice (const :tag "off" nil)
254                  (const :tag "unique" unique)
255                  (const :tag "unsent" unsent)
256                  (function fun)))
257
258 (defcustom message-kill-buffer-on-exit nil
259   "*Non-nil means that the message buffer will be killed after sending a message."
260   :group 'message-buffers
261   :type 'boolean)
262
263 (defvar gnus-local-organization)
264 (defcustom message-user-organization
265   (or (and (boundp 'gnus-local-organization)
266            (stringp gnus-local-organization)
267            gnus-local-organization)
268       (getenv "ORGANIZATION")
269       t)
270   "*String to be used as an Organization header.
271 If t, use `message-user-organization-file'."
272   :group 'message-headers
273   :type '(choice string
274                  (const :tag "consult file" t)))
275
276 ;;;###autoload
277 (defcustom message-user-organization-file "/usr/lib/news/organization"
278   "*Local news organization file."
279   :type 'file
280   :group 'message-headers)
281
282 (defcustom message-make-forward-subject-function
283   'message-forward-subject-author-subject
284  "*A list of functions that are called to generate a subject header for forwarded messages.
285 The subject generated by the previous function is passed into each
286 successive function.
287
288 The provided functions are:
289
290 * message-forward-subject-author-subject (Source of article (author or
291       newsgroup)), in brackets followed by the subject
292 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
293       to it."
294  :group 'message-forwarding
295  :type '(radio (function-item message-forward-subject-author-subject)
296                (function-item message-forward-subject-fwd)))
297
298 (defcustom message-wash-forwarded-subjects nil
299   "*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."
300   :group 'message-forwarding
301   :type 'boolean)
302
303 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
304   "*All headers that match this regexp will be deleted when resending a message."
305   :group 'message-interface
306   :type 'regexp)
307
308
309 (defcustom message-forward-ignored-headers nil
310   "*All headers that match this regexp will be deleted when forwarding a message."
311   :group 'message-forwarding
312   :type '(choice (const :tag "None" nil)
313                  regexp))
314
315 (defcustom message-ignored-cited-headers "."
316   "*Delete these headers from the messages you yank."
317   :group 'message-insertion
318   :type 'regexp)
319
320 (defcustom message-cancel-message "I am canceling my own article."
321   "Message to be inserted in the cancel message."
322   :group 'message-interface
323   :type 'string)
324
325 ;; Useful to set in site-init.el
326 ;;;###autoload
327 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
328   "Function to call to send the current buffer as mail.
329 The headers should be delimited by a line whose contents match the
330 variable `mail-header-separator'.
331
332 Valid values include `message-send-mail-with-sendmail' (the default),
333 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
334 `smtpmail-send-it'."
335   :type '(radio (function-item message-send-mail-with-sendmail)
336                 (function-item message-send-mail-with-mh)
337                 (function-item message-send-mail-with-qmail)
338                 (function-item smtpmail-send-it)
339                 (function :tag "Other"))
340   :group 'message-sending
341   :group 'message-mail)
342
343 (defcustom message-send-news-function 'message-send-news
344   "Function to call to send the current buffer as news.
345 The headers should be delimited by a line whose contents match the
346 variable `mail-header-separator'."
347   :group 'message-sending
348   :group 'message-news
349   :type 'function)
350
351 (defcustom message-reply-to-function nil
352   "Function that should return a list of headers.
353 This function should pick out addresses from the To, Cc, and From headers
354 and respond with new To and Cc headers."
355   :group 'message-interface
356   :type 'function)
357
358 (defcustom message-wide-reply-to-function nil
359   "Function that should return a list of headers.
360 This function should pick out addresses from the To, Cc, and From headers
361 and respond with new To and Cc headers."
362   :group 'message-interface
363   :type 'function)
364
365 (defcustom message-followup-to-function nil
366   "Function that should return a list of headers.
367 This function should pick out addresses from the To, Cc, and From headers
368 and respond with new To and Cc headers."
369   :group 'message-interface
370   :type 'function)
371
372 (defcustom message-use-followup-to 'ask
373   "*Specifies what to do with Followup-To header.
374 If nil, always ignore the header.  If it is t, use its value, but
375 query before using the \"poster\" value.  If it is the symbol `ask',
376 always query the user whether to use the value.  If it is the symbol
377 `use', always use the value."
378   :group 'message-interface
379   :type '(choice (const :tag "ignore" nil)
380                  (const use)
381                  (const ask)))
382
383 ;; stuff relating to broken sendmail in MMDF
384 (defcustom message-sendmail-f-is-evil nil
385   "*Non-nil means that \"-f username\" should not be added to the sendmail
386 command line, because it is even more evil than leaving it out."
387   :group 'message-sending
388   :type 'boolean)
389
390 ;; qmail-related stuff
391 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
392   "Location of the qmail-inject program."
393   :group 'message-sending
394   :type 'file)
395
396 (defcustom message-qmail-inject-args nil
397   "Arguments passed to qmail-inject programs.
398 This should be a list of strings, one string for each argument.
399
400 For e.g., if you wish to set the envelope sender address so that bounces
401 go to the right place or to deal with listserv's usage of that address, you
402 might set this variable to '(\"-f\" \"you@some.where\")."
403   :group 'message-sending
404   :type '(repeat string))
405
406 (defvar gnus-post-method)
407 (defvar gnus-select-method)
408 (defcustom message-post-method
409   (cond ((and (boundp 'gnus-post-method)
410               (listp gnus-post-method)
411               gnus-post-method)
412          gnus-post-method)
413         ((boundp 'gnus-select-method)
414          gnus-select-method)
415         (t '(nnspool "")))
416   "*Method used to post news.
417 Note that when posting from inside Gnus, for instance, this
418 variable isn't used."
419   :group 'message-news
420   :group 'message-sending
421   ;; This should be the `gnus-select-method' widget, but that might
422   ;; create a dependence to `gnus.el'.
423   :type 'sexp)
424
425 (defcustom message-generate-headers-first nil
426   "*If non-nil, generate all possible headers before composing."
427   :group 'message-headers
428   :type 'boolean)
429
430 (defcustom message-setup-hook nil
431   "Normal hook, run each time a new outgoing message is initialized.
432 The function `message-setup' runs this hook."
433   :group 'message-various
434   :type 'hook)
435
436 (defcustom message-cancel-hook nil
437   "Hook run when cancelling articles."
438   :group 'message-various
439   :type 'hook)
440
441 (defcustom message-signature-setup-hook nil
442   "Normal hook, run each time a new outgoing message is initialized.
443 It is run after the headers have been inserted and before
444 the signature is inserted."
445   :group 'message-various
446   :type 'hook)
447
448 (defcustom message-mode-hook nil
449   "Hook run in message mode buffers."
450   :group 'message-various
451   :type 'hook)
452
453 (defcustom message-header-hook nil
454   "Hook run in a message mode buffer narrowed to the headers."
455   :group 'message-various
456   :type 'hook)
457
458 (defcustom message-header-setup-hook nil
459   "Hook called narrowed to the headers when setting up a message buffer."
460   :group 'message-various
461   :type 'hook)
462
463 ;;;###autoload
464 (defcustom message-citation-line-function 'message-insert-citation-line
465   "*Function called to insert the \"Whomever writes:\" line."
466   :type 'function
467   :group 'message-insertion)
468
469 ;;;###autoload
470 (defcustom message-yank-prefix "> "
471   "*Prefix inserted on the lines of yanked messages."
472   :type 'string
473   :group 'message-insertion)
474
475 (defcustom message-indentation-spaces 3
476   "*Number of spaces to insert at the beginning of each cited line.
477 Used by `message-yank-original' via `message-yank-cite'."
478   :group 'message-insertion
479   :type 'integer)
480
481 ;;;###autoload
482 (defcustom message-cite-function 'message-cite-original
483   "*Function for citing an original message.
484 Predefined functions include `message-cite-original' and
485 `message-cite-original-without-signature'.
486 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
487   :type '(radio (function-item message-cite-original)
488                 (function-item message-cite-original-without-signature)
489                 (function-item sc-cite-original)
490                 (function :tag "Other"))
491   :group 'message-insertion)
492
493 ;;;###autoload
494 (defcustom message-indent-citation-function 'message-indent-citation
495   "*Function for modifying a citation just inserted in the mail buffer.
496 This can also be a list of functions.  Each function can find the
497 citation between (point) and (mark t).  And each function should leave
498 point and mark around the citation text as modified."
499   :type 'function
500   :group 'message-insertion)
501
502 (defvar message-abbrevs-loaded nil)
503
504 ;;;###autoload
505 (defcustom message-signature t
506   "*String to be inserted at the end of the message buffer.
507 If t, the `message-signature-file' file will be inserted instead.
508 If a function, the result from the function will be used instead.
509 If a form, the result from the form will be used instead."
510   :type 'sexp
511   :group 'message-insertion)
512
513 ;;;###autoload
514 (defcustom message-signature-file "~/.signature"
515   "*File containing the text inserted at end of message buffer."
516   :type 'file
517   :group 'message-insertion)
518
519 (defcustom message-distribution-function nil
520   "*Function called to return a Distribution header."
521   :group 'message-news
522   :group 'message-headers
523   :type 'function)
524
525 (defcustom message-expires 14
526   "Number of days before your article expires."
527   :group 'message-news
528   :group 'message-headers
529   :link '(custom-manual "(message)News Headers")
530   :type 'integer)
531
532 (defcustom message-user-path nil
533   "If nil, use the NNTP server name in the Path header.
534 If stringp, use this; if non-nil, use no host name (user name only)."
535   :group 'message-news
536   :group 'message-headers
537   :link '(custom-manual "(message)News Headers")
538   :type '(choice (const :tag "nntp" nil)
539                  (string :tag "name")
540                  (sexp :tag "none" :format "%t" t)))
541
542 (defvar message-reply-buffer nil)
543 (defvar message-reply-headers nil)
544 (defvar message-newsreader nil)
545 (defvar message-mailer nil)
546 (defvar message-sent-message-via nil)
547 (defvar message-checksum nil)
548 (defvar message-send-actions nil
549   "A list of actions to be performed upon successful sending of a message.")
550 (defvar message-exit-actions nil
551   "A list of actions to be performed upon exiting after sending a message.")
552 (defvar message-kill-actions nil
553   "A list of actions to be performed before killing a message buffer.")
554 (defvar message-postpone-actions nil
555   "A list of actions to be performed after postponing a message.")
556
557 (define-widget 'message-header-lines 'text
558   "All header lines must be LFD terminated."
559   :format "%t:%n%v"
560   :valid-regexp "^\\'"
561   :error "All header lines must be newline terminated")
562
563 (defcustom message-default-headers ""
564   "*A string containing header lines to be inserted in outgoing messages.
565 It is inserted before you edit the message, so you can edit or delete
566 these lines."
567   :group 'message-headers
568   :type 'message-header-lines)
569
570 (defcustom message-default-mail-headers ""
571   "*A string of header lines to be inserted in outgoing mails."
572   :group 'message-headers
573   :group 'message-mail
574   :type 'message-header-lines)
575
576 (defcustom message-default-news-headers ""
577   "*A string of header lines to be inserted in outgoing news
578 articles."
579   :group 'message-headers
580   :group 'message-news
581   :type 'message-header-lines)
582
583 ;; Note: could use /usr/ucb/mail instead of sendmail;
584 ;; options -t, and -v if not interactive.
585 (defcustom message-mailer-swallows-blank-line
586   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
587                          system-configuration)
588            (file-readable-p "/etc/sendmail.cf")
589            (let ((buffer (get-buffer-create " *temp*")))
590              (unwind-protect
591                  (save-excursion
592                    (set-buffer buffer)
593                    (insert-file-contents "/etc/sendmail.cf")
594                    (goto-char (point-min))
595                    (let ((case-fold-search nil))
596                      (re-search-forward "^OR\\>" nil t)))
597                (kill-buffer buffer))))
598       ;; According to RFC822, "The field-name must be composed of printable
599       ;; ASCII characters (i. e., characters that have decimal values between
600       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
601       ;; space, or colon.
602       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
603   "*Set this non-nil if the system's mailer runs the header and body together.
604 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
605 The value should be an expression to test whether the problem will
606 actually occur."
607   :group 'message-sending
608   :type 'sexp)
609
610 ;; Ignore errors in case this is used in Emacs 19.
611 ;; Don't use ignore-errors because this is copied into loaddefs.el.
612 ;;;###autoload
613 (ignore-errors
614   (define-mail-user-agent 'message-user-agent
615     'message-mail 'message-send-and-exit
616     'message-kill-buffer 'message-send-hook))
617
618 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
619   "If non-nil, delete the deletable headers before feeding to mh.")
620
621 (defvar message-send-method-alist
622   '((news message-news-p message-send-via-news)
623     (mail message-mail-p message-send-via-mail))
624   "Alist of ways to send outgoing messages.
625 Each element has the form
626
627   \(TYPE PREDICATE FUNCTION)
628
629 where TYPE is a symbol that names the method; PREDICATE is a function
630 called without any parameters to determine whether the message is
631 a message of type TYPE; and FUNCTION is a function to be called if
632 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
633 the prefix.")
634
635 (defvar message-mail-alias-type 'abbrev
636   "*What alias expansion type to use in Message buffers.
637 The default is `abbrev', which uses mailabbrev.  nil switches
638 mail aliases off.")
639
640 (defcustom message-auto-save-directory
641   (nnheader-concat message-directory "drafts/")
642   "*Directory where Message auto-saves buffers if Gnus isn't running.
643 If nil, Message won't auto-save."
644   :group 'message-buffers
645   :type 'directory)
646
647 (defcustom message-buffer-naming-style 'unique
648   "*The way new message buffers are named.
649 Valid valued are `unique' and `unsent'."
650   :group 'message-buffers
651   :type '(choice (const :tag "unique" unique)
652                  (const :tag "unsent" unsent)))
653
654 (defcustom message-default-charset nil
655   "Default charset used in non-MULE XEmacsen."
656   :group 'message
657   :type 'symbol)
658
659 (defcustom message-dont-reply-to-names rmail-dont-reply-to-names
660   "*A regexp specifying names to prune when doing wide replies.
661 A value of nil means exclude your own name only."
662   :group 'message
663   :type '(choice (const :tag "Yourself" nil)
664                  regexp))
665
666 ;;; Internal variables.
667 ;;; Well, not really internal.
668
669 (defvar message-mode-syntax-table
670   (let ((table (copy-syntax-table text-mode-syntax-table)))
671     (modify-syntax-entry ?% ". " table)
672     (modify-syntax-entry ?> ". " table)
673     (modify-syntax-entry ?< ". " table)
674     table)
675   "Syntax table used while in Message mode.")
676
677 (defvar message-mode-abbrev-table text-mode-abbrev-table
678   "Abbrev table used in Message mode buffers.
679 Defaults to `text-mode-abbrev-table'.")
680 (defgroup message-headers nil
681   "Message headers."
682   :link '(custom-manual "(message)Variables")
683   :group 'message)
684
685 (defface message-header-to-face
686   '((((class color)
687       (background dark))
688      (:foreground "green2" :bold t))
689     (((class color)
690       (background light))
691      (:foreground "MidnightBlue" :bold t))
692     (t
693      (:bold t :italic t)))
694   "Face used for displaying From headers."
695   :group 'message-faces)
696
697 (defface message-header-cc-face
698   '((((class color)
699       (background dark))
700      (:foreground "green4" :bold t))
701     (((class color)
702       (background light))
703      (:foreground "MidnightBlue"))
704     (t
705      (:bold t)))
706   "Face used for displaying Cc headers."
707   :group 'message-faces)
708
709 (defface message-header-subject-face
710   '((((class color)
711       (background dark))
712      (:foreground "green3"))
713     (((class color)
714       (background light))
715      (:foreground "navy blue" :bold t))
716     (t
717      (:bold t)))
718   "Face used for displaying subject headers."
719   :group 'message-faces)
720
721 (defface message-header-newsgroups-face
722   '((((class color)
723       (background dark))
724      (:foreground "yellow" :bold t :italic t))
725     (((class color)
726       (background light))
727      (:foreground "blue4" :bold t :italic t))
728     (t
729      (:bold t :italic t)))
730   "Face used for displaying newsgroups headers."
731   :group 'message-faces)
732
733 (defface message-header-other-face
734   '((((class color)
735       (background dark))
736      (:foreground "#b00000"))
737     (((class color)
738       (background light))
739      (:foreground "steel blue"))
740     (t
741      (:bold t :italic t)))
742   "Face used for displaying newsgroups headers."
743   :group 'message-faces)
744
745 (defface message-header-name-face
746   '((((class color)
747       (background dark))
748      (:foreground "DarkGreen"))
749     (((class color)
750       (background light))
751      (:foreground "cornflower blue"))
752     (t
753      (:bold t)))
754   "Face used for displaying header names."
755   :group 'message-faces)
756
757 (defface message-header-xheader-face
758   '((((class color)
759       (background dark))
760      (:foreground "blue"))
761     (((class color)
762       (background light))
763      (:foreground "blue"))
764     (t
765      (:bold t)))
766   "Face used for displaying X-Header headers."
767   :group 'message-faces)
768
769 (defface message-separator-face
770   '((((class color)
771       (background dark))
772      (:foreground "blue3"))
773     (((class color)
774       (background light))
775      (:foreground "brown"))
776     (t
777      (:bold t)))
778   "Face used for displaying the separator."
779   :group 'message-faces)
780
781 (defface message-cited-text-face
782   '((((class color)
783       (background dark))
784      (:foreground "red"))
785     (((class color)
786       (background light))
787      (:foreground "red"))
788     (t
789      (:bold t)))
790   "Face used for displaying cited text names."
791   :group 'message-faces)
792
793 (defface message-mml-face
794   '((((class color)
795       (background dark))
796      (:foreground "ForestGreen"))
797     (((class color)
798       (background light))
799      (:foreground "ForestGreen"))
800     (t
801      (:bold t)))
802   "Face used for displaying MML."
803   :group 'message-faces)
804
805 (defvar message-font-lock-keywords
806   (let* ((cite-prefix "A-Za-z")
807          (cite-suffix (concat cite-prefix "0-9_.@-"))
808          (content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)"))
809     `((,(concat "^\\([Tt]o:\\)" content)
810        (1 'message-header-name-face)
811        (2 'message-header-to-face nil t))
812       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
813        (1 'message-header-name-face)
814        (2 'message-header-cc-face nil t))
815       (,(concat "^\\([Ss]ubject:\\)" content)
816        (1 'message-header-name-face)
817        (2 'message-header-subject-face nil t))
818       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
819        (1 'message-header-name-face)
820        (2 'message-header-newsgroups-face nil t))
821       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
822        (1 'message-header-name-face)
823        (2 'message-header-other-face nil t))
824       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
825        (1 'message-header-name-face)
826        (2 'message-header-name-face))
827       ,@(if (and mail-header-separator
828                  (not (equal mail-header-separator "")))
829             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
830                1 'message-separator-face))
831           nil)
832       (,(concat "^[ \t]*"
833                 "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
834                 "[:>|}].*")
835        (0 'message-cited-text-face))
836       ("<#/?\\(multipart\\|part\\|external\\).*>"
837        (0 'message-mml-face))))
838   "Additional expressions to highlight in Message mode.")
839
840 ;; XEmacs does it like this.  For Emacs, we have to set the
841 ;; `font-lock-defaults' buffer-local variable.
842 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
843
844 (defvar message-face-alist
845   '((bold . bold-region)
846     (underline . underline-region)
847     (default . (lambda (b e)
848                  (unbold-region b e)
849                  (ununderline-region b e))))
850   "Alist of mail and news faces for facemenu.
851 The cdr of ech entry is a function for applying the face to a region.")
852
853 (defcustom message-send-hook nil
854   "Hook run before sending messages."
855   :group 'message-various
856   :options '(ispell-message)
857   :type 'hook)
858
859 (defcustom message-send-mail-hook nil
860   "Hook run before sending mail messages."
861   :group 'message-various
862   :type 'hook)
863
864 (defcustom message-send-news-hook nil
865   "Hook run before sending news messages."
866   :group 'message-various
867   :type 'hook)
868
869 (defcustom message-sent-hook nil
870   "Hook run after sending messages."
871   :group 'message-various
872   :type 'hook)
873
874 (defvar message-send-coding-system 'binary
875   "Coding system to encode outgoing mail.")
876
877 (defvar message-draft-coding-system
878   mm-auto-save-coding-system
879   "Coding system to compose mail.")
880
881 ;;; Internal variables.
882
883 (defvar message-buffer-list nil)
884 (defvar message-this-is-news nil)
885 (defvar message-this-is-mail nil)
886 (defvar message-draft-article nil)
887 (defvar message-mime-part nil)
888 (defvar message-posting-charset nil)
889
890 ;; Byte-compiler warning
891 (defvar gnus-active-hashtb)
892 (defvar gnus-read-active-file)
893
894 ;;; Regexp matching the delimiter of messages in UNIX mail format
895 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
896 ;;; of rmail.el's rmail-unix-mail-delimiter.
897 (defvar message-unix-mail-delimiter
898   (let ((time-zone-regexp
899          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
900                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
901                  "\\|"
902                  "\\) *")))
903     (concat
904      "From "
905
906      ;; Many things can happen to an RFC 822 mailbox before it is put into
907      ;; a `From' line.  The leading phrase can be stripped, e.g.
908      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
909      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
910      ;; can be removed, e.g.
911      ;;         From: joe@y.z (Joe      K
912      ;;                 User)
913      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
914      ;;         From: Joe User
915      ;;                 <joe@y.z>
916      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
917      ;; The mailbox can be removed or be replaced by white space, e.g.
918      ;;         From: "Joe User"{space}{tab}
919      ;;                 <joe@y.z>
920      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
921      ;; where {space} and {tab} represent the Ascii space and tab characters.
922      ;; We want to match the results of any of these manglings.
923      ;; The following regexp rejects names whose first characters are
924      ;; obviously bogus, but after that anything goes.
925      "\\([^\0-\b\n-\r\^?].*\\)? "
926
927      ;; The time the message was sent.
928      "\\([^\0-\r \^?]+\\) +"                            ; day of the week
929      "\\([^\0-\r \^?]+\\) +"                            ; month
930      "\\([0-3]?[0-9]\\) +"                              ; day of month
931      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *"  ; time of day
932
933      ;; Perhaps a time zone, specified by an abbreviation, or by a
934      ;; numeric offset.
935      time-zone-regexp
936
937      ;; The year.
938      " \\([0-9][0-9]+\\) *"
939
940      ;; On some systems the time zone can appear after the year, too.
941      time-zone-regexp
942
943      ;; Old uucp cruft.
944      "\\(remote from .*\\)?"
945
946      "\n"))
947   "Regexp matching the delimiter of messages in UNIX mail format.")
948
949 (defvar message-unsent-separator
950   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
951           "^ *---+ +Returned message +---+ *$\\|"
952           "^Start of returned message$\\|"
953           "^ *---+ +Original message +---+ *$\\|"
954           "^ *--+ +begin message +--+ *$\\|"
955           "^ *---+ +Original message follows +---+ *$\\|"
956           "^ *---+ +Undelivered message follows +---+ *$\\|"
957           "^|? *---+ +Message text follows: +---+ *|?$")
958   "A regexp that matches the separator before the text of a failed message.")
959
960 (defvar message-header-format-alist
961   `((Newsgroups)
962     (To . message-fill-address)
963     (Cc . message-fill-address)
964     (Subject)
965     (In-Reply-To)
966     (Fcc)
967     (Bcc)
968     (Date)
969     (Organization)
970     (Distribution)
971     (Lines)
972     (Expires)
973     (Message-ID)
974     (References . message-shorten-references)
975     (User-Agent))
976   "Alist used for formatting headers.")
977
978 (eval-and-compile
979   (autoload 'message-setup-toolbar "messagexmas")
980   (autoload 'mh-new-draft-name "mh-comp")
981   (autoload 'mh-send-letter "mh-comp")
982   (autoload 'gnus-point-at-eol "gnus-util")
983   (autoload 'gnus-point-at-bol "gnus-util")
984   (autoload 'gnus-output-to-mail "gnus-util")
985   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
986   (autoload 'nndraft-request-associate-buffer "nndraft")
987   (autoload 'nndraft-request-expire-articles "nndraft")
988   (autoload 'gnus-open-server "gnus-int")
989   (autoload 'gnus-request-post "gnus-int")
990   (autoload 'gnus-alive-p "gnus-util")
991   (autoload 'rmail-output "rmail"))
992
993 \f
994
995 ;;;
996 ;;; Utility functions.
997 ;;;
998
999 (defmacro message-y-or-n-p (question show &rest text)
1000   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1001   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1002
1003 ;; Delete the current line (and the next N lines.);
1004 (defmacro message-delete-line (&optional n)
1005   `(delete-region (progn (beginning-of-line) (point))
1006                   (progn (forward-line ,(or n 1)) (point))))
1007
1008 (defun message-tokenize-header (header &optional separator)
1009   "Split HEADER into a list of header elements.
1010 \",\" is used as the separator."
1011   (if (not header)
1012       nil
1013     (let ((regexp (format "[%s]+" (or separator ",")))
1014           (beg 1)
1015           (first t)
1016           quoted elems paren)
1017       (save-excursion
1018         (message-set-work-buffer)
1019         (insert header)
1020         (goto-char (point-min))
1021         (while (not (eobp))
1022           (if first
1023               (setq first nil)
1024             (forward-char 1))
1025           (cond ((and (> (point) beg)
1026                       (or (eobp)
1027                           (and (looking-at regexp)
1028                                (not quoted)
1029                                (not paren))))
1030                  (push (buffer-substring beg (point)) elems)
1031                  (setq beg (match-end 0)))
1032                 ((eq (char-after) ?\")
1033                  (setq quoted (not quoted)))
1034                 ((and (eq (char-after) ?\()
1035                       (not quoted))
1036                  (setq paren t))
1037                 ((and (eq (char-after) ?\))
1038                       (not quoted))
1039                  (setq paren nil))))
1040         (nreverse elems)))))
1041
1042 (defun message-mail-file-mbox-p (file)
1043   "Say whether FILE looks like a Unix mbox file."
1044   (when (and (file-exists-p file)
1045              (file-readable-p file)
1046              (file-regular-p file))
1047     (with-temp-buffer
1048       (nnheader-insert-file-contents file)
1049       (goto-char (point-min))
1050       (looking-at message-unix-mail-delimiter))))
1051
1052 (defun message-fetch-field (header &optional not-all)
1053   "The same as `mail-fetch-field', only remove all newlines."
1054   (let* ((inhibit-point-motion-hooks t)
1055          (value (mail-fetch-field header nil (not not-all))))
1056     (when value
1057       (while (string-match "\n[\t ]+" value)
1058         (setq value (replace-match " " t t value)))
1059       ;; We remove all text props.delete-region
1060       (format "%s" value))))
1061
1062 (defun message-narrow-to-field ()
1063   "Narrow the buffer to the header on the current line."
1064   (beginning-of-line)
1065   (narrow-to-region
1066    (point)
1067    (progn
1068      (forward-line 1)
1069      (if (re-search-forward "^[^ \n\t]" nil t)
1070          (progn
1071            (beginning-of-line)
1072            (point))
1073        (point-max))))
1074   (goto-char (point-min)))
1075
1076 (defun message-add-header (&rest headers)
1077   "Add the HEADERS to the message header, skipping those already present."
1078   (while headers
1079     (let (hclean)
1080       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1081         (error "Invalid header `%s'" (car headers)))
1082       (setq hclean (match-string 1 (car headers)))
1083     (save-restriction
1084       (message-narrow-to-headers)
1085       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1086         (insert (car headers) ?\n))))
1087     (setq headers (cdr headers))))
1088
1089
1090 (defun message-fetch-reply-field (header)
1091   "Fetch FIELD from the message we're replying to."
1092   (when (and message-reply-buffer
1093              (buffer-name message-reply-buffer))
1094     (save-excursion
1095       (set-buffer message-reply-buffer)
1096       (message-fetch-field header))))
1097
1098 (defun message-set-work-buffer ()
1099   (if (get-buffer " *message work*")
1100       (progn
1101         (set-buffer " *message work*")
1102         (erase-buffer))
1103     (set-buffer (get-buffer-create " *message work*"))
1104     (kill-all-local-variables)
1105     (mm-enable-multibyte)))
1106
1107 (defun message-functionp (form)
1108   "Return non-nil if FORM is funcallable."
1109   (or (and (symbolp form) (fboundp form))
1110       (and (listp form) (eq (car form) 'lambda))
1111       (byte-code-function-p form)))
1112
1113 (defun message-strip-subject-re (subject)
1114   "Remove \"Re:\" from subject lines."
1115   (if (string-match message-subject-re-regexp subject)
1116       (substring subject (match-end 0))
1117     subject))
1118
1119 (defun message-remove-header (header &optional is-regexp first reverse)
1120   "Remove HEADER in the narrowed buffer.
1121 If REGEXP, HEADER is a regular expression.
1122 If FIRST, only remove the first instance of the header.
1123 Return the number of headers removed."
1124   (goto-char (point-min))
1125   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1126         (number 0)
1127         (case-fold-search t)
1128         last)
1129     (while (and (not (eobp))
1130                 (not last))
1131       (if (if reverse
1132               (not (looking-at regexp))
1133             (looking-at regexp))
1134           (progn
1135             (incf number)
1136             (when first
1137               (setq last t))
1138             (delete-region
1139              (point)
1140              ;; There might be a continuation header, so we have to search
1141              ;; until we find a new non-continuation line.
1142              (progn
1143                (forward-line 1)
1144                (if (re-search-forward "^[^ \t]" nil t)
1145                    (goto-char (match-beginning 0))
1146                  (point-max)))))
1147         (forward-line 1)
1148         (if (re-search-forward "^[^ \t]" nil t)
1149             (goto-char (match-beginning 0))
1150           (goto-char (point-max)))))
1151     number))
1152
1153 (defun message-remove-first-header (header)
1154   "Remove the first instance of HEADER if there is more than one."
1155   (let ((count 0)
1156         (regexp (concat "^" (regexp-quote header) ":")))
1157     (save-excursion
1158       (goto-char (point-min))
1159       (while (re-search-forward regexp nil t)
1160         (incf count)))
1161     (while (> count 1)
1162       (message-remove-header header nil t)
1163       (decf count))))
1164
1165 (defun message-narrow-to-headers ()
1166   "Narrow the buffer to the head of the message."
1167   (widen)
1168   (narrow-to-region
1169    (goto-char (point-min))
1170    (if (re-search-forward
1171         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1172        (match-beginning 0)
1173      (point-max)))
1174   (goto-char (point-min)))
1175
1176 (defun message-narrow-to-head ()
1177   "Narrow the buffer to the head of the message.
1178 Point is left at the beginning of the narrowed-to region."
1179   (widen)
1180   (narrow-to-region
1181    (goto-char (point-min))
1182    (if (search-forward "\n\n" nil 1)
1183        (1- (point))
1184      (point-max)))
1185   (goto-char (point-min)))
1186
1187 (defun message-narrow-to-headers-or-head ()
1188   "Narrow the buffer to the head of the message."
1189   (widen)
1190   (narrow-to-region
1191    (goto-char (point-min))
1192    (cond
1193     ((re-search-forward
1194       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1195      (match-beginning 0))
1196     ((search-forward "\n\n" nil t)
1197      (1- (point)))
1198     (t
1199      (point-max))))
1200   (goto-char (point-min)))
1201
1202 (defun message-news-p ()
1203   "Say whether the current buffer contains a news message."
1204   (and (not message-this-is-mail)
1205        (or message-this-is-news
1206            (save-excursion
1207              (save-restriction
1208                (message-narrow-to-headers)
1209                (and (message-fetch-field "newsgroups")
1210                     (not (message-fetch-field "posted-to"))))))))
1211
1212 (defun message-mail-p ()
1213   "Say whether the current buffer contains a mail message."
1214   (and (not message-this-is-news)
1215        (or message-this-is-mail
1216            (save-excursion
1217              (save-restriction
1218                (message-narrow-to-headers)
1219                (or (message-fetch-field "to")
1220                    (message-fetch-field "cc")
1221                    (message-fetch-field "bcc")))))))
1222
1223 (defun message-next-header ()
1224   "Go to the beginning of the next header."
1225   (beginning-of-line)
1226   (or (eobp) (forward-char 1))
1227   (not (if (re-search-forward "^[^ \t]" nil t)
1228            (beginning-of-line)
1229          (goto-char (point-max)))))
1230
1231 (defun message-sort-headers-1 ()
1232   "Sort the buffer as headers using `message-rank' text props."
1233   (goto-char (point-min))
1234   (require 'sort)
1235   (sort-subr
1236    nil 'message-next-header
1237    (lambda ()
1238      (message-next-header)
1239      (unless (bobp)
1240        (forward-char -1)))
1241    (lambda ()
1242      (or (get-text-property (point) 'message-rank)
1243          10000))))
1244
1245 (defun message-sort-headers ()
1246   "Sort the headers of the current message according to `message-header-format-alist'."
1247   (interactive)
1248   (save-excursion
1249     (save-restriction
1250       (let ((max (1+ (length message-header-format-alist)))
1251             rank)
1252         (message-narrow-to-headers)
1253         (while (re-search-forward "^[^ \n]+:" nil t)
1254           (put-text-property
1255            (match-beginning 0) (1+ (match-beginning 0))
1256            'message-rank
1257            (if (setq rank (length (memq (assq (intern (buffer-substring
1258                                                        (match-beginning 0)
1259                                                        (1- (match-end 0))))
1260                                               message-header-format-alist)
1261                                         message-header-format-alist)))
1262                (- max rank)
1263              (1+ max)))))
1264       (message-sort-headers-1))))
1265
1266 \f
1267
1268 ;;;
1269 ;;; Message mode
1270 ;;;
1271
1272 ;;; Set up keymap.
1273
1274 (defvar message-mode-map nil)
1275
1276 (unless message-mode-map
1277   (setq message-mode-map (make-keymap))
1278   (set-keymap-parent message-mode-map text-mode-map)
1279   (define-key message-mode-map "\C-c?" 'describe-mode)
1280
1281   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1282   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1283   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1284   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1285   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1286   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1287   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1288   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1289   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1290   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1291   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1292   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1293   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1294
1295   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1296   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1297
1298   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1299   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1300   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1301   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1302   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1303   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1304   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1305
1306   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1307   (define-key message-mode-map "\C-c\C-s" 'message-send)
1308   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1309   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1310
1311   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1312   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1313   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1314   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1315
1316   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1317
1318   (define-key message-mode-map "\t" 'message-tab))
1319
1320 (easy-menu-define
1321  message-mode-menu message-mode-map "Message Menu."
1322  '("Message"
1323    ["Sort Headers" message-sort-headers t]
1324    ["Yank Original" message-yank-original t]
1325    ["Fill Yanked Message" message-fill-yanked-message t]
1326    ["Insert Signature" message-insert-signature t]
1327    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1328    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1329    ["Elide Region" message-elide-region (mark t)]
1330    ["Delete Outside Region" message-delete-not-region (mark t)]
1331    ["Kill To Signature" message-kill-to-signature t]
1332    ["Newline and Reformat" message-newline-and-reformat t]
1333    ["Rename buffer" message-rename-buffer t]
1334    ["Spellcheck" ispell-message t]
1335    ["Attach file as MIME" mml-attach-file t]
1336    "----"
1337    ["Send Message" message-send-and-exit t]
1338    ["Abort Message" message-dont-send t]
1339    ["Kill Message" message-kill-buffer t]))
1340
1341 (easy-menu-define
1342  message-mode-field-menu message-mode-map ""
1343  '("Field"
1344    ["Fetch To" message-insert-to t]
1345    ["Fetch Newsgroups" message-insert-newsgroups t]
1346    "----"
1347    ["To" message-goto-to t]
1348    ["Subject" message-goto-subject t]
1349    ["Cc" message-goto-cc t]
1350    ["Reply-To" message-goto-reply-to t]
1351    ["Summary" message-goto-summary t]
1352    ["Keywords" message-goto-keywords t]
1353    ["Newsgroups" message-goto-newsgroups t]
1354    ["Followup-To" message-goto-followup-to t]
1355    ["Distribution" message-goto-distribution t]
1356    ["Body" message-goto-body t]
1357    ["Signature" message-goto-signature t]))
1358
1359 (defvar facemenu-add-face-function)
1360 (defvar facemenu-remove-face-function)
1361
1362 ;;;###autoload
1363 (defun message-mode ()
1364   "Major mode for editing mail and news to be sent.
1365 Like Text Mode but with these additional commands:
1366 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1367 C-c C-d  Pospone sending the message        C-c C-k  Kill the message
1368 C-c C-f  move to a header field (and create it if there isn't):
1369          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1370          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1371          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1372          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1373          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1374          C-c C-f C-f  move to Followup-To
1375 C-c C-t  message-insert-to (add a To header to a news followup)
1376 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1377 C-c C-b  message-goto-body (move to beginning of message text).
1378 C-c C-i  message-goto-signature (move to the beginning of the signature).
1379 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1380 C-c C-y  message-yank-original (insert current message, if any).
1381 C-c C-q  message-fill-yanked-message (fill what was yanked).
1382 C-c C-e  message-elide-region (elide the text between point and mark).
1383 C-c C-v  message-delete-not-region (remove the text outside the region).
1384 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1385 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1386 C-c C-a  mml-attach-file (attach a file as MIME)."
1387   (interactive)
1388   (kill-all-local-variables)
1389   (set (make-local-variable 'message-reply-buffer) nil)
1390   (make-local-variable 'message-send-actions)
1391   (make-local-variable 'message-exit-actions)
1392   (make-local-variable 'message-kill-actions)
1393   (make-local-variable 'message-postpone-actions)
1394   (make-local-variable 'message-draft-article)
1395   (make-local-hook 'kill-buffer-hook)
1396   (set-syntax-table message-mode-syntax-table)
1397   (use-local-map message-mode-map)
1398   (setq local-abbrev-table message-mode-abbrev-table)
1399   (setq major-mode 'message-mode)
1400   (setq mode-name "Message")
1401   (setq buffer-offer-save t)
1402   (make-local-variable 'facemenu-add-face-function)
1403   (make-local-variable 'facemenu-remove-face-function)
1404   (setq facemenu-add-face-function
1405         (lambda (face end)
1406           (let ((face-fun (cdr (assq face message-face-alist))))
1407             (if face-fun
1408                 (funcall face-fun (point) end)
1409               (error "Face %s not configured for %s mode" face mode-name)))
1410           "")
1411         facemenu-remove-face-function t)
1412   (make-local-variable 'paragraph-separate)
1413   (make-local-variable 'paragraph-start)
1414   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1415   ;; lines that delimit forwarded messages.
1416   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1417   ;; are also sometimes used and should be separators.
1418   (setq paragraph-start
1419         (concat (regexp-quote mail-header-separator)
1420                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1421                 "-- $\\|---+$\\|"
1422                 page-delimiter
1423                 ;;!!! Uhm... shurely this can't be right?
1424                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1425   (setq paragraph-separate paragraph-start)
1426   (make-local-variable 'message-reply-headers)
1427   (setq message-reply-headers nil)
1428   (make-local-variable 'message-newsreader)
1429   (make-local-variable 'message-mailer)
1430   (make-local-variable 'message-post-method)
1431   (set (make-local-variable 'message-sent-message-via) nil)
1432   (set (make-local-variable 'message-checksum) nil)
1433   (set (make-local-variable 'message-mime-part) 0)
1434   ;;(when (fboundp 'mail-hist-define-keys)
1435   ;;  (mail-hist-define-keys))
1436   (when (string-match "XEmacs\\|Lucid" emacs-version)
1437     (message-setup-toolbar))
1438   (easy-menu-add message-mode-menu message-mode-map)
1439   (easy-menu-add message-mode-field-menu message-mode-map)
1440   ;; Allow mail alias things.
1441   (when (eq message-mail-alias-type 'abbrev)
1442     (if (fboundp 'mail-abbrevs-setup)
1443         (mail-abbrevs-setup)
1444       (mail-aliases-setup)))
1445   (message-set-auto-save-file-name)
1446   (unless (string-match "XEmacs" emacs-version)
1447     (set (make-local-variable 'font-lock-defaults)
1448          '(message-font-lock-keywords t)))
1449   (make-local-variable 'adaptive-fill-regexp)
1450   (setq adaptive-fill-regexp
1451         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|" adaptive-fill-regexp))
1452   (unless (boundp 'adaptive-fill-first-line-regexp)
1453     (setq adaptive-fill-first-line-regexp nil))
1454   (make-local-variable 'adaptive-fill-first-line-regexp)
1455   (setq adaptive-fill-first-line-regexp
1456         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1457                 adaptive-fill-first-line-regexp))
1458   (mm-enable-multibyte)
1459   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1460   (setq indent-tabs-mode nil)
1461   (mml-mode)
1462   (run-hooks 'text-mode-hook 'message-mode-hook))
1463
1464 \f
1465
1466 ;;;
1467 ;;; Message mode commands
1468 ;;;
1469
1470 ;;; Movement commands
1471
1472 (defun message-goto-to ()
1473   "Move point to the To header."
1474   (interactive)
1475   (message-position-on-field "To"))
1476
1477 (defun message-goto-subject ()
1478   "Move point to the Subject header."
1479   (interactive)
1480   (message-position-on-field "Subject"))
1481
1482 (defun message-goto-cc ()
1483   "Move point to the Cc header."
1484   (interactive)
1485   (message-position-on-field "Cc" "To"))
1486
1487 (defun message-goto-bcc ()
1488   "Move point to the Bcc  header."
1489   (interactive)
1490   (message-position-on-field "Bcc" "Cc" "To"))
1491
1492 (defun message-goto-fcc ()
1493   "Move point to the Fcc header."
1494   (interactive)
1495   (message-position-on-field "Fcc" "To" "Newsgroups"))
1496
1497 (defun message-goto-reply-to ()
1498   "Move point to the Reply-To header."
1499   (interactive)
1500   (message-position-on-field "Reply-To" "Subject"))
1501
1502 (defun message-goto-newsgroups ()
1503   "Move point to the Newsgroups header."
1504   (interactive)
1505   (message-position-on-field "Newsgroups"))
1506
1507 (defun message-goto-distribution ()
1508   "Move point to the Distribution header."
1509   (interactive)
1510   (message-position-on-field "Distribution"))
1511
1512 (defun message-goto-followup-to ()
1513   "Move point to the Followup-To header."
1514   (interactive)
1515   (message-position-on-field "Followup-To" "Newsgroups"))
1516
1517 (defun message-goto-keywords ()
1518   "Move point to the Keywords header."
1519   (interactive)
1520   (message-position-on-field "Keywords" "Subject"))
1521
1522 (defun message-goto-summary ()
1523   "Move point to the Summary header."
1524   (interactive)
1525   (message-position-on-field "Summary" "Subject"))
1526
1527 (defun message-goto-body ()
1528   "Move point to the beginning of the message body."
1529   (interactive)
1530   (if (looking-at "[ \t]*\n") (expand-abbrev))
1531   (goto-char (point-min))
1532   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1533       (search-forward "\n\n" nil t)))
1534
1535 (defun message-goto-eoh ()
1536   "Move point to the end of the headers."
1537   (interactive)
1538   (message-goto-body)
1539   (forward-line -1))
1540
1541 (defun message-goto-signature ()
1542   "Move point to the beginning of the message signature.
1543 If there is no signature in the article, go to the end and
1544 return nil."
1545   (interactive)
1546   (goto-char (point-min))
1547   (if (re-search-forward message-signature-separator nil t)
1548       (forward-line 1)
1549     (goto-char (point-max))
1550     nil))
1551
1552 \f
1553
1554 (defun message-insert-to (&optional force)
1555   "Insert a To header that points to the author of the article being replied to.
1556 If the original author requested not to be sent mail, the function signals
1557 an error.
1558 With the prefix argument FORCE, insert the header anyway."
1559   (interactive "P")
1560   (let ((co (message-fetch-reply-field "mail-copies-to")))
1561     (when (and (null force)
1562                co
1563                (or (equal (downcase co) "never")
1564                    (equal (downcase co) "nobody")))
1565       (error "The user has requested not to have copies sent via mail")))
1566   (when (and (message-position-on-field "To")
1567              (mail-fetch-field "to")
1568              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1569     (insert ", "))
1570   (insert (or (message-fetch-reply-field "reply-to")
1571               (message-fetch-reply-field "from") "")))
1572
1573 (defun message-insert-newsgroups ()
1574   "Insert the Newsgroups header from the article being replied to."
1575   (interactive)
1576   (when (and (message-position-on-field "Newsgroups")
1577              (mail-fetch-field "newsgroups")
1578              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1579     (insert ","))
1580   (insert (or (message-fetch-reply-field "newsgroups") "")))
1581
1582 \f
1583
1584 ;;; Various commands
1585
1586 (defun message-delete-not-region (beg end)
1587   "Delete everything in the body of the current message that is outside of the region."
1588   (interactive "r")
1589   (save-excursion
1590     (goto-char end)
1591     (delete-region (point) (if (not (message-goto-signature))
1592                                (point)
1593                              (forward-line -2)
1594                              (point)))
1595     (insert "\n")
1596     (goto-char beg)
1597     (delete-region beg (progn (message-goto-body)
1598                               (forward-line 2)
1599                               (point))))
1600   (when (message-goto-signature)
1601     (forward-line -2)))
1602
1603 (defun message-kill-to-signature ()
1604   "Deletes all text up to the signature."
1605   (interactive)
1606   (let ((point (point)))
1607     (message-goto-signature)
1608     (unless (eobp)
1609       (forward-line -2))
1610     (kill-region point (point))
1611     (unless (bolp)
1612       (insert "\n"))))
1613
1614 (defun message-newline-and-reformat ()
1615   "Insert four newlines, and then reformat if inside quoted text."
1616   (interactive)
1617   (let ((point (point))
1618         quoted)
1619     (save-excursion
1620       (beginning-of-line)
1621       (if (looking-at (sc-cite-regexp))
1622           (setq quoted (buffer-substring (match-beginning 0) (match-end 0)))))
1623     (insert "\n\n\n\n")
1624     (delete-region (point) (re-search-forward "[ \t]*"))
1625     (when quoted
1626       (insert quoted))
1627     (fill-paragraph nil)
1628     (goto-char point)
1629     (forward-line 2)))
1630
1631 (defun message-insert-signature (&optional force)
1632   "Insert a signature.  See documentation for the `message-signature' variable."
1633   (interactive (list 0))
1634   (let* ((signature
1635           (cond
1636            ((and (null message-signature)
1637                  (eq force 0))
1638             (save-excursion
1639               (goto-char (point-max))
1640               (not (re-search-backward message-signature-separator nil t))))
1641            ((and (null message-signature)
1642                  force)
1643             t)
1644            ((message-functionp message-signature)
1645             (funcall message-signature))
1646            ((listp message-signature)
1647             (eval message-signature))
1648            (t message-signature)))
1649          (signature
1650           (cond ((stringp signature)
1651                  signature)
1652                 ((and (eq t signature)
1653                       message-signature-file
1654                       (file-exists-p message-signature-file))
1655                  signature))))
1656     (when signature
1657       (goto-char (point-max))
1658       ;; Insert the signature.
1659       (unless (bolp)
1660         (insert "\n"))
1661       (insert "\n-- \n")
1662       (if (eq signature t)
1663           (insert-file-contents message-signature-file)
1664         (insert signature))
1665       (goto-char (point-max))
1666       (or (bolp) (insert "\n")))))
1667
1668 (defun message-elide-region (b e)
1669   "Elide the text between point and mark.
1670 An ellipsis (from `message-elide-elipsis') will be inserted where the
1671 text was killed."
1672   (interactive "r")
1673   (kill-region b e)
1674   (unless (bolp)
1675     (insert "\n"))
1676   (insert message-elide-elipsis))
1677
1678 (defvar message-caesar-translation-table nil)
1679
1680 (defun message-caesar-region (b e &optional n)
1681   "Caesar rotation of region by N, default 13, for decrypting netnews."
1682   (interactive
1683    (list
1684     (min (point) (or (mark t) (point)))
1685     (max (point) (or (mark t) (point)))
1686     (when current-prefix-arg
1687       (prefix-numeric-value current-prefix-arg))))
1688
1689   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1690   (unless (or (zerop n)                 ; no action needed for a rot of 0
1691               (= b e))                  ; no region to rotate
1692     ;; We build the table, if necessary.
1693     (when (or (not message-caesar-translation-table)
1694               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1695         (setq message-caesar-translation-table
1696               (message-make-caesar-translation-table n)))
1697     ;; Then we translate the region.  Do it this way to retain
1698     ;; text properties.
1699     (while (< b e)
1700       (when (< (char-after b) 255)
1701         (subst-char-in-region
1702          b (1+ b) (char-after b)
1703          (aref message-caesar-translation-table (char-after b))))
1704       (incf b))))
1705
1706 (defun message-make-caesar-translation-table (n)
1707   "Create a rot table with offset N."
1708   (let ((i -1)
1709         (table (make-string 256 0)))
1710     (while (< (incf i) 256)
1711       (aset table i i))
1712     (concat
1713      (substring table 0 ?A)
1714      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1715      (substring table ?A (+ ?A n))
1716      (substring table (+ ?A 26) ?a)
1717      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1718      (substring table ?a (+ ?a n))
1719      (substring table (+ ?a 26) 255))))
1720
1721 (defun message-caesar-buffer-body (&optional rotnum)
1722   "Caesar rotates all letters in the current buffer by 13 places.
1723 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1724 With prefix arg, specifies the number of places to rotate each letter forward.
1725 Mail and USENET news headers are not rotated."
1726   (interactive (if current-prefix-arg
1727                    (list (prefix-numeric-value current-prefix-arg))
1728                  (list nil)))
1729   (save-excursion
1730     (save-restriction
1731       (when (message-goto-body)
1732         (narrow-to-region (point) (point-max)))
1733       (message-caesar-region (point-min) (point-max) rotnum))))
1734
1735 (defun message-pipe-buffer-body (program)
1736   "Pipe the message body in the current buffer through PROGRAM."
1737   (save-excursion
1738     (save-restriction
1739       (when (message-goto-body)
1740         (narrow-to-region (point) (point-max)))
1741       (let ((body (buffer-substring (point-min) (point-max))))
1742         (unless (equal 0 (call-process-region
1743                            (point-min) (point-max) program t t))
1744             (insert body)
1745             (message "%s failed." program))))))
1746
1747 (defun message-rename-buffer (&optional enter-string)
1748   "Rename the *message* buffer to \"*message* RECIPIENT\".
1749 If the function is run with a prefix, it will ask for a new buffer
1750 name, rather than giving an automatic name."
1751   (interactive "Pbuffer name: ")
1752   (save-excursion
1753     (save-restriction
1754       (goto-char (point-min))
1755       (narrow-to-region (point)
1756                         (search-forward mail-header-separator nil 'end))
1757       (let* ((mail-to (or
1758                        (if (message-news-p) (message-fetch-field "Newsgroups")
1759                          (message-fetch-field "To"))
1760                        ""))
1761              (mail-trimmed-to
1762               (if (string-match "," mail-to)
1763                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1764                 mail-to))
1765              (name-default (concat "*message* " mail-trimmed-to))
1766              (name (if enter-string
1767                        (read-string "New buffer name: " name-default)
1768                      name-default)))
1769         (rename-buffer name t)))))
1770
1771 (defun message-fill-yanked-message (&optional justifyp)
1772   "Fill the paragraphs of a message yanked into this one.
1773 Numeric argument means justify as well."
1774   (interactive "P")
1775   (save-excursion
1776     (goto-char (point-min))
1777     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1778     (let ((fill-prefix message-yank-prefix))
1779       (fill-individual-paragraphs (point) (point-max) justifyp))))
1780
1781 (defun message-indent-citation ()
1782   "Modify text just inserted from a message to be cited.
1783 The inserted text should be the region.
1784 When this function returns, the region is again around the modified text.
1785
1786 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1787 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1788   (let ((start (point)))
1789     ;; Remove unwanted headers.
1790     (when message-ignored-cited-headers
1791       (let (all-removed)
1792         (save-restriction
1793           (narrow-to-region
1794            (goto-char start)
1795            (if (search-forward "\n\n" nil t)
1796                (1- (point))
1797              (point)))
1798           (message-remove-header message-ignored-cited-headers t)
1799           (when (= (point-min) (point-max))
1800             (setq all-removed t))
1801           (goto-char (point-max)))
1802         (if all-removed
1803             (goto-char start)
1804           (forward-line 1))))
1805     ;; Delete blank lines at the start of the buffer.
1806     (while (and (point-min)
1807                 (eolp)
1808                 (not (eobp)))
1809       (message-delete-line))
1810     ;; Delete blank lines at the end of the buffer.
1811     (goto-char (point-max))
1812     (unless (eolp)
1813       (insert "\n"))
1814     (while (and (zerop (forward-line -1))
1815                 (looking-at "$"))
1816       (message-delete-line))
1817     ;; Do the indentation.
1818     (if (null message-yank-prefix)
1819         (indent-rigidly start (mark t) message-indentation-spaces)
1820       (save-excursion
1821         (goto-char start)
1822         (while (< (point) (mark t))
1823           (insert message-yank-prefix)
1824           (forward-line 1))))
1825     (goto-char start)))
1826
1827 (defun message-yank-original (&optional arg)
1828   "Insert the message being replied to, if any.
1829 Puts point before the text and mark after.
1830 Normally indents each nonblank line ARG spaces (default 3).  However,
1831 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1832
1833 This function uses `message-cite-function' to do the actual citing.
1834
1835 Just \\[universal-argument] as argument means don't indent, insert no
1836 prefix, and don't delete any headers."
1837   (interactive "P")
1838   (let ((modified (buffer-modified-p)))
1839     (when (and message-reply-buffer
1840                message-cite-function)
1841       (delete-windows-on message-reply-buffer t)
1842       (insert-buffer message-reply-buffer)
1843       (funcall message-cite-function)
1844       (message-exchange-point-and-mark)
1845       (unless (bolp)
1846         (insert ?\n))
1847       (unless modified
1848         (setq message-checksum (message-checksum))))))
1849
1850 (defun message-cite-original-without-signature ()
1851   "Cite function in the standard Message manner."
1852   (let ((start (point))
1853         (end (mark t))
1854         (functions
1855          (when message-indent-citation-function
1856            (if (listp message-indent-citation-function)
1857                message-indent-citation-function
1858              (list message-indent-citation-function)))))
1859     (mml-quote-region start end)
1860     (goto-char end)
1861     (when (re-search-backward message-signature-separator start t)
1862       ;; Also peel off any blank lines before the signature.
1863       (forward-line -1)
1864       (while (looking-at "^[ \t]*$")
1865         (forward-line -1))
1866       (forward-line 1)
1867       (delete-region (point) end))
1868     (goto-char start)
1869     (while functions
1870       (funcall (pop functions)))
1871     (when message-citation-line-function
1872       (unless (bolp)
1873         (insert "\n"))
1874       (funcall message-citation-line-function))))
1875
1876 (defvar mail-citation-hook)             ;Compiler directive
1877 (defun message-cite-original ()
1878   "Cite function in the standard Message manner."
1879   (if (and (boundp 'mail-citation-hook)
1880            mail-citation-hook)
1881       (run-hooks 'mail-citation-hook)
1882     (let ((start (point))
1883           (end (mark t))
1884           (functions
1885            (when message-indent-citation-function
1886              (if (listp message-indent-citation-function)
1887                  message-indent-citation-function
1888                (list message-indent-citation-function)))))
1889       (mml-quote-region start end)
1890       (goto-char start)
1891       (while functions
1892         (funcall (pop functions)))
1893       (when message-citation-line-function
1894         (unless (bolp)
1895           (insert "\n"))
1896         (funcall message-citation-line-function)))))
1897
1898 (defun message-insert-citation-line ()
1899   "Function that inserts a simple citation line."
1900   (when message-reply-headers
1901     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1902
1903 (defun message-position-on-field (header &rest afters)
1904   (let ((case-fold-search t))
1905     (save-restriction
1906       (narrow-to-region
1907        (goto-char (point-min))
1908        (progn
1909          (re-search-forward
1910           (concat "^" (regexp-quote mail-header-separator) "$"))
1911          (match-beginning 0)))
1912       (goto-char (point-min))
1913       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1914           (progn
1915             (re-search-forward "^[^ \t]" nil 'move)
1916             (beginning-of-line)
1917             (skip-chars-backward "\n")
1918             t)
1919         (while (and afters
1920                     (not (re-search-forward
1921                           (concat "^" (regexp-quote (car afters)) ":")
1922                           nil t)))
1923           (pop afters))
1924         (when afters
1925           (re-search-forward "^[^ \t]" nil 'move)
1926           (beginning-of-line))
1927         (insert header ": \n")
1928         (forward-char -1)
1929         nil))))
1930
1931 (defun message-remove-signature ()
1932   "Remove the signature from the text between point and mark.
1933 The text will also be indented the normal way."
1934   (save-excursion
1935     (let ((start (point))
1936           mark)
1937       (if (not (re-search-forward message-signature-separator (mark t) t))
1938           ;; No signature here, so we just indent the cited text.
1939           (message-indent-citation)
1940         ;; Find the last non-empty line.
1941         (forward-line -1)
1942         (while (looking-at "[ \t]*$")
1943           (forward-line -1))
1944         (forward-line 1)
1945         (setq mark (set-marker (make-marker) (point)))
1946         (goto-char start)
1947         (message-indent-citation)
1948         ;; Enable undoing the deletion.
1949         (undo-boundary)
1950         (delete-region mark (mark t))
1951         (set-marker mark nil)))))
1952
1953 \f
1954
1955 ;;;
1956 ;;; Sending messages
1957 ;;;
1958
1959 (defun message-send-and-exit (&optional arg)
1960   "Send message like `message-send', then, if no errors, exit from mail buffer."
1961   (interactive "P")
1962   (let ((buf (current-buffer))
1963         (actions message-exit-actions))
1964     (when (and (message-send arg)
1965                (buffer-name buf))
1966       (if message-kill-buffer-on-exit
1967           (kill-buffer buf)
1968         (bury-buffer buf)
1969         (when (eq buf (current-buffer))
1970           (message-bury buf)))
1971       (message-do-actions actions)
1972       t)))
1973
1974 (defun message-dont-send ()
1975   "Don't send the message you have been editing."
1976   (interactive)
1977   (set-buffer-modified-p t)
1978   (save-buffer)
1979   (let ((actions message-postpone-actions))
1980     (message-bury (current-buffer))
1981     (message-do-actions actions)))
1982
1983 (defun message-kill-buffer ()
1984   "Kill the current buffer."
1985   (interactive)
1986   (when (or (not (buffer-modified-p))
1987             (yes-or-no-p "Message modified; kill anyway? "))
1988     (let ((actions message-kill-actions))
1989       (setq buffer-file-name nil)
1990       (kill-buffer (current-buffer))
1991       (message-do-actions actions))))
1992
1993 (defun message-bury (buffer)
1994   "Bury this mail buffer."
1995   (let ((newbuf (other-buffer buffer)))
1996     (bury-buffer buffer)
1997     (if (and (fboundp 'frame-parameters)
1998              (cdr (assq 'dedicated (frame-parameters)))
1999              (not (null (delq (selected-frame) (visible-frame-list)))))
2000         (delete-frame (selected-frame))
2001       (switch-to-buffer newbuf))))
2002
2003 (defun message-send (&optional arg)
2004   "Send the message in the current buffer.
2005 If `message-interactive' is non-nil, wait for success indication
2006 or error messages, and inform user.
2007 Otherwise any failure is reported in a message back to
2008 the user from the mailer."
2009   (interactive "P")
2010   ;; Make it possible to undo the coming changes.
2011   (undo-boundary)
2012   (let ((inhibit-read-only t))
2013     (put-text-property (point-min) (point-max) 'read-only nil))
2014   (message-fix-before-sending)
2015   (run-hooks 'message-send-hook)
2016   (message "Sending...")
2017   (let ((alist message-send-method-alist)
2018         (success t)
2019         elem sent)
2020     (while (and success
2021                 (setq elem (pop alist)))
2022       (when (or (not (funcall (cadr elem)))
2023                 (and (or (not (memq (car elem)
2024                                     message-sent-message-via))
2025                          (y-or-n-p
2026                           (format
2027                            "Already sent message via %s; resend? "
2028                            (car elem))))
2029                      (setq success (funcall (caddr elem) arg))))
2030         (setq sent t)))
2031     (unless (or sent (not success))
2032       (error "No methods specified to send by"))
2033     (when (and success sent)
2034       (message-do-fcc)
2035       (save-excursion
2036         (run-hooks 'message-sent-hook))
2037       (message "Sending...done")
2038       ;; Mark the buffer as unmodified and delete auto-save.
2039       (set-buffer-modified-p nil)
2040       (delete-auto-save-file-if-necessary t)
2041       (message-disassociate-draft)
2042       ;; Delete other mail buffers and stuff.
2043       (message-do-send-housekeeping)
2044       (message-do-actions message-send-actions)
2045       ;; Return success.
2046       t)))
2047
2048 (defun message-send-via-mail (arg)
2049   "Send the current message via mail."
2050   (message-send-mail arg))
2051
2052 (defun message-send-via-news (arg)
2053   "Send the current message via news."
2054   (funcall message-send-news-function arg))
2055
2056 (defmacro message-check (type &rest forms)
2057   "Eval FORMS if TYPE is to be checked."
2058   `(or (message-check-element ,type)
2059        (save-excursion
2060          ,@forms)))
2061
2062 (put 'message-check 'lisp-indent-function 1)
2063 (put 'message-check 'edebug-form-spec '(form body))
2064
2065 (defun message-fix-before-sending ()
2066   "Do various things to make the message nice before sending it."
2067   ;; Make sure there's a newline at the end of the message.
2068   (goto-char (point-max))
2069   (unless (bolp)
2070     (insert "\n"))
2071   ;; Delete all invisible text.
2072   (message-check 'invisible-text
2073     (when (text-property-any (point-min) (point-max) 'invisible t)
2074       (put-text-property (point-min) (point-max) 'invisible nil)
2075       (unless (yes-or-no-p
2076                "Invisible text found and made visible; continue posting? ")
2077         (error "Invisible text found and made visible")))))
2078
2079 (defun message-add-action (action &rest types)
2080   "Add ACTION to be performed when doing an exit of type TYPES."
2081   (let (var)
2082     (while types
2083       (set (setq var (intern (format "message-%s-actions" (pop types))))
2084            (nconc (symbol-value var) (list action))))))
2085
2086 (defun message-do-actions (actions)
2087   "Perform all actions in ACTIONS."
2088   ;; Now perform actions on successful sending.
2089   (while actions
2090     (ignore-errors
2091       (cond
2092        ;; A simple function.
2093        ((message-functionp (car actions))
2094         (funcall (car actions)))
2095        ;; Something to be evaled.
2096        (t
2097         (eval (car actions)))))
2098     (pop actions)))
2099
2100 (defun message-send-mail (&optional arg)
2101   (require 'mail-utils)
2102   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2103         (case-fold-search nil)
2104         (news (message-news-p))
2105         (mailbuf (current-buffer)))
2106     (save-restriction
2107       (message-narrow-to-headers)
2108       ;; Insert some headers.
2109       (let ((message-deletable-headers
2110              (if news nil message-deletable-headers)))
2111         (message-generate-headers message-required-mail-headers))
2112       ;; Let the user do all of the above.
2113       (run-hooks 'message-header-hook))
2114     (unwind-protect
2115         (save-excursion
2116           (set-buffer tembuf)
2117           (erase-buffer)
2118           ;; Avoid copying text props.
2119           (insert (format
2120                    "%s" (save-excursion
2121                           (set-buffer mailbuf)
2122                           (buffer-string))))
2123           ;; Remove some headers.
2124           (message-encode-message-body)
2125           (save-restriction
2126             (message-narrow-to-headers)
2127             ;; We (re)generate the Lines header.
2128             (when (memq 'Lines message-required-mail-headers)
2129               (message-generate-headers '(Lines)))
2130             ;; Remove some headers.
2131             (message-remove-header message-ignored-mail-headers t)
2132             (mail-encode-encoded-word-buffer))
2133           (goto-char (point-max))
2134           ;; require one newline at the end.
2135           (or (= (preceding-char) ?\n)
2136               (insert ?\n))
2137           (when (and news
2138                      (or (message-fetch-field "cc")
2139                          (message-fetch-field "to")))
2140             (message-insert-courtesy-copy))
2141           (funcall message-send-mail-function))
2142       (kill-buffer tembuf))
2143     (set-buffer mailbuf)
2144     (push 'mail message-sent-message-via)))
2145
2146 (defun message-send-mail-with-sendmail ()
2147   "Send off the prepared buffer with sendmail."
2148   (let ((errbuf (if message-interactive
2149                     (generate-new-buffer " sendmail errors")
2150                   0))
2151         resend-to-addresses delimline)
2152     (let ((case-fold-search t))
2153       (save-restriction
2154         (message-narrow-to-headers)
2155         (setq resend-to-addresses (message-fetch-field "resent-to")))
2156       ;; Change header-delimiter to be what sendmail expects.
2157       (goto-char (point-min))
2158       (re-search-forward
2159        (concat "^" (regexp-quote mail-header-separator) "\n"))
2160       (replace-match "\n")
2161       (backward-char 1)
2162       (setq delimline (point-marker))
2163       (run-hooks 'message-send-mail-hook)
2164       ;; Insert an extra newline if we need it to work around
2165       ;; Sun's bug that swallows newlines.
2166       (goto-char (1+ delimline))
2167       (when (eval message-mailer-swallows-blank-line)
2168         (newline))
2169       (when message-interactive
2170         (save-excursion
2171           (set-buffer errbuf)
2172           (erase-buffer))))
2173     (let ((default-directory "/")
2174           (coding-system-for-write message-send-coding-system))
2175       (apply 'call-process-region
2176              (append (list (point-min) (point-max)
2177                            (if (boundp 'sendmail-program)
2178                                sendmail-program
2179                              "/usr/lib/sendmail")
2180                            nil errbuf nil "-oi")
2181                      ;; Always specify who from,
2182                      ;; since some systems have broken sendmails.
2183                      ;; But some systems are more broken with -f, so
2184                      ;; we'll let users override this.
2185                      (if (null message-sendmail-f-is-evil)
2186                          (list "-f" (user-login-name)))
2187                      ;; These mean "report errors by mail"
2188                      ;; and "deliver in background".
2189                      (if (null message-interactive) '("-oem" "-odb"))
2190                      ;; Get the addresses from the message
2191                      ;; unless this is a resend.
2192                      ;; We must not do that for a resend
2193                      ;; because we would find the original addresses.
2194                      ;; For a resend, include the specific addresses.
2195                      (if resend-to-addresses
2196                          (list resend-to-addresses)
2197                        '("-t")))))
2198     (when message-interactive
2199       (save-excursion
2200         (set-buffer errbuf)
2201         (goto-char (point-min))
2202         (while (re-search-forward "\n\n* *" nil t)
2203           (replace-match "; "))
2204         (if (not (zerop (buffer-size)))
2205             (error "Sending...failed to %s"
2206                    (buffer-substring (point-min) (point-max)))))
2207       (when (bufferp errbuf)
2208         (kill-buffer errbuf)))))
2209
2210 (defun message-send-mail-with-qmail ()
2211   "Pass the prepared message buffer to qmail-inject.
2212 Refer to the documentation for the variable `message-send-mail-function'
2213 to find out how to use this."
2214   ;; replace the header delimiter with a blank line
2215   (goto-char (point-min))
2216   (re-search-forward
2217    (concat "^" (regexp-quote mail-header-separator) "\n"))
2218   (replace-match "\n")
2219   (run-hooks 'message-send-mail-hook)
2220   ;; send the message
2221   (case
2222       (let ((coding-system-for-write message-send-coding-system))
2223         (apply
2224          'call-process-region 1 (point-max) message-qmail-inject-program
2225          nil nil nil
2226          ;; qmail-inject's default behaviour is to look for addresses on the
2227          ;; command line; if there're none, it scans the headers.
2228          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2229          ;;
2230          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2231          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2232          ;; message from stdin.
2233          ;;
2234          ;; qmail also has the advantage of not having been raped by
2235          ;; various vendors, so we don't have to allow for that, either --
2236          ;; compare this with message-send-mail-with-sendmail and weep
2237          ;; for sendmail's lost innocence.
2238          ;;
2239          ;; all this is way cool coz it lets us keep the arguments entirely
2240          ;; free for -inject-arguments -- a big win for the user and for us
2241          ;; since we don't have to play that double-guessing game and the user
2242          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2243          message-qmail-inject-args))
2244     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2245     ;; we have to look at the retval instead
2246     (0 nil)
2247     (1   (error "qmail-inject reported permanent failure"))
2248     (111 (error "qmail-inject reported transient failure"))
2249     ;; should never happen
2250     (t   (error "qmail-inject reported unknown failure"))))
2251
2252 (defun message-send-mail-with-mh ()
2253   "Send the prepared message buffer with mh."
2254   (let ((mh-previous-window-config nil)
2255         (name (mh-new-draft-name)))
2256     (setq buffer-file-name name)
2257     ;; MH wants to generate these headers itself.
2258     (when message-mh-deletable-headers
2259       (let ((headers message-mh-deletable-headers))
2260         (while headers
2261           (goto-char (point-min))
2262           (and (re-search-forward
2263                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2264                (message-delete-line))
2265           (pop headers))))
2266     (run-hooks 'message-send-mail-hook)
2267     ;; Pass it on to mh.
2268     (mh-send-letter)))
2269
2270 (defun message-send-news (&optional arg)
2271   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2272         (case-fold-search nil)
2273         (method (if (message-functionp message-post-method)
2274                     (funcall message-post-method arg)
2275                   message-post-method))
2276         (messbuf (current-buffer))
2277         (message-syntax-checks
2278          (if arg
2279              (cons '(existing-newsgroups . disabled)
2280                    message-syntax-checks)
2281            message-syntax-checks))
2282         result)
2283     (if (not (message-check-news-body-syntax))
2284         nil
2285       (save-restriction
2286         (message-narrow-to-headers)
2287         ;; Insert some headers.
2288         (message-generate-headers message-required-news-headers)
2289         ;; Let the user do all of the above.
2290         (run-hooks 'message-header-hook))
2291       (message-cleanup-headers)
2292       (if (not (message-check-news-syntax))
2293           nil
2294         (unwind-protect
2295             (save-excursion
2296               (set-buffer tembuf)
2297               (buffer-disable-undo)
2298               (erase-buffer)
2299               ;; Avoid copying text props.
2300               (insert (format
2301                        "%s" (save-excursion
2302                               (set-buffer messbuf)
2303                               (buffer-string))))
2304               (message-encode-message-body)
2305               ;; Remove some headers.
2306               (save-restriction
2307                 (message-narrow-to-headers)
2308                 ;; We (re)generate the Lines header.
2309                 (when (memq 'Lines message-required-mail-headers)
2310                   (message-generate-headers '(Lines)))
2311                 ;; Remove some headers.
2312                 (message-remove-header message-ignored-news-headers t)
2313                 (let ((mail-parse-charset message-posting-charset))
2314                   (mail-encode-encoded-word-buffer)))
2315               (goto-char (point-max))
2316               ;; require one newline at the end.
2317               (or (= (preceding-char) ?\n)
2318                   (insert ?\n))
2319               (let ((case-fold-search t))
2320                 ;; Remove the delimiter.
2321                 (goto-char (point-min))
2322                 (re-search-forward
2323                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2324                 (replace-match "\n")
2325                 (backward-char 1))
2326               (run-hooks 'message-send-news-hook)
2327               (gnus-open-server method)
2328             (setq result (let ((mail-header-separator ""))
2329                            (gnus-request-post method))))
2330           (kill-buffer tembuf))
2331         (set-buffer messbuf)
2332         (if result
2333             (push 'news message-sent-message-via)
2334           (message "Couldn't send message via news: %s"
2335                    (nnheader-get-report (car method)))
2336           nil)))))
2337
2338 ;;;
2339 ;;; Header generation & syntax checking.
2340 ;;;
2341
2342 (defun message-check-element (type)
2343   "Returns non-nil if this type is not to be checked."
2344   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2345       t
2346     (let ((able (assq type message-syntax-checks)))
2347       (and (consp able)
2348            (eq (cdr able) 'disabled)))))
2349
2350 (defun message-check-news-syntax ()
2351   "Check the syntax of the message."
2352   (save-excursion
2353     (save-restriction
2354       (widen)
2355       ;; We narrow to the headers and check them first.
2356       (save-excursion
2357         (save-restriction
2358           (message-narrow-to-headers)
2359           (message-check-news-header-syntax))))))
2360
2361 (defun message-check-news-header-syntax ()
2362   (and
2363    ;; Check Newsgroups header.
2364    (message-check 'newsgroyps
2365      (let ((group (message-fetch-field "newsgroups")))
2366        (or
2367         (and group
2368              (not (string-match "\\`[ \t]*\\'" group)))
2369         (ignore
2370          (message
2371           "The newsgroups field is empty or missing.  Posting is denied.")))))
2372    ;; Check the Subject header.
2373    (message-check 'subject
2374      (let* ((case-fold-search t)
2375             (subject (message-fetch-field "subject")))
2376        (or
2377         (and subject
2378              (not (string-match "\\`[ \t]*\\'" subject)))
2379         (ignore
2380          (message
2381           "The subject field is empty or missing.  Posting is denied.")))))
2382    ;; Check for commands in Subject.
2383    (message-check 'subject-cmsg
2384      (if (string-match "^cmsg " (message-fetch-field "subject"))
2385          (y-or-n-p
2386           "The control code \"cmsg\" is in the subject.  Really post? ")
2387        t))
2388    ;; Check for multiple identical headers.
2389    (message-check 'multiple-headers
2390      (let (found)
2391        (while (and (not found)
2392                    (re-search-forward "^[^ \t:]+: " nil t))
2393          (save-excursion
2394            (or (re-search-forward
2395                 (concat "^"
2396                         (regexp-quote
2397                          (setq found
2398                                (buffer-substring
2399                                 (match-beginning 0) (- (match-end 0) 2))))
2400                         ":")
2401                 nil t)
2402                (setq found nil))))
2403        (if found
2404            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2405          t)))
2406    ;; Check for Version and Sendsys.
2407    (message-check 'sendsys
2408      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2409          (y-or-n-p
2410           (format "The article contains a %s command.  Really post? "
2411                   (buffer-substring (match-beginning 0)
2412                                     (1- (match-end 0)))))
2413        t))
2414    ;; See whether we can shorten Followup-To.
2415    (message-check 'shorten-followup-to
2416      (let ((newsgroups (message-fetch-field "newsgroups"))
2417            (followup-to (message-fetch-field "followup-to"))
2418            to)
2419        (when (and newsgroups
2420                   (string-match "," newsgroups)
2421                   (not followup-to)
2422                   (not
2423                    (zerop
2424                     (length
2425                      (setq to (completing-read
2426                                "Followups to: (default all groups) "
2427                                (mapcar (lambda (g) (list g))
2428                                        (cons "poster"
2429                                              (message-tokenize-header
2430                                               newsgroups)))))))))
2431          (goto-char (point-min))
2432          (insert "Followup-To: " to "\n"))
2433        t))
2434    ;; Check "Shoot me".
2435    (message-check 'shoot
2436      (if (re-search-forward
2437           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2438          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2439        t))
2440    ;; Check for Approved.
2441    (message-check 'approved
2442      (if (re-search-forward "^Approved:" nil t)
2443          (y-or-n-p "The article contains an Approved header.  Really post? ")
2444        t))
2445    ;; Check the Message-ID header.
2446    (message-check 'message-id
2447      (let* ((case-fold-search t)
2448             (message-id (message-fetch-field "message-id" t)))
2449        (or (not message-id)
2450            ;; Is there an @ in the ID?
2451            (and (string-match "@" message-id)
2452                 ;; Is there a dot in the ID?
2453                 (string-match "@[^.]*\\." message-id)
2454                 ;; Does the ID end with a dot?
2455                 (not (string-match "\\.>" message-id)))
2456            (y-or-n-p
2457             (format "The Message-ID looks strange: \"%s\".  Really post? "
2458                     message-id)))))
2459    ;; Check the Newsgroups & Followup-To headers.
2460    (message-check 'existing-newsgroups
2461      (let* ((case-fold-search t)
2462             (newsgroups (message-fetch-field "newsgroups"))
2463             (followup-to (message-fetch-field "followup-to"))
2464             (groups (message-tokenize-header
2465                      (if followup-to
2466                          (concat newsgroups "," followup-to)
2467                        newsgroups)))
2468             (hashtb (and (boundp 'gnus-active-hashtb)
2469                          gnus-active-hashtb))
2470             errors)
2471        (if (or (not hashtb)