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