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