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