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