Importing pgnus-0.13
[elisp/gnus.git-] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'mailheader)
35 (require 'nnheader)
36 (require 'timezone)
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 . X-Newsreader))
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 X-Newsreader 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 . X-Mailer))
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 X-Mailer 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     (X-Mailer)
944     (X-Newsreader))
945   "Alist used for formatting headers.")
946
947 (eval-and-compile
948   (autoload 'message-setup-toolbar "messagexmas")
949   (autoload 'mh-new-draft-name "mh-comp")
950   (autoload 'mh-send-letter "mh-comp")
951   (autoload 'gnus-point-at-eol "gnus-util")
952   (autoload 'gnus-point-at-bol "gnus-util")
953   (autoload 'gnus-output-to-mail "gnus-util")
954   (autoload 'gnus-output-to-rmail "gnus-util")
955   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
956   (autoload 'nndraft-request-associate-buffer "nndraft")
957   (autoload 'nndraft-request-expire-articles "nndraft")
958   (autoload 'gnus-open-server "gnus-int")
959   (autoload 'gnus-request-post "gnus-int")
960   (autoload 'gnus-alive-p "gnus-util")
961   (autoload 'rmail-output "rmail"))
962
963 \f
964
965 ;;;
966 ;;; Utility functions.
967 ;;;
968
969 (defmacro message-y-or-n-p (question show &rest text)
970   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
971   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
972
973 ;; Delete the current line (and the next N lines.);
974 (defmacro message-delete-line (&optional n)
975   `(delete-region (progn (beginning-of-line) (point))
976                   (progn (forward-line ,(or n 1)) (point))))
977
978 (defun message-tokenize-header (header &optional separator)
979   "Split HEADER into a list of header elements.
980 \",\" is used as the separator."
981   (if (not header)
982       nil
983     (let ((regexp (format "[%s]+" (or separator ",")))
984           (beg 1)
985           (first t)
986           quoted elems paren)
987       (save-excursion
988         (message-set-work-buffer)
989         (insert header)
990         (goto-char (point-min))
991         (while (not (eobp))
992           (if first
993               (setq first nil)
994             (forward-char 1))
995           (cond ((and (> (point) beg)
996                       (or (eobp)
997                           (and (looking-at regexp)
998                                (not quoted)
999                                (not paren))))
1000                  (push (buffer-substring beg (point)) elems)
1001                  (setq beg (match-end 0)))
1002                 ((= (following-char) ?\")
1003                  (setq quoted (not quoted)))
1004                 ((and (= (following-char) ?\()
1005                       (not quoted))
1006                  (setq paren t))
1007                 ((and (= (following-char) ?\))
1008                       (not quoted))
1009                  (setq paren nil))))
1010         (nreverse elems)))))
1011
1012 (defun message-mail-file-mbox-p (file)
1013   "Say whether FILE looks like a Unix mbox file."
1014   (when (and (file-exists-p file)
1015              (file-readable-p file)
1016              (file-regular-p file))
1017     (with-temp-buffer
1018       (nnheader-insert-file-contents file)
1019       (goto-char (point-min))
1020       (looking-at message-unix-mail-delimiter))))
1021
1022 (defun message-fetch-field (header &optional not-all)
1023   "The same as `mail-fetch-field', only remove all newlines."
1024   (let* ((inhibit-point-motion-hooks t)
1025          (value (mail-fetch-field header nil (not not-all))))
1026     (when value
1027       (nnheader-replace-chars-in-string value ?\n ? ))))
1028
1029 (defun message-narrow-to-field ()
1030   "Narrow the buffer to the header on the current line."
1031   (beginning-of-line)
1032   (narrow-to-region
1033    (point)
1034    (progn
1035      (forward-line 1)
1036      (if (re-search-forward "^[^ \n\t]" nil t)
1037          (progn
1038            (beginning-of-line)
1039            (point))
1040        (point-max))))
1041   (goto-char (point-min)))
1042
1043 (defun message-add-header (&rest headers)
1044   "Add the HEADERS to the message header, skipping those already present."
1045   (while headers
1046     (let (hclean)
1047       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1048         (error "Invalid header `%s'" (car headers)))
1049       (setq hclean (match-string 1 (car headers)))
1050     (save-restriction
1051       (message-narrow-to-headers)
1052       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1053         (insert (car headers) ?\n))))
1054     (setq headers (cdr headers))))
1055
1056 (defun message-fetch-reply-field (header)
1057   "Fetch FIELD from the message we're replying to."
1058   (when (and message-reply-buffer
1059              (buffer-name message-reply-buffer))
1060     (save-excursion
1061       (set-buffer message-reply-buffer)
1062       (message-fetch-field header))))
1063
1064 (defun message-set-work-buffer ()
1065   (if (get-buffer " *message work*")
1066       (progn
1067         (set-buffer " *message work*")
1068         (erase-buffer))
1069     (set-buffer (get-buffer-create " *message work*"))
1070     (kill-all-local-variables)
1071     (mm-enable-multibyte)))
1072
1073 (defun message-functionp (form)
1074   "Return non-nil if FORM is funcallable."
1075   (or (and (symbolp form) (fboundp form))
1076       (and (listp form) (eq (car form) 'lambda))
1077       (byte-code-function-p form)))
1078
1079 (defun message-strip-subject-re (subject)
1080   "Remove \"Re:\" from subject lines."
1081   (if (string-match message-subject-re-regexp subject)
1082       (substring subject (match-end 0))
1083     subject))
1084
1085 (defun message-remove-header (header &optional is-regexp first reverse)
1086   "Remove HEADER in the narrowed buffer.
1087 If REGEXP, HEADER is a regular expression.
1088 If FIRST, only remove the first instance of the header.
1089 Return the number of headers removed."
1090   (goto-char (point-min))
1091   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1092         (number 0)
1093         (case-fold-search t)
1094         last)
1095     (while (and (not (eobp))
1096                 (not last))
1097       (if (if reverse
1098               (not (looking-at regexp))
1099             (looking-at regexp))
1100           (progn
1101             (incf number)
1102             (when first
1103               (setq last t))
1104             (delete-region
1105              (point)
1106              ;; There might be a continuation header, so we have to search
1107              ;; until we find a new non-continuation line.
1108              (progn
1109                (forward-line 1)
1110                (if (re-search-forward "^[^ \t]" nil t)
1111                    (goto-char (match-beginning 0))
1112                  (point-max)))))
1113         (forward-line 1)
1114         (if (re-search-forward "^[^ \t]" nil t)
1115             (goto-char (match-beginning 0))
1116           (point-max))))
1117     number))
1118
1119 (defun message-narrow-to-headers ()
1120   "Narrow the buffer to the head of the message."
1121   (widen)
1122   (narrow-to-region
1123    (goto-char (point-min))
1124    (if (re-search-forward
1125         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1126        (match-beginning 0)
1127      (point-max)))
1128   (goto-char (point-min)))
1129
1130 (defun message-narrow-to-head ()
1131   "Narrow the buffer to the head of the message.
1132 Point is left at the beginning of the narrowed-to region."
1133   (widen)
1134   (narrow-to-region
1135    (goto-char (point-min))
1136    (if (search-forward "\n\n" nil 1)
1137        (1- (point))
1138      (point-max)))
1139   (goto-char (point-min)))
1140
1141 (defun message-news-p ()
1142   "Say whether the current buffer contains a news message."
1143   (and (not message-this-is-mail)
1144        (or message-this-is-news
1145            (save-excursion
1146              (save-restriction
1147                (message-narrow-to-headers)
1148                (and (message-fetch-field "newsgroups")
1149                     (not (message-fetch-field "posted-to"))))))))
1150
1151 (defun message-mail-p ()
1152   "Say whether the current buffer contains a mail message."
1153   (and (not message-this-is-news)
1154        (or message-this-is-mail
1155            (save-excursion
1156              (save-restriction
1157                (message-narrow-to-headers)
1158                (or (message-fetch-field "to")
1159                    (message-fetch-field "cc")
1160                    (message-fetch-field "bcc")))))))
1161
1162 (defun message-next-header ()
1163   "Go to the beginning of the next header."
1164   (beginning-of-line)
1165   (or (eobp) (forward-char 1))
1166   (not (if (re-search-forward "^[^ \t]" nil t)
1167            (beginning-of-line)
1168          (goto-char (point-max)))))
1169
1170 (defun message-sort-headers-1 ()
1171   "Sort the buffer as headers using `message-rank' text props."
1172   (goto-char (point-min))
1173   (sort-subr
1174    nil 'message-next-header
1175    (lambda ()
1176      (message-next-header)
1177      (unless (bobp)
1178        (forward-char -1)))
1179    (lambda ()
1180      (or (get-text-property (point) 'message-rank)
1181          10000))))
1182
1183 (defun message-sort-headers ()
1184   "Sort the headers of the current message according to `message-header-format-alist'."
1185   (interactive)
1186   (save-excursion
1187     (save-restriction
1188       (let ((max (1+ (length message-header-format-alist)))
1189             rank)
1190         (message-narrow-to-headers)
1191         (while (re-search-forward "^[^ \n]+:" nil t)
1192           (put-text-property
1193            (match-beginning 0) (1+ (match-beginning 0))
1194            'message-rank
1195            (if (setq rank (length (memq (assq (intern (buffer-substring
1196                                                        (match-beginning 0)
1197                                                        (1- (match-end 0))))
1198                                               message-header-format-alist)
1199                                         message-header-format-alist)))
1200                (- max rank)
1201              (1+ max)))))
1202       (message-sort-headers-1))))
1203
1204 \f
1205
1206 ;;;
1207 ;;; Message mode
1208 ;;;
1209
1210 ;;; Set up keymap.
1211
1212 (defvar message-mode-map nil)
1213
1214 (unless message-mode-map
1215   (setq message-mode-map (copy-keymap text-mode-map))
1216   (define-key message-mode-map "\C-c?" 'describe-mode)
1217
1218   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1219   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1220   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1221   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1222   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1223   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1224   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1225   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1226   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1227   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1228   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1229   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1230   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1231
1232   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1233   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1234
1235   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1236   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1237   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1238   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1239   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1240   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1241
1242   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1243   (define-key message-mode-map "\C-c\C-s" 'message-send)
1244   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1245   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1246
1247   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1248   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1249   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1250   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1251
1252   (define-key message-mode-map "\t" 'message-tab))
1253
1254 (easy-menu-define
1255  message-mode-menu message-mode-map "Message Menu."
1256  '("Message"
1257    ["Sort Headers" message-sort-headers t]
1258    ["Yank Original" message-yank-original t]
1259    ["Fill Yanked Message" message-fill-yanked-message t]
1260    ["Insert Signature" message-insert-signature t]
1261    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1262    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1263    ["Elide Region" message-elide-region (mark t)]
1264    ["Delete Outside Region" message-delete-not-region (mark t)]
1265    ["Kill To Signature" message-kill-to-signature t]
1266    ["Newline and Reformat" message-newline-and-reformat t]
1267    ["Rename buffer" message-rename-buffer t]
1268    ["Spellcheck" ispell-message t]
1269    "----"
1270    ["Send Message" message-send-and-exit t]
1271    ["Abort Message" message-dont-send t]
1272    ["Kill Message" message-kill-buffer t]))
1273
1274 (easy-menu-define
1275  message-mode-field-menu message-mode-map ""
1276  '("Field"
1277    ["Fetch To" message-insert-to t]
1278    ["Fetch Newsgroups" message-insert-newsgroups t]
1279    "----"
1280    ["To" message-goto-to t]
1281    ["Subject" message-goto-subject t]
1282    ["Cc" message-goto-cc t]
1283    ["Reply-To" message-goto-reply-to t]
1284    ["Summary" message-goto-summary t]
1285    ["Keywords" message-goto-keywords t]
1286    ["Newsgroups" message-goto-newsgroups t]
1287    ["Followup-To" message-goto-followup-to t]
1288    ["Distribution" message-goto-distribution t]
1289    ["Body" message-goto-body t]
1290    ["Signature" message-goto-signature t]))
1291
1292 (defvar facemenu-add-face-function)
1293 (defvar facemenu-remove-face-function)
1294
1295 ;;;###autoload
1296 (defun message-mode ()
1297   "Major mode for editing mail and news to be sent.
1298 Like Text Mode but with these additional commands:
1299 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1300 C-c C-f  move to a header field (and create it if there isn't):
1301          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1302          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1303          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1304          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1305          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1306          C-c C-f C-f  move to Followup-To
1307 C-c C-t  message-insert-to (add a To header to a news followup)
1308 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1309 C-c C-b  message-goto-body (move to beginning of message text).
1310 C-c C-i  message-goto-signature (move to the beginning of the signature).
1311 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1312 C-c C-y  message-yank-original (insert current message, if any).
1313 C-c C-q  message-fill-yanked-message (fill what was yanked).
1314 C-c C-e  message-elide-region (elide the text between point and mark).
1315 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1316 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1317   (interactive)
1318   (kill-all-local-variables)
1319   (make-local-variable 'message-reply-buffer)
1320   (setq message-reply-buffer nil)
1321   (make-local-variable 'message-send-actions) 
1322   (make-local-variable 'message-exit-actions) 
1323   (make-local-variable 'message-kill-actions)
1324   (make-local-variable 'message-postpone-actions)
1325   (make-local-variable 'message-draft-article)
1326   (make-local-hook 'kill-buffer-hook)
1327   (set-syntax-table message-mode-syntax-table)
1328   (use-local-map message-mode-map)
1329   (setq local-abbrev-table message-mode-abbrev-table)
1330   (setq major-mode 'message-mode)
1331   (setq mode-name "Message")
1332   (setq buffer-offer-save t)
1333   (make-local-variable 'facemenu-add-face-function)
1334   (make-local-variable 'facemenu-remove-face-function)
1335   (setq facemenu-add-face-function
1336         (lambda (face end)
1337           (let ((face-fun (cdr (assq face message-face-alist))))
1338             (if face-fun
1339                 (funcall face-fun (point) end)
1340               (error "Face %s not configured for %s mode" face mode-name)))
1341           "")
1342         facemenu-remove-face-function t)
1343   (make-local-variable 'paragraph-separate)
1344   (make-local-variable 'paragraph-start)
1345   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1346   ;; lines that delimit forwarded messages.
1347   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1348   ;; are also sometimes used and should be separators.
1349   (setq paragraph-start
1350         (concat (regexp-quote mail-header-separator)
1351                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1352                 "-- $\\|---+$\\|"
1353                 page-delimiter
1354                 ;;!!! Uhm... shurely this can't be right?
1355                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1356   (setq paragraph-separate paragraph-start)
1357   (make-local-variable 'message-reply-headers)
1358   (setq message-reply-headers nil)
1359   (make-local-variable 'message-newsreader)
1360   (make-local-variable 'message-mailer)
1361   (make-local-variable 'message-post-method)
1362   (make-local-variable 'message-sent-message-via)
1363   (setq message-sent-message-via nil)
1364   (make-local-variable 'message-checksum)
1365   (setq message-checksum nil)
1366   ;;(when (fboundp 'mail-hist-define-keys)
1367   ;;  (mail-hist-define-keys))
1368   (when (string-match "XEmacs\\|Lucid" emacs-version)
1369     (message-setup-toolbar))
1370   (easy-menu-add message-mode-menu message-mode-map)
1371   (easy-menu-add message-mode-field-menu message-mode-map)
1372   ;; Allow mail alias things.
1373   (when (eq message-mail-alias-type 'abbrev)
1374     (if (fboundp 'mail-abbrevs-setup)
1375         (mail-abbrevs-setup)
1376       (mail-aliases-setup)))
1377   (message-set-auto-save-file-name)
1378   (unless (string-match "XEmacs" emacs-version)
1379     (set (make-local-variable 'font-lock-defaults)
1380          '(message-font-lock-keywords t)))
1381   (make-local-variable 'adaptive-fill-regexp)
1382   (setq adaptive-fill-regexp
1383         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1384   (unless (boundp 'adaptive-fill-first-line-regexp)
1385     (setq adaptive-fill-first-line-regexp nil))
1386   (make-local-variable 'adaptive-fill-first-line-regexp)
1387   (setq adaptive-fill-first-line-regexp
1388         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1389                 adaptive-fill-first-line-regexp))
1390   (mm-enable-multibyte)
1391   (run-hooks 'text-mode-hook 'message-mode-hook))
1392
1393 \f
1394
1395 ;;;
1396 ;;; Message mode commands
1397 ;;;
1398
1399 ;;; Movement commands
1400
1401 (defun message-goto-to ()
1402   "Move point to the To header."
1403   (interactive)
1404   (message-position-on-field "To"))
1405
1406 (defun message-goto-subject ()
1407   "Move point to the Subject header."
1408   (interactive)
1409   (message-position-on-field "Subject"))
1410
1411 (defun message-goto-cc ()
1412   "Move point to the Cc header."
1413   (interactive)
1414   (message-position-on-field "Cc" "To"))
1415
1416 (defun message-goto-bcc ()
1417   "Move point to the Bcc  header."
1418   (interactive)
1419   (message-position-on-field "Bcc" "Cc" "To"))
1420
1421 (defun message-goto-fcc ()
1422   "Move point to the Fcc header."
1423   (interactive)
1424   (message-position-on-field "Fcc" "To" "Newsgroups"))
1425
1426 (defun message-goto-reply-to ()
1427   "Move point to the Reply-To header."
1428   (interactive)
1429   (message-position-on-field "Reply-To" "Subject"))
1430
1431 (defun message-goto-newsgroups ()
1432   "Move point to the Newsgroups header."
1433   (interactive)
1434   (message-position-on-field "Newsgroups"))
1435
1436 (defun message-goto-distribution ()
1437   "Move point to the Distribution header."
1438   (interactive)
1439   (message-position-on-field "Distribution"))
1440
1441 (defun message-goto-followup-to ()
1442   "Move point to the Followup-To header."
1443   (interactive)
1444   (message-position-on-field "Followup-To" "Newsgroups"))
1445
1446 (defun message-goto-keywords ()
1447   "Move point to the Keywords header."
1448   (interactive)
1449   (message-position-on-field "Keywords" "Subject"))
1450
1451 (defun message-goto-summary ()
1452   "Move point to the Summary header."
1453   (interactive)
1454   (message-position-on-field "Summary" "Subject"))
1455
1456 (defun message-goto-body ()
1457   "Move point to the beginning of the message body."
1458   (interactive)
1459   (if (looking-at "[ \t]*\n") (expand-abbrev))
1460   (goto-char (point-min))
1461   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1462
1463 (defun message-goto-eoh ()
1464   "Move point to the end of the headers."
1465   (interactive)
1466   (message-goto-body)
1467   (forward-line -2))
1468
1469 (defun message-goto-signature ()
1470   "Move point to the beginning of the message signature.
1471 If there is no signature in the article, go to the end and
1472 return nil."
1473   (interactive)
1474   (goto-char (point-min))
1475   (if (re-search-forward message-signature-separator nil t)
1476       (forward-line 1)
1477     (goto-char (point-max))
1478     nil))
1479
1480 \f
1481
1482 (defun message-insert-to (&optional force)
1483   "Insert a To header that points to the author of the article being replied to.
1484 If the original author requested not to be sent mail, the function signals
1485 an error.
1486 With the prefix argument FORCE, insert the header anyway."
1487   (interactive "P")
1488   (let ((co (message-fetch-reply-field "mail-copies-to")))
1489     (when (and (null force)
1490                co
1491                (equal (downcase co) "never"))
1492       (error "The user has requested not to have copies sent via mail")))
1493   (when (and (message-position-on-field "To")
1494              (mail-fetch-field "to")
1495              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1496     (insert ", "))
1497   (insert (or (message-fetch-reply-field "reply-to")
1498               (message-fetch-reply-field "from") "")))
1499
1500 (defun message-insert-newsgroups ()
1501   "Insert the Newsgroups header from the article being replied to."
1502   (interactive)
1503   (when (and (message-position-on-field "Newsgroups")
1504              (mail-fetch-field "newsgroups")
1505              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1506     (insert ","))
1507   (insert (or (message-fetch-reply-field "newsgroups") "")))
1508
1509 \f
1510
1511 ;;; Various commands
1512
1513 (defun message-delete-not-region (beg end)
1514   "Delete everything in the body of the current message that is outside of the region."
1515   (interactive "r")
1516   (save-excursion
1517     (goto-char end)
1518     (delete-region (point) (if (not (message-goto-signature))
1519                                (point)
1520                              (forward-line -2)
1521                              (point)))
1522     (insert "\n")
1523     (goto-char beg)
1524     (delete-region beg (progn (message-goto-body)
1525                               (forward-line 2)
1526                               (point))))
1527   (when (message-goto-signature)
1528     (forward-line -2)))
1529
1530 (defun message-kill-to-signature ()
1531   "Deletes all text up to the signature."
1532   (interactive)
1533   (let ((point (point)))
1534     (message-goto-signature)
1535     (unless (eobp)
1536       (forward-line -2))
1537     (kill-region point (point))
1538     (unless (bolp)
1539       (insert "\n"))))
1540
1541 (defun message-newline-and-reformat ()
1542   "Insert four newlines, and then reformat if inside quoted text."
1543   (interactive)
1544   (let ((point (point))
1545         quoted)
1546     (save-excursion
1547       (beginning-of-line)
1548       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1549     (insert "\n\n\n\n")
1550     (when quoted
1551       (insert message-yank-prefix))
1552     (fill-paragraph nil)
1553     (goto-char point)
1554     (forward-line 2)))
1555
1556 (defun message-insert-signature (&optional force)
1557   "Insert a signature.  See documentation for the `message-signature' variable."
1558   (interactive (list 0))
1559   (let* ((signature
1560           (cond
1561            ((and (null message-signature)
1562                  (eq force 0))
1563             (save-excursion
1564               (goto-char (point-max))
1565               (not (re-search-backward
1566                     message-signature-separator nil t))))
1567            ((and (null message-signature)
1568                  force)
1569             t)
1570            ((message-functionp message-signature)
1571             (funcall message-signature))
1572            ((listp message-signature)
1573             (eval message-signature))
1574            (t message-signature)))
1575          (signature
1576           (cond ((stringp signature)
1577                  signature)
1578                 ((and (eq t signature)
1579                       message-signature-file
1580                       (file-exists-p message-signature-file))
1581                  signature))))
1582     (when signature
1583       (goto-char (point-max))
1584       ;; Insert the signature.
1585       (unless (bolp)
1586         (insert "\n"))
1587       (insert "\n-- \n")
1588       (if (eq signature t)
1589           (insert-file-contents message-signature-file)
1590         (insert signature))
1591       (goto-char (point-max))
1592       (or (bolp) (insert "\n")))))
1593
1594 (defun message-elide-region (b e)
1595   "Elide the text between point and mark.
1596 An ellipsis (from `message-elide-elipsis') will be inserted where the
1597 text was killed."
1598   (interactive "r")
1599   (kill-region b e)
1600   (unless (bolp)
1601     (insert "\n"))
1602   (insert message-elide-elipsis))
1603
1604 (defvar message-caesar-translation-table nil)
1605
1606 (defun message-caesar-region (b e &optional n)
1607   "Caesar rotation of region by N, default 13, for decrypting netnews."
1608   (interactive
1609    (list
1610     (min (point) (or (mark t) (point)))
1611     (max (point) (or (mark t) (point)))
1612     (when current-prefix-arg
1613       (prefix-numeric-value current-prefix-arg))))
1614
1615   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1616   (unless (or (zerop n)                 ; no action needed for a rot of 0
1617               (= b e))                  ; no region to rotate
1618     ;; We build the table, if necessary.
1619     (when (or (not message-caesar-translation-table)
1620               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1621         (setq message-caesar-translation-table
1622               (message-make-caesar-translation-table n)))
1623     ;; Then we translate the region.  Do it this way to retain
1624     ;; text properties.
1625     (while (< b e)
1626       (subst-char-in-region
1627        b (1+ b) (char-after b)
1628        (aref message-caesar-translation-table (char-after b)))
1629       (incf b))))
1630
1631 (defun message-make-caesar-translation-table (n)
1632   "Create a rot table with offset N."
1633   (let ((i -1)
1634         (table (make-string 256 0)))
1635     (while (< (incf i) 256)
1636       (aset table i i))
1637     (concat
1638      (substring table 0 ?A)
1639      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1640      (substring table ?A (+ ?A n))
1641      (substring table (+ ?A 26) ?a)
1642      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1643      (substring table ?a (+ ?a n))
1644      (substring table (+ ?a 26) 255))))
1645
1646 (defun message-caesar-buffer-body (&optional rotnum)
1647   "Caesar rotates all letters in the current buffer by 13 places.
1648 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1649 With prefix arg, specifies the number of places to rotate each letter forward.
1650 Mail and USENET news headers are not rotated."
1651   (interactive (if current-prefix-arg
1652                    (list (prefix-numeric-value current-prefix-arg))
1653                  (list nil)))
1654   (save-excursion
1655     (save-restriction
1656       (when (message-goto-body)
1657         (narrow-to-region (point) (point-max)))
1658       (message-caesar-region (point-min) (point-max) rotnum))))
1659
1660 (defun message-pipe-buffer-body (program)
1661   "Pipe the message body in the current buffer through PROGRAM."
1662   (save-excursion
1663     (save-restriction
1664       (when (message-goto-body)
1665         (narrow-to-region (point) (point-max)))
1666       (let ((body (buffer-substring (point-min) (point-max))))
1667         (unless (equal 0 (call-process-region
1668                            (point-min) (point-max) program t t))
1669             (insert body)
1670             (message "%s failed." program))))))
1671
1672 (defun message-rename-buffer (&optional enter-string)
1673   "Rename the *message* buffer to \"*message* RECIPIENT\".
1674 If the function is run with a prefix, it will ask for a new buffer
1675 name, rather than giving an automatic name."
1676   (interactive "Pbuffer name: ")
1677   (save-excursion
1678     (save-restriction
1679       (goto-char (point-min))
1680       (narrow-to-region (point)
1681                         (search-forward mail-header-separator nil 'end))
1682       (let* ((mail-to (or
1683                        (if (message-news-p) (message-fetch-field "Newsgroups")
1684                          (message-fetch-field "To"))
1685                        ""))
1686              (mail-trimmed-to
1687               (if (string-match "," mail-to)
1688                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1689                 mail-to))
1690              (name-default (concat "*message* " mail-trimmed-to))
1691              (name (if enter-string
1692                        (read-string "New buffer name: " name-default)
1693                      name-default)))
1694         (rename-buffer name t)))))
1695
1696 (defun message-fill-yanked-message (&optional justifyp)
1697   "Fill the paragraphs of a message yanked into this one.
1698 Numeric argument means justify as well."
1699   (interactive "P")
1700   (save-excursion
1701     (goto-char (point-min))
1702     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1703     (let ((fill-prefix message-yank-prefix))
1704       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1705
1706 (defun message-indent-citation ()
1707   "Modify text just inserted from a message to be cited.
1708 The inserted text should be the region.
1709 When this function returns, the region is again around the modified text.
1710
1711 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1712 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1713   (let ((start (point)))
1714     ;; Remove unwanted headers.
1715     (when message-ignored-cited-headers
1716       (let (all-removed)
1717         (save-restriction
1718           (narrow-to-region
1719            (goto-char start)
1720            (if (search-forward "\n\n" nil t)
1721                (1- (point))
1722              (point)))
1723           (message-remove-header message-ignored-cited-headers t)
1724           (when (= (point-min) (point-max))
1725             (setq all-removed t))
1726           (goto-char (point-max)))
1727         (if all-removed
1728             (goto-char start)
1729           (forward-line 1))))
1730     ;; Delete blank lines at the start of the buffer.
1731     (while (and (point-min)
1732                 (eolp)
1733                 (not (eobp)))
1734       (message-delete-line))
1735     ;; Delete blank lines at the end of the buffer.
1736     (goto-char (point-max))
1737     (unless (eolp)
1738       (insert "\n"))
1739     (while (and (zerop (forward-line -1))
1740                 (looking-at "$"))
1741       (message-delete-line))
1742     ;; Do the indentation.
1743     (if (null message-yank-prefix)
1744         (indent-rigidly start (mark t) message-indentation-spaces)
1745       (save-excursion
1746         (goto-char start)
1747         (while (< (point) (mark t))
1748           (insert message-yank-prefix)
1749           (forward-line 1))))
1750     (goto-char start)))
1751
1752 (defun message-yank-original (&optional arg)
1753   "Insert the message being replied to, if any.
1754 Puts point before the text and mark after.
1755 Normally indents each nonblank line ARG spaces (default 3).  However,
1756 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1757
1758 This function uses `message-cite-function' to do the actual citing.
1759
1760 Just \\[universal-argument] as argument means don't indent, insert no
1761 prefix, and don't delete any headers."
1762   (interactive "P")
1763   (let ((modified (buffer-modified-p)))
1764     (when (and message-reply-buffer
1765                message-cite-function)
1766       (delete-windows-on message-reply-buffer t)
1767       (insert-buffer message-reply-buffer)
1768       (funcall message-cite-function)
1769       (message-exchange-point-and-mark)
1770       (unless (bolp)
1771         (insert ?\n))
1772       (unless modified
1773         (setq message-checksum (message-checksum))))))
1774
1775 (defun message-cite-original-without-signature ()
1776   "Cite function in the standard Message manner."
1777   (let ((start (point))
1778         (end (mark t))
1779         (functions
1780          (when message-indent-citation-function
1781            (if (listp message-indent-citation-function)
1782                message-indent-citation-function
1783              (list message-indent-citation-function)))))
1784     (goto-char end)
1785     (when (re-search-backward "^-- $" start t)
1786       ;; Also peel off any blank lines before the signature.
1787       (forward-line -1)
1788       (while (looking-at "^[ \t]*$")
1789         (forward-line -1))
1790       (forward-line 1)
1791       (delete-region (point) end))
1792     (goto-char start)
1793     (while functions
1794       (funcall (pop functions)))
1795     (when message-citation-line-function
1796       (unless (bolp)
1797         (insert "\n"))
1798       (funcall message-citation-line-function))))
1799
1800 (defvar mail-citation-hook) ;Compiler directive
1801 (defun message-cite-original ()
1802   "Cite function in the standard Message manner."
1803   (if (and (boundp 'mail-citation-hook)
1804            mail-citation-hook)
1805       (run-hooks 'mail-citation-hook)
1806     (let ((start (point))
1807           (functions
1808            (when message-indent-citation-function
1809              (if (listp message-indent-citation-function)
1810                  message-indent-citation-function
1811                (list message-indent-citation-function)))))
1812       (goto-char start)
1813       (while functions
1814         (funcall (pop functions)))
1815       (when message-citation-line-function
1816         (unless (bolp)
1817           (insert "\n"))
1818         (funcall message-citation-line-function)))))
1819
1820 (defun message-insert-citation-line ()
1821   "Function that inserts a simple citation line."
1822   (when message-reply-headers
1823     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1824
1825 (defun message-position-on-field (header &rest afters)
1826   (let ((case-fold-search t))
1827     (save-restriction
1828       (narrow-to-region
1829        (goto-char (point-min))
1830        (progn
1831          (re-search-forward
1832           (concat "^" (regexp-quote mail-header-separator) "$"))
1833          (match-beginning 0)))
1834       (goto-char (point-min))
1835       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1836           (progn
1837             (re-search-forward "^[^ \t]" nil 'move)
1838             (beginning-of-line)
1839             (skip-chars-backward "\n")
1840             t)
1841         (while (and afters
1842                     (not (re-search-forward
1843                           (concat "^" (regexp-quote (car afters)) ":")
1844                           nil t)))
1845           (pop afters))
1846         (when afters
1847           (re-search-forward "^[^ \t]" nil 'move)
1848           (beginning-of-line))
1849         (insert header ": \n")
1850         (forward-char -1)
1851         nil))))
1852
1853 (defun message-remove-signature ()
1854   "Remove the signature from the text between point and mark.
1855 The text will also be indented the normal way."
1856   (save-excursion
1857     (let ((start (point))
1858           mark)
1859       (if (not (re-search-forward message-signature-separator (mark t) t))
1860           ;; No signature here, so we just indent the cited text.
1861           (message-indent-citation)
1862         ;; Find the last non-empty line.
1863         (forward-line -1)
1864         (while (looking-at "[ \t]*$")
1865           (forward-line -1))
1866         (forward-line 1)
1867         (setq mark (set-marker (make-marker) (point)))
1868         (goto-char start)
1869         (message-indent-citation)
1870         ;; Enable undoing the deletion.
1871         (undo-boundary)
1872         (delete-region mark (mark t))
1873         (set-marker mark nil)))))
1874
1875 \f
1876
1877 ;;;
1878 ;;; Sending messages
1879 ;;;
1880
1881 (defun message-send-and-exit (&optional arg)
1882   "Send message like `message-send', then, if no errors, exit from mail buffer."
1883   (interactive "P")
1884   (let ((buf (current-buffer))
1885         (actions message-exit-actions))
1886     (when (and (message-send arg)
1887                (buffer-name buf))
1888       (if message-kill-buffer-on-exit
1889           (kill-buffer buf)
1890         (bury-buffer buf)
1891         (when (eq buf (current-buffer))
1892           (message-bury buf)))
1893       (message-do-actions actions))))
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       (gnus-output-to-rmail 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 ()
2619   "Make a valid data header."
2620   (let ((now (current-time)))
2621     (timezone-make-date-arpa-standard
2622      (current-time-string now) (current-time-zone now))))
2623
2624 (defun message-make-message-id ()
2625   "Make a unique Message-ID."
2626   (concat "<" (message-unique-id)
2627           (let ((psubject (save-excursion (message-fetch-field "subject")))
2628                 (psupersedes
2629                  (save-excursion (message-fetch-field "supersedes"))))
2630             (if (or
2631                  (and message-reply-headers
2632                       (mail-header-references message-reply-headers)
2633                       (mail-header-subject message-reply-headers)
2634                       psubject
2635                       (mail-header-subject message-reply-headers)
2636                       (not (string=
2637                             (message-strip-subject-re
2638                              (mail-header-subject message-reply-headers))
2639                             (message-strip-subject-re psubject))))
2640                  (and psupersedes
2641                       (string-match "_-_@" psupersedes)))
2642                 "_-_" ""))
2643           "@" (message-make-fqdn) ">"))
2644
2645 (defvar message-unique-id-char nil)
2646
2647 ;; If you ever change this function, make sure the new version
2648 ;; cannot generate IDs that the old version could.
2649 ;; You might for example insert a "." somewhere (not next to another dot
2650 ;; or string boundary), or modify the "fsf" string.
2651 (defun message-unique-id ()
2652   ;; Don't use microseconds from (current-time), they may be unsupported.
2653   ;; Instead we use this randomly inited counter.
2654   (setq message-unique-id-char
2655         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2656            ;; (current-time) returns 16-bit ints,
2657            ;; and 2^16*25 just fits into 4 digits i base 36.
2658            (* 25 25)))
2659   (let ((tm (current-time)))
2660     (concat
2661      (if (memq system-type '(ms-dos emx vax-vms))
2662          (let ((user (downcase (user-login-name))))
2663            (while (string-match "[^a-z0-9_]" user)
2664              (aset user (match-beginning 0) ?_))
2665            user)
2666        (message-number-base36 (user-uid) -1))
2667      (message-number-base36 (+ (car   tm)
2668                                (lsh (% message-unique-id-char 25) 16)) 4)
2669      (message-number-base36 (+ (nth 1 tm)
2670                                (lsh (/ message-unique-id-char 25) 16)) 4)
2671      ;; Append the newsreader name, because while the generated
2672      ;; ID is unique to this newsreader, other newsreaders might
2673      ;; otherwise generate the same ID via another algorithm.
2674      ".fsf")))
2675
2676 (defun message-number-base36 (num len)
2677   (if (if (< len 0)
2678           (<= num 0)
2679         (= len 0))
2680       ""
2681     (concat (message-number-base36 (/ num 36) (1- len))
2682             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2683                                   (% num 36))))))
2684
2685 (defun message-make-organization ()
2686   "Make an Organization header."
2687   (let* ((organization
2688           (when message-user-organization
2689                 (if (message-functionp message-user-organization)
2690                     (funcall message-user-organization)
2691                   message-user-organization))))
2692     (save-excursion
2693       (message-set-work-buffer)
2694       (cond ((stringp organization)
2695              (insert organization))
2696             ((and (eq t organization)
2697                   message-user-organization-file
2698                   (file-exists-p message-user-organization-file))
2699              (insert-file-contents message-user-organization-file)))
2700       (goto-char (point-min))
2701       (while (re-search-forward "[\t\n]+" nil t)
2702         (replace-match "" t t))
2703       (unless (zerop (buffer-size))
2704         (buffer-string)))))
2705
2706 (defun message-make-lines ()
2707   "Count the number of lines and return numeric string."
2708   (save-excursion
2709     (save-restriction
2710       (widen)
2711       (goto-char (point-min))
2712       (re-search-forward
2713        (concat "^" (regexp-quote mail-header-separator) "$"))
2714       (forward-line 1)
2715       (int-to-string (count-lines (point) (point-max))))))
2716
2717 (defun message-make-in-reply-to ()
2718   "Return the In-Reply-To header for this message."
2719   (when message-reply-headers
2720     (let ((from (mail-header-from message-reply-headers))
2721           (date (mail-header-date message-reply-headers)))
2722       (when from
2723         (let ((stop-pos
2724                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2725           (concat (if (and stop-pos
2726                            (not (zerop stop-pos)))
2727                       (substring from 0 stop-pos) from)
2728                   "'s message of \""
2729                   (if (or (not date) (string= date ""))
2730                       "(unknown date)" date)
2731                   "\""))))))
2732
2733 (defun message-make-distribution ()
2734   "Make a Distribution header."
2735   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2736     (cond ((message-functionp message-distribution-function)
2737            (funcall message-distribution-function))
2738           (t orig-distribution))))
2739
2740 (defun message-make-expires ()
2741   "Return an Expires header based on `message-expires'."
2742   (let ((current (current-time))
2743         (future (* 1.0 message-expires 60 60 24)))
2744     ;; Add the future to current.
2745     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2746     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2747     ;; Return the date in the future in UT.
2748     (timezone-make-date-arpa-standard
2749      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2750
2751 (defun message-make-path ()
2752   "Return uucp path."
2753   (let ((login-name (user-login-name)))
2754     (cond ((null message-user-path)
2755            (concat (system-name) "!" login-name))
2756           ((stringp message-user-path)
2757            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2758            (concat message-user-path "!" login-name))
2759           (t login-name))))
2760
2761 (defun message-make-from ()
2762   "Make a From header."
2763   (let* ((style message-from-style)
2764          (login (message-make-address))
2765          (fullname
2766           (or (and (boundp 'user-full-name)
2767                    user-full-name)
2768               (user-full-name))))
2769     (when (string= fullname "&")
2770       (setq fullname (user-login-name)))
2771     (save-excursion
2772       (message-set-work-buffer)
2773       (cond
2774        ((or (null style)
2775             (equal fullname ""))
2776         (insert login))
2777        ((or (eq style 'angles)
2778             (and (not (eq style 'parens))
2779                  ;; Use angles if no quoting is needed, or if parens would
2780                  ;; need quoting too.
2781                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2782                      (let ((tmp (concat fullname nil)))
2783                        (while (string-match "([^()]*)" tmp)
2784                          (aset tmp (match-beginning 0) ?-)
2785                          (aset tmp (1- (match-end 0)) ?-))
2786                        (string-match "[\\()]" tmp)))))
2787         (insert fullname)
2788         (goto-char (point-min))
2789         ;; Look for a character that cannot appear unquoted
2790         ;; according to RFC 822.
2791         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2792           ;; Quote fullname, escaping specials.
2793           (goto-char (point-min))
2794           (insert "\"")
2795           (while (re-search-forward "[\"\\]" nil 1)
2796             (replace-match "\\\\\\&" t))
2797           (insert "\""))
2798         (insert " <" login ">"))
2799        (t                               ; 'parens or default
2800         (insert login " (")
2801         (let ((fullname-start (point)))
2802           (insert fullname)
2803           (goto-char fullname-start)
2804           ;; RFC 822 says \ and nonmatching parentheses
2805           ;; must be escaped in comments.
2806           ;; Escape every instance of ()\ ...
2807           (while (re-search-forward "[()\\]" nil 1)
2808             (replace-match "\\\\\\&" t))
2809           ;; ... then undo escaping of matching parentheses,
2810           ;; including matching nested parentheses.
2811           (goto-char fullname-start)
2812           (while (re-search-forward
2813                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2814                   nil 1)
2815             (replace-match "\\1(\\3)" t)
2816             (goto-char fullname-start)))
2817         (insert ")")))
2818       (buffer-string))))
2819
2820 (defun message-make-sender ()
2821   "Return the \"real\" user address.
2822 This function tries to ignore all user modifications, and
2823 give as trustworthy answer as possible."
2824   (concat (user-login-name) "@" (system-name)))
2825
2826 (defun message-make-address ()
2827   "Make the address of the user."
2828   (or (message-user-mail-address)
2829       (concat (user-login-name) "@" (message-make-domain))))
2830
2831 (defun message-user-mail-address ()
2832   "Return the pertinent part of `user-mail-address'."
2833   (when user-mail-address
2834     (if (string-match " " user-mail-address)
2835         (nth 1 (mail-extract-address-components user-mail-address))
2836       user-mail-address)))
2837
2838 (defun message-make-fqdn ()
2839   "Return user's fully qualified domain name."
2840   (let ((system-name (system-name))
2841         (user-mail (message-user-mail-address)))
2842     (cond
2843      ((string-match "[^.]\\.[^.]" system-name)
2844       ;; `system-name' returned the right result.
2845       system-name)
2846      ;; Try `mail-host-address'.
2847      ((and (boundp 'mail-host-address)
2848            (stringp mail-host-address)
2849            (string-match "\\." mail-host-address))
2850       mail-host-address)
2851      ;; We try `user-mail-address' as a backup.
2852      ((and user-mail
2853            (string-match "\\." user-mail)
2854            (string-match "@\\(.*\\)\\'" user-mail))
2855       (match-string 1 user-mail))
2856      ;; Default to this bogus thing.
2857      (t
2858       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2859
2860 (defun message-make-host-name ()
2861   "Return the name of the host."
2862   (let ((fqdn (message-make-fqdn)))
2863     (string-match "^[^.]+\\." fqdn)
2864     (substring fqdn 0 (1- (match-end 0)))))
2865
2866 (defun message-make-domain ()
2867   "Return the domain name."
2868   (or mail-host-address
2869       (message-make-fqdn)))
2870
2871 (defun message-generate-headers (headers)
2872   "Prepare article HEADERS.
2873 Headers already prepared in the buffer are not modified."
2874   (save-restriction
2875     (message-narrow-to-headers)
2876     (let* ((Date (message-make-date))
2877            (Message-ID (message-make-message-id))
2878            (Organization (message-make-organization))
2879            (From (message-make-from))
2880            (Path (message-make-path))
2881            (Subject nil)
2882            (Newsgroups nil)
2883            (In-Reply-To (message-make-in-reply-to))
2884            (To nil)
2885            (Distribution (message-make-distribution))
2886            (Lines (message-make-lines))
2887            (X-Newsreader message-newsreader)
2888            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2889                           message-mailer))
2890            (Expires (message-make-expires))
2891            (case-fold-search t)
2892            header value elem)
2893       ;; First we remove any old generated headers.
2894       (let ((headers message-deletable-headers))
2895         (unless (buffer-modified-p)
2896           (setq headers (delq 'Message-ID (copy-sequence headers))))
2897         (while headers
2898           (goto-char (point-min))
2899           (and (re-search-forward
2900                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2901                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2902                (message-delete-line))
2903           (pop headers)))
2904       ;; Go through all the required headers and see if they are in the
2905       ;; articles already.  If they are not, or are empty, they are
2906       ;; inserted automatically - except for Subject, Newsgroups and
2907       ;; Distribution.
2908       (while headers
2909         (goto-char (point-min))
2910         (setq elem (pop headers))
2911         (if (consp elem)
2912             (if (eq (car elem) 'optional)
2913                 (setq header (cdr elem))
2914               (setq header (car elem)))
2915           (setq header elem))
2916         (when (or (not (re-search-forward
2917                         (concat "^"
2918                                 (regexp-quote
2919                                  (downcase
2920                                   (if (stringp header)
2921                                       header
2922                                     (symbol-name header))))
2923                                 ":")
2924                         nil t))
2925                   (progn
2926                     ;; The header was found.  We insert a space after the
2927                     ;; colon, if there is none.
2928                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2929                     ;; Find out whether the header is empty...
2930                     (looking-at "[ \t]*$")))
2931           ;; So we find out what value we should insert.
2932           (setq value
2933                 (cond
2934                  ((and (consp elem) (eq (car elem) 'optional))
2935                   ;; This is an optional header.  If the cdr of this
2936                   ;; is something that is nil, then we do not insert
2937                   ;; this header.
2938                   (setq header (cdr elem))
2939                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2940                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2941                  ((consp elem)
2942                   ;; The element is a cons.  Either the cdr is a
2943                   ;; string to be inserted verbatim, or it is a
2944                   ;; function, and we insert the value returned from
2945                   ;; this function.
2946                   (or (and (stringp (cdr elem)) (cdr elem))
2947                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2948                  ((and (boundp header) (symbol-value header))
2949                   ;; The element is a symbol.  We insert the value
2950                   ;; of this symbol, if any.
2951                   (symbol-value header))
2952                  (t
2953                   ;; We couldn't generate a value for this header,
2954                   ;; so we just ask the user.
2955                   (read-from-minibuffer
2956                    (format "Empty header for %s; enter value: " header)))))
2957           ;; Finally insert the header.
2958           (when (and value
2959                      (not (equal value "")))
2960             (save-excursion
2961               (if (bolp)
2962                   (progn
2963                     ;; This header didn't exist, so we insert it.
2964                     (goto-char (point-max))
2965                     (insert (if (stringp header) header (symbol-name header))
2966                             ": " value "\n")
2967                     (forward-line -1))
2968                 ;; The value of this header was empty, so we clear
2969                 ;; totally and insert the new value.
2970                 (delete-region (point) (gnus-point-at-eol))
2971                 (insert value))
2972               ;; Add the deletable property to the headers that require it.
2973               (and (memq header message-deletable-headers)
2974                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2975                    (add-text-properties
2976                     (point) (match-end 0)
2977                     '(message-deletable t face italic) (current-buffer)))))))
2978       ;; Insert new Sender if the From is strange.
2979       (let ((from (message-fetch-field "from"))
2980             (sender (message-fetch-field "sender"))
2981             (secure-sender (message-make-sender)))
2982         (when (and from
2983                    (not (message-check-element 'sender))
2984                    (not (string=
2985                          (downcase
2986                           (cadr (mail-extract-address-components from)))
2987                          (downcase secure-sender)))
2988                    (or (null sender)
2989                        (not
2990                         (string=
2991                          (downcase
2992                           (cadr (mail-extract-address-components sender)))
2993                          (downcase secure-sender)))))
2994           (goto-char (point-min))
2995           ;; Rename any old Sender headers to Original-Sender.
2996           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2997             (beginning-of-line)
2998             (insert "Original-")
2999             (beginning-of-line))
3000           (when (or (message-news-p)
3001                     (string-match "@.+\\.." secure-sender))
3002             (insert "Sender: " secure-sender "\n")))))))
3003
3004 (defun message-insert-courtesy-copy ()
3005   "Insert a courtesy message in mail copies of combined messages."
3006   (let (newsgroups)
3007     (save-excursion
3008       (save-restriction
3009         (message-narrow-to-headers)
3010         (when (setq newsgroups (message-fetch-field "newsgroups"))
3011           (goto-char (point-max))
3012           (insert "Posted-To: " newsgroups "\n")))
3013       (forward-line 1)
3014       (when message-courtesy-message
3015         (cond
3016          ((string-match "%s" message-courtesy-message)
3017           (insert (format message-courtesy-message newsgroups)))
3018          (t
3019           (insert message-courtesy-message)))))))
3020
3021 ;;;
3022 ;;; Setting up a message buffer
3023 ;;;
3024
3025 (defun message-fill-address (header value)
3026   (save-restriction
3027     (narrow-to-region (point) (point))
3028     (insert (capitalize (symbol-name header))
3029             ": "
3030             (if (consp value) (car value) value)
3031             "\n")
3032     (narrow-to-region (point-min) (1- (point-max)))
3033     (let (quoted last)
3034       (goto-char (point-min))
3035       (while (not (eobp))
3036         (skip-chars-forward "^,\"" (point-max))
3037         (if (or (= (following-char) ?,)
3038                 (eobp))
3039             (when (not quoted)
3040               (if (and (> (current-column) 78)
3041                        last)
3042                   (progn
3043                     (save-excursion
3044                       (goto-char last)
3045                       (insert "\n\t"))
3046                     (setq last (1+ (point))))
3047                 (setq last (1+ (point)))))
3048           (setq quoted (not quoted)))
3049         (unless (eobp)
3050           (forward-char 1))))
3051     (goto-char (point-max))
3052     (widen)
3053     (forward-line 1)))
3054
3055 (defun message-fill-header (header value)
3056   (let ((begin (point))
3057         (fill-column 990)
3058         (fill-prefix "\t"))
3059     (insert (capitalize (symbol-name header))
3060             ": "
3061             (if (consp value) (car value) value)
3062             "\n")
3063     (save-restriction
3064       (narrow-to-region begin (point))
3065       (fill-region-as-paragraph begin (point))
3066       ;; Tapdance around looong Message-IDs.
3067       (forward-line -1)
3068       (when (looking-at "[ \t]*$")
3069         (message-delete-line))
3070       (goto-char begin)
3071       (re-search-forward ":" nil t)
3072       (when (looking-at "\n[ \t]+")
3073         (replace-match " " t t))
3074       (goto-char (point-max)))))
3075
3076 (defun message-shorten-references (header references)
3077   "Limit REFERENCES to be shorter than 988 characters."
3078   (let ((max 988)
3079         (cut 4)
3080         refs)
3081     (with-temp-buffer
3082       (insert references)
3083       (goto-char (point-min))
3084       (while (re-search-forward "<[^>]+>" nil t)
3085         (push (match-string 0) refs))
3086       (setq refs (nreverse refs))
3087       (while (> (length (mapconcat 'identity refs " ")) max)
3088         (when (< (length refs) (1+ cut))
3089           (decf cut))
3090         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3091     (insert (capitalize (symbol-name header)) ": "
3092             (mapconcat 'identity refs " ") "\n")))
3093
3094 (defun message-position-point ()
3095   "Move point to where the user probably wants to find it."
3096   (message-narrow-to-headers)
3097   (cond
3098    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3099     (search-backward ":" )
3100     (widen)
3101     (forward-char 1)
3102     (if (= (following-char) ? )
3103         (forward-char 1)
3104       (insert " ")))
3105    (t
3106     (goto-char (point-max))
3107     (widen)
3108     (forward-line 1)
3109     (unless (looking-at "$")
3110       (forward-line 2)))
3111    (sit-for 0)))
3112
3113 (defun message-buffer-name (type &optional to group)
3114   "Return a new (unique) buffer name based on TYPE and TO."
3115   (cond
3116    ;; Check whether `message-generate-new-buffers' is a function,
3117    ;; and if so, call it.
3118    ((message-functionp message-generate-new-buffers)
3119     (funcall message-generate-new-buffers type to group))
3120    ;; Generate a new buffer name The Message Way.
3121    (message-generate-new-buffers
3122     (generate-new-buffer-name
3123      (concat "*" type
3124              (if to
3125                  (concat " to "
3126                          (or (car (mail-extract-address-components to))
3127                              to) "")
3128                "")
3129              (if (and group (not (string= group ""))) (concat " on " group) "")
3130              "*")))
3131    ;; Use standard name.
3132    (t
3133     (format "*%s message*" type))))
3134
3135 (defun message-pop-to-buffer (name)
3136   "Pop to buffer NAME, and warn if it already exists and is modified."
3137   (let ((buffer (get-buffer name)))
3138     (if (and buffer
3139              (buffer-name buffer))
3140         (progn
3141           (set-buffer (pop-to-buffer buffer))
3142           (when (and (buffer-modified-p)
3143                      (not (y-or-n-p
3144                            "Message already being composed; erase? ")))
3145             (error "Message being composed")))
3146       (set-buffer (pop-to-buffer name)))
3147     (erase-buffer)
3148     (message-mode)))
3149
3150 (defun message-do-send-housekeeping ()
3151   "Kill old message buffers."
3152   ;; We might have sent this buffer already.  Delete it from the
3153   ;; list of buffers.
3154   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3155   (while (and message-max-buffers
3156               message-buffer-list
3157               (>= (length message-buffer-list) message-max-buffers))
3158     ;; Kill the oldest buffer -- unless it has been changed.
3159     (let ((buffer (pop message-buffer-list)))
3160       (when (and (buffer-name buffer)
3161                  (not (buffer-modified-p buffer)))
3162         (kill-buffer buffer))))
3163   ;; Rename the buffer.
3164   (if message-send-rename-function
3165       (funcall message-send-rename-function)
3166     (when (string-match "\\`\\*" (buffer-name))
3167       (rename-buffer
3168        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3169   ;; Push the current buffer onto the list.
3170   (when message-max-buffers
3171     (setq message-buffer-list
3172           (nconc message-buffer-list (list (current-buffer))))))
3173
3174 (defvar mc-modes-alist)
3175 (defun message-setup (headers &optional replybuffer actions)
3176   (when (and (boundp 'mc-modes-alist)
3177              (not (assq 'message-mode mc-modes-alist)))
3178     (push '(message-mode (encrypt . mc-encrypt-message)
3179                          (sign . mc-sign-message))
3180           mc-modes-alist))
3181   (when actions
3182     (setq message-send-actions actions))
3183   (setq message-reply-buffer replybuffer)
3184   (goto-char (point-min))
3185   ;; Insert all the headers.
3186   (mail-header-format
3187    (let ((h headers)
3188          (alist message-header-format-alist))
3189      (while h
3190        (unless (assq (caar h) message-header-format-alist)
3191          (push (list (caar h)) alist))
3192        (pop h))
3193      alist)
3194    headers)
3195   (delete-region (point) (progn (forward-line -1) (point)))
3196   (when message-default-headers
3197     (insert message-default-headers)
3198     (or (bolp) (insert ?\n)))
3199   (put-text-property
3200    (point)
3201    (progn
3202      (insert mail-header-separator "\n")
3203      (1- (point)))
3204    'read-only nil)
3205   (forward-line -1)
3206   (when (message-news-p)
3207     (when message-default-news-headers
3208       (insert message-default-news-headers)
3209       (or (bolp) (insert ?\n)))
3210     (when message-generate-headers-first
3211       (message-generate-headers
3212        (delq 'Lines
3213              (delq 'Subject
3214                    (copy-sequence message-required-news-headers))))))
3215   (when (message-mail-p)
3216     (when message-default-mail-headers
3217       (insert message-default-mail-headers)
3218       (or (bolp) (insert ?\n)))
3219     (when message-generate-headers-first
3220       (message-generate-headers
3221        (delq 'Lines
3222              (delq 'Subject
3223                    (copy-sequence message-required-mail-headers))))))
3224   (run-hooks 'message-signature-setup-hook)
3225   (message-insert-signature)
3226   (save-restriction
3227     (message-narrow-to-headers)
3228     (run-hooks 'message-header-setup-hook))
3229   (set-buffer-modified-p nil)
3230   (setq buffer-undo-list nil)
3231   (run-hooks 'message-setup-hook)
3232   (message-position-point)
3233   (undo-boundary))
3234
3235 (defun message-set-auto-save-file-name ()
3236   "Associate the message buffer with a file in the drafts directory."
3237   (when message-autosave-directory
3238     (if (gnus-alive-p)
3239         (setq message-draft-article
3240               (nndraft-request-associate-buffer "drafts"))
3241       (setq buffer-file-name (expand-file-name "*message*"
3242                                                message-autosave-directory))
3243       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3244     (clear-visited-file-modtime)))
3245
3246 (defun message-disassociate-draft ()
3247   "Disassociate the message buffer from the drafts directory."
3248   (when message-draft-article
3249     (nndraft-request-expire-articles
3250      (list message-draft-article) "drafts" nil t)))
3251
3252 \f
3253
3254 ;;;
3255 ;;; Commands for interfacing with message
3256 ;;;
3257
3258 ;;;###autoload
3259 (defun message-mail (&optional to subject
3260                                other-headers continue switch-function
3261                                yank-action send-actions)
3262   "Start editing a mail message to be sent.
3263 OTHER-HEADERS is an alist of header/value pairs."
3264   (interactive)
3265   (let ((message-this-is-mail t))
3266     (message-pop-to-buffer (message-buffer-name "mail" to))
3267     (message-setup
3268      (nconc
3269       `((To . ,(or to "")) (Subject . ,(or subject "")))
3270       (when other-headers other-headers)))))
3271
3272 ;;;###autoload
3273 (defun message-news (&optional newsgroups subject)
3274   "Start editing a news article to be sent."
3275   (interactive)
3276   (let ((message-this-is-news t))
3277     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3278     (message-setup `((Newsgroups . ,(or newsgroups ""))
3279                      (Subject . ,(or subject ""))))))
3280
3281 ;;;###autoload
3282 (defun message-reply (&optional to-address wide)
3283   "Start editing a reply to the article in the current buffer."
3284   (interactive)
3285   (let ((cur (current-buffer))
3286         from subject date reply-to to cc
3287         references message-id follow-to
3288         (inhibit-point-motion-hooks t)
3289         mct never-mct gnus-warning)
3290     (save-restriction
3291       (message-narrow-to-head)
3292       ;; Allow customizations to have their say.
3293       (if (not wide)
3294           ;; This is a regular reply.
3295           (if (message-functionp message-reply-to-function)
3296               (setq follow-to (funcall message-reply-to-function)))
3297         ;; This is a followup.
3298         (if (message-functionp message-wide-reply-to-function)
3299             (save-excursion
3300               (setq follow-to
3301                     (funcall message-wide-reply-to-function)))))
3302       ;; Find all relevant headers we need.
3303       (setq from (message-fetch-field "from")
3304             date (message-fetch-field "date")
3305             subject (or (message-fetch-field "subject") "none")
3306             to (message-fetch-field "to")
3307             cc (message-fetch-field "cc")
3308             mct (message-fetch-field "mail-copies-to")
3309             reply-to (message-fetch-field "reply-to")
3310             references (message-fetch-field "references")
3311             message-id (message-fetch-field "message-id" t))
3312       ;; Remove any (buggy) Re:'s that are present and make a
3313       ;; proper one.
3314       (when (string-match message-subject-re-regexp subject)
3315         (setq subject (substring subject (match-end 0))))
3316       (setq subject (concat "Re: " subject))
3317
3318       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3319                  (string-match "<[^>]+>" gnus-warning))
3320         (setq message-id (match-string 0 gnus-warning)))
3321
3322       ;; Handle special values of Mail-Copies-To.
3323       (when mct
3324         (cond ((equal (downcase mct) "never")
3325                (setq never-mct t)
3326                (setq mct nil))
3327               ((equal (downcase mct) "always")
3328                (setq mct (or reply-to from)))))
3329
3330       (unless follow-to
3331         (if (or (not wide)
3332                 to-address)
3333             (progn
3334               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3335               (when (and wide mct)
3336                 (push (cons 'Cc mct) follow-to)))
3337           (let (ccalist)
3338             (save-excursion
3339               (message-set-work-buffer)
3340               (unless never-mct
3341                 (insert (or reply-to from "")))
3342               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3343               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3344               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3345               (goto-char (point-min))
3346               (while (re-search-forward "[ \t]+" nil t)
3347                 (replace-match " " t t))
3348               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3349               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3350                         (erase-buffer)))
3351               (goto-char (point-min))
3352               ;; Perhaps Mail-Copies-To: never removed the only address?
3353               (when (eobp)
3354                 (insert (or reply-to from "")))
3355               (setq ccalist
3356                     (mapcar
3357                      (lambda (addr)
3358                        (cons (mail-strip-quoted-names addr) addr))
3359                      (message-tokenize-header (buffer-string))))
3360               (let ((s ccalist))
3361                 (while s
3362                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3363             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3364             (when ccalist
3365               (let ((ccs (cons 'Cc (mapconcat
3366                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3367                 (when (string-match "^ +" (cdr ccs))
3368                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3369                 (push ccs follow-to))))))
3370       (widen))
3371
3372     (message-pop-to-buffer (message-buffer-name
3373                             (if wide "wide reply" "reply") from
3374                             (if wide to-address nil)))
3375
3376     (setq message-reply-headers
3377           (vector 0 subject from date message-id references 0 0 ""))
3378
3379     (message-setup
3380      `((Subject . ,subject)
3381        ,@follow-to
3382        ,@(if (or references message-id)
3383              `((References . ,(concat (or references "") (and references " ")
3384                                       (or message-id ""))))
3385            nil))
3386      cur)))
3387
3388 ;;;###autoload
3389 (defun message-wide-reply (&optional to-address)
3390   "Make a \"wide\" reply to the message in the current buffer."
3391   (interactive)
3392   (message-reply to-address t))
3393
3394 ;;;###autoload
3395 (defun message-followup (&optional to-newsgroups)
3396   "Follow up to the message in the current buffer.
3397 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3398   (interactive)
3399   (let ((cur (current-buffer))
3400         from subject date reply-to mct
3401         references message-id follow-to
3402         (inhibit-point-motion-hooks t)
3403         (message-this-is-news t)
3404         followup-to distribution newsgroups gnus-warning posted-to)
3405     (save-restriction
3406       (narrow-to-region
3407        (goto-char (point-min))
3408        (if (search-forward "\n\n" nil t)
3409            (1- (point))
3410          (point-max)))
3411       (when (message-functionp message-followup-to-function)
3412         (setq follow-to
3413               (funcall message-followup-to-function)))
3414       (setq from (message-fetch-field "from")
3415             date (message-fetch-field "date")
3416             subject (or (message-fetch-field "subject") "none")
3417             references (message-fetch-field "references")
3418             message-id (message-fetch-field "message-id" t)
3419             followup-to (message-fetch-field "followup-to")
3420             newsgroups (message-fetch-field "newsgroups")
3421             posted-to (message-fetch-field "posted-to")
3422             reply-to (message-fetch-field "reply-to")
3423             distribution (message-fetch-field "distribution")
3424             mct (message-fetch-field "mail-copies-to"))
3425       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3426                  (string-match "<[^>]+>" gnus-warning))
3427         (setq message-id (match-string 0 gnus-warning)))
3428       ;; Remove bogus distribution.
3429       (when (and (stringp distribution)
3430                  (let ((case-fold-search t))
3431                    (string-match "world" distribution)))
3432         (setq distribution nil))
3433       ;; Remove any (buggy) Re:'s that are present and make a
3434       ;; proper one.
3435       (when (string-match message-subject-re-regexp subject)
3436         (setq subject (substring subject (match-end 0))))
3437       (setq subject (concat "Re: " subject))
3438       (widen))
3439
3440     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3441
3442     (message-setup
3443      `((Subject . ,subject)
3444        ,@(cond
3445           (to-newsgroups
3446            (list (cons 'Newsgroups to-newsgroups)))
3447           (follow-to follow-to)
3448           ((and followup-to message-use-followup-to)
3449            (list
3450             (cond
3451              ((equal (downcase followup-to) "poster")
3452               (if (or (eq message-use-followup-to 'use)
3453                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3454 You should normally obey the Followup-To: header.
3455
3456 `Followup-To: poster' sends your response via e-mail instead of news.
3457
3458 A typical situation where `Followup-To: poster' is used is when the poster
3459 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3460                   (progn
3461                     (setq message-this-is-news nil)
3462                     (cons 'To (or reply-to from "")))
3463                 (cons 'Newsgroups newsgroups)))
3464              (t
3465               (if (or (equal followup-to newsgroups)
3466                       (not (eq message-use-followup-to 'ask))
3467                       (message-y-or-n-p
3468                        (concat "Obey Followup-To: " followup-to "? ") t "\
3469 You should normally obey the Followup-To: header.
3470
3471         `Followup-To: " followup-to "'
3472 directs your response to " (if (string-match "," followup-to)
3473                                "the specified newsgroups"
3474                              "that newsgroup only") ".
3475
3476 If a message is posted to several newsgroups, Followup-To is often
3477 used to direct the following discussion to one newsgroup only,
3478 because discussions that are spread over several newsgroup tend to
3479 be fragmented and very difficult to follow.
3480
3481 Also, some source/announcement newsgroups are not indented for discussion;
3482 responses here are directed to other newsgroups."))
3483                   (cons 'Newsgroups followup-to)
3484                 (cons 'Newsgroups newsgroups))))))
3485           (posted-to
3486            `((Newsgroups . ,posted-to)))
3487           (t
3488            `((Newsgroups . ,newsgroups))))
3489        ,@(and distribution (list (cons 'Distribution distribution)))
3490        ,@(if (or references message-id)
3491              `((References . ,(concat (or references "") (and references " ")
3492                                       (or message-id "")))))
3493        ,@(when (and mct
3494                     (not (equal (downcase mct) "never")))
3495            (list (cons 'Cc (if (equal (downcase mct) "always")
3496                                (or reply-to from "")
3497                              mct)))))
3498
3499      cur)
3500
3501     (setq message-reply-headers
3502           (vector 0 subject from date message-id references 0 0 ""))))
3503
3504
3505 ;;;###autoload
3506 (defun message-cancel-news ()
3507   "Cancel an article you posted."
3508   (interactive)
3509   (unless (message-news-p)
3510     (error "This is not a news article; canceling is impossible"))
3511   (when (yes-or-no-p "Do you really want to cancel this article? ")
3512     (let (from newsgroups message-id distribution buf sender)
3513       (save-excursion
3514         ;; Get header info. from original article.
3515         (save-restriction
3516           (message-narrow-to-head)
3517           (setq from (message-fetch-field "from")
3518                 sender (message-fetch-field "sender")
3519                 newsgroups (message-fetch-field "newsgroups")
3520                 message-id (message-fetch-field "message-id" t)
3521                 distribution (message-fetch-field "distribution")))
3522         ;; Make sure that this article was written by the user.
3523         (unless (or (and sender
3524                          (string-equal
3525                           (downcase sender)
3526                           (downcase (message-make-sender))))
3527                     (string-equal
3528                      (downcase (cadr (mail-extract-address-components from)))
3529                      (downcase (cadr (mail-extract-address-components
3530                                       (message-make-from))))))
3531           (error "This article is not yours"))
3532         ;; Make control message.
3533         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3534         (buffer-disable-undo (current-buffer))
3535         (erase-buffer)
3536         (insert "Newsgroups: " newsgroups "\n"
3537                 "From: " (message-make-from) "\n"
3538                 "Subject: cmsg cancel " message-id "\n"
3539                 "Control: cancel " message-id "\n"
3540                 (if distribution
3541                     (concat "Distribution: " distribution "\n")
3542                   "")
3543                 mail-header-separator "\n"
3544                 message-cancel-message)
3545         (message "Canceling your article...")
3546         (if (let ((message-syntax-checks
3547                    'dont-check-for-anything-just-trust-me))
3548               (funcall message-send-news-function))
3549             (message "Canceling your article...done"))
3550         (kill-buffer buf)))))
3551
3552 ;;;###autoload
3553 (defun message-supersede ()
3554   "Start composing a message to supersede the current message.
3555 This is done simply by taking the old article and adding a Supersedes
3556 header line with the old Message-ID."
3557   (interactive)
3558   (let ((cur (current-buffer))
3559         (sender (message-fetch-field "sender"))
3560         (from (message-fetch-field "from")))
3561     ;; Check whether the user owns the article that is to be superseded.
3562     (unless (or (and sender
3563                      (string-equal
3564                       (downcase sender)
3565                       (downcase (message-make-sender))))
3566                 (string-equal
3567                  (downcase (cadr (mail-extract-address-components from)))
3568                  (downcase (cadr (mail-extract-address-components
3569                                   (message-make-from))))))
3570       (error "This article is not yours"))
3571     ;; Get a normal message buffer.
3572     (message-pop-to-buffer (message-buffer-name "supersede"))
3573     (insert-buffer-substring cur)
3574     (message-narrow-to-head)
3575     ;; Remove unwanted headers.
3576     (when message-ignored-supersedes-headers
3577       (message-remove-header message-ignored-supersedes-headers t))
3578     (goto-char (point-min))
3579     (if (not (re-search-forward "^Message-ID: " nil t))
3580         (error "No Message-ID in this article")
3581       (replace-match "Supersedes: " t t))
3582     (goto-char (point-max))
3583     (insert mail-header-separator)
3584     (widen)
3585     (forward-line 1)))
3586
3587 ;;;###autoload
3588 (defun message-recover ()
3589   "Reread contents of current buffer from its last auto-save file."
3590   (interactive)
3591   (let ((file-name (make-auto-save-file-name)))
3592     (cond ((save-window-excursion
3593              (if (not (eq system-type 'vax-vms))
3594                  (with-output-to-temp-buffer "*Directory*"
3595                    (buffer-disable-undo standard-output)
3596                    (let ((default-directory "/"))
3597                      (call-process
3598                       "ls" nil standard-output nil "-l" file-name))))
3599              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3600            (let ((buffer-read-only nil))
3601              (erase-buffer)
3602              (insert-file-contents file-name nil)))
3603           (t (error "message-recover cancelled")))))
3604
3605 ;;; Washing Subject:
3606
3607 (defun message-wash-subject (subject)
3608   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3609   (with-temp-buffer
3610     (insert-string subject)
3611     (goto-char (point-min))
3612     ;; strip Re/Fwd stuff off the beginning
3613     (while (re-search-forward
3614             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3615       (replace-match ""))
3616
3617     ;; and gnus-style forwards [foo@bar.com] subject
3618     (goto-char (point-min))
3619     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3620       (replace-match ""))
3621
3622     ;; and off the end
3623     (goto-char (point-max))
3624     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3625       (replace-match ""))
3626
3627     ;; and finally, any whitespace that was left-over
3628     (goto-char (point-min))
3629     (while (re-search-forward "^[ \t]+" nil t)
3630       (replace-match ""))
3631     (goto-char (point-max))
3632     (while (re-search-backward "[ \t]+$" nil t)
3633       (replace-match ""))
3634
3635     (buffer-string)))
3636     
3637 ;;; Forwarding messages.
3638
3639 (defun message-forward-subject-author-subject (subject)
3640   "Generate a subject for a forwarded message.
3641 The form is: [Source] Subject, where if the original message was mail,
3642 Source is the sender, and if the original message was news, Source is
3643 the list of newsgroups is was posted to."
3644   (concat "["
3645           (or (message-fetch-field
3646                (if (message-news-p) "newsgroups" "from"))
3647               "(nowhere)")
3648           "] " subject))
3649
3650 (defun message-forward-subject-fwd (subject)
3651   "Generate a subject for a forwarded message.
3652 The form is: Fwd: Subject, where Subject is the original subject of
3653 the message."
3654   (concat "Fwd: " subject))
3655
3656 (defun message-make-forward-subject ()
3657   "Return a Subject header suitable for the message in the current buffer."
3658   (save-excursion
3659     (save-restriction
3660       (current-buffer)
3661       (message-narrow-to-head)
3662       (let ((funcs message-make-forward-subject-function)
3663             (subject (if message-wash-forwarded-subjects
3664                          (message-wash-subject
3665                           (or (message-fetch-field "Subject") ""))
3666                        (or (message-fetch-field "Subject") ""))))
3667         ;; Make sure funcs is a list.
3668         (and funcs
3669              (not (listp funcs))
3670              (setq funcs (list funcs)))
3671         ;; Apply funcs in order, passing subject generated by previous
3672         ;; func to the next one.
3673         (while funcs
3674           (when (message-functionp (car funcs))
3675             (setq subject (funcall (car funcs) subject)))
3676           (setq funcs (cdr funcs)))
3677         subject))))
3678
3679 ;;;###autoload
3680 (defun message-forward (&optional news)
3681   "Forward the current message via mail.
3682 Optional NEWS will use news to forward instead of mail."
3683   (interactive "P")
3684   (let ((cur (current-buffer))
3685         (subject (message-make-forward-subject))
3686         art-beg)
3687     (if news (message-news nil subject) (message-mail nil subject))
3688     ;; Put point where we want it before inserting the forwarded
3689     ;; message.
3690     (if message-signature-before-forwarded-message
3691         (goto-char (point-max))
3692       (message-goto-body))
3693     ;; Make sure we're at the start of the line.
3694     (unless (eolp)
3695       (insert "\n"))
3696     ;; Narrow to the area we are to insert.
3697     (narrow-to-region (point) (point))
3698     ;; Insert the separators and the forwarded buffer.
3699     (insert message-forward-start-separator)
3700     (setq art-beg (point))
3701     (insert-buffer-substring cur)
3702     (goto-char (point-max))
3703     (insert message-forward-end-separator)
3704     (set-text-properties (point-min) (point-max) nil)
3705     ;; Remove all unwanted headers.
3706     (goto-char art-beg)
3707     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3708                                   (1- (point))
3709                                 (point)))
3710     (goto-char (point-min))
3711     (message-remove-header message-included-forward-headers t nil t)
3712     (widen)
3713     (message-position-point)))
3714
3715 ;;;###autoload
3716 (defun message-resend (address)
3717   "Resend the current article to ADDRESS."
3718   (interactive "sResend message to: ")
3719   (message "Resending message to %s..." address)
3720   (save-excursion
3721     (let ((cur (current-buffer))
3722           beg)
3723       ;; We first set up a normal mail buffer.
3724       (set-buffer (get-buffer-create " *message resend*"))
3725       (buffer-disable-undo (current-buffer))
3726       (erase-buffer)
3727       (message-setup `((To . ,address)))
3728       ;; Insert our usual headers.
3729       (message-generate-headers '(From Date To))
3730       (message-narrow-to-headers)
3731       ;; Rename them all to "Resent-*".
3732       (while (re-search-forward "^[A-Za-z]" nil t)
3733         (forward-char -1)
3734         (insert "Resent-"))
3735       (widen)
3736       (forward-line)
3737       (delete-region (point) (point-max))
3738       (setq beg (point))
3739       ;; Insert the message to be resent.
3740       (insert-buffer-substring cur)
3741       (goto-char (point-min))
3742       (search-forward "\n\n")
3743       (forward-char -1)
3744       (save-restriction
3745         (narrow-to-region beg (point))
3746         (message-remove-header message-ignored-resent-headers t)
3747         (goto-char (point-max)))
3748       (insert mail-header-separator)
3749       ;; Rename all old ("Also-")Resent headers.
3750       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3751         (beginning-of-line)
3752         (insert "Also-"))
3753       ;; Quote any "From " lines at the beginning.
3754       (goto-char beg)
3755       (when (looking-at "From ")
3756         (replace-match "X-From-Line: "))
3757       ;; Send it.
3758       (message-send-mail)
3759       (kill-buffer (current-buffer)))
3760     (message "Resending message to %s...done" address)))
3761
3762 ;;;###autoload
3763 (defun message-bounce ()
3764   "Re-mail the current message.
3765 This only makes sense if the current message is a bounce message than
3766 contains some mail you have written which has been bounced back to
3767 you."
3768   (interactive)
3769   (let ((cur (current-buffer))
3770         boundary)
3771     (message-pop-to-buffer (message-buffer-name "bounce"))
3772     (insert-buffer-substring cur)
3773     (undo-boundary)
3774     (message-narrow-to-head)
3775     (if (and (message-fetch-field "Mime-Version")
3776              (setq boundary (message-fetch-field "Content-Type")))
3777         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3778             (setq boundary (concat (match-string 1 boundary) " *\n"
3779                                    "Content-Type: message/rfc822"))
3780           (setq boundary nil)))
3781     (widen)
3782     (goto-char (point-min))
3783     (search-forward "\n\n" nil t)
3784     (or (and boundary
3785              (re-search-forward boundary nil t)
3786              (forward-line 2))
3787         (and (re-search-forward message-unsent-separator nil t)
3788              (forward-line 1))
3789         (re-search-forward "^Return-Path:.*\n" nil t))
3790     ;; We remove everything before the bounced mail.
3791     (delete-region
3792      (point-min)
3793      (if (re-search-forward "^[^ \n\t]+:" nil t)
3794          (match-beginning 0)
3795        (point)))
3796     (save-restriction
3797       (message-narrow-to-head)
3798       (message-remove-header message-ignored-bounced-headers t)
3799       (goto-char (point-max))
3800       (insert mail-header-separator))
3801     (message-position-point)))
3802
3803 ;;;
3804 ;;; Interactive entry points for new message buffers.
3805 ;;;
3806
3807 ;;;###autoload
3808 (defun message-mail-other-window (&optional to subject)
3809   "Like `message-mail' command, but display mail buffer in another window."
3810   (interactive)
3811   (let ((pop-up-windows t)
3812         (special-display-buffer-names nil)
3813         (special-display-regexps nil)
3814         (same-window-buffer-names nil)
3815         (same-window-regexps nil))
3816     (message-pop-to-buffer (message-buffer-name "mail" to)))
3817   (let ((message-this-is-mail t))
3818     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3819
3820 ;;;###autoload
3821 (defun message-mail-other-frame (&optional to subject)
3822   "Like `message-mail' command, but display mail buffer in another frame."
3823   (interactive)
3824   (let ((pop-up-frames t)
3825         (special-display-buffer-names nil)
3826         (special-display-regexps nil)
3827         (same-window-buffer-names nil)
3828         (same-window-regexps nil))
3829     (message-pop-to-buffer (message-buffer-name "mail" to)))
3830   (let ((message-this-is-mail t))
3831     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3832
3833 ;;;###autoload
3834 (defun message-news-other-window (&optional newsgroups subject)
3835   "Start editing a news article to be sent."
3836   (interactive)
3837   (let ((pop-up-windows t)
3838         (special-display-buffer-names nil)
3839         (special-display-regexps nil)
3840         (same-window-buffer-names nil)
3841         (same-window-regexps nil))
3842     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3843   (let ((message-this-is-news t))
3844     (message-setup `((Newsgroups . ,(or newsgroups ""))
3845                      (Subject . ,(or subject ""))))))
3846
3847 ;;;###autoload
3848 (defun message-news-other-frame (&optional newsgroups subject)
3849   "Start editing a news article to be sent."
3850   (interactive)
3851   (let ((pop-up-frames t)
3852         (special-display-buffer-names nil)
3853         (special-display-regexps nil)
3854         (same-window-buffer-names nil)
3855         (same-window-regexps nil))
3856     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3857   (let ((message-this-is-news t))
3858     (message-setup `((Newsgroups . ,(or newsgroups ""))
3859                      (Subject . ,(or subject ""))))))
3860
3861 ;;; underline.el
3862
3863 ;; This code should be moved to underline.el (from which it is stolen).
3864
3865 ;;;###autoload
3866 (defun bold-region (start end)
3867   "Bold all nonblank characters in the region.
3868 Works by overstriking characters.
3869 Called from program, takes two arguments START and END
3870 which specify the range to operate on."
3871   (interactive "r")
3872   (save-excursion
3873     (let ((end1 (make-marker)))
3874       (move-marker end1 (max start end))
3875       (goto-char (min start end))
3876       (while (< (point) end1)
3877         (or (looking-at "[_\^@- ]")
3878             (insert (following-char) "\b"))
3879         (forward-char 1)))))
3880
3881 ;;;###autoload
3882 (defun unbold-region (start end)
3883   "Remove all boldness (overstruck characters) in the region.
3884 Called from program, takes two arguments START and END
3885 which specify the range to operate on."
3886   (interactive "r")
3887   (save-excursion
3888     (let ((end1 (make-marker)))
3889       (move-marker end1 (max start end))
3890       (goto-char (min start end))
3891       (while (re-search-forward "\b" end1 t)
3892         (if (eq (following-char) (char-after (- (point) 2)))
3893             (delete-char -2))))))
3894
3895 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3896
3897 ;; Support for toolbar
3898 (when (string-match "XEmacs\\|Lucid" emacs-version)
3899   (require 'messagexmas))
3900
3901 ;;; Group name completion.
3902
3903 (defvar message-newgroups-header-regexp
3904   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3905   "Regexp that match headers that lists groups.")
3906
3907 (defun message-tab ()
3908   "Expand group names in Newsgroups and Followup-To headers.
3909 Do a `tab-to-tab-stop' if not in those headers."
3910   (interactive)
3911   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3912         (mail-abbrev-in-expansion-header-p))
3913       (message-expand-group)
3914     (tab-to-tab-stop)))
3915
3916 (defvar gnus-active-hashtb)
3917 (defun message-expand-group ()
3918   "Expand the group name under point."
3919   (let* ((b (save-excursion
3920               (save-restriction
3921                 (narrow-to-region
3922                  (save-excursion
3923                    (beginning-of-line)
3924                    (skip-chars-forward "^:")
3925                    (1+ (point)))
3926                  (point))
3927                 (skip-chars-backward "^, \t\n") (point))))
3928          (completion-ignore-case t)
3929          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
3930                                             (point))))
3931          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3932          (completions (all-completions string hashtb))
3933          comp)
3934     (delete-region b (point))
3935     (cond
3936      ((= (length completions) 1)
3937       (if (string= (car completions) string)
3938           (progn
3939             (insert string)
3940             (message "Only matching group"))
3941         (insert (car completions))))
3942      ((and (setq comp (try-completion string hashtb))
3943            (not (string= comp string)))
3944       (insert comp))
3945      (t
3946       (insert string)
3947       (if (not comp)
3948           (message "No matching groups")
3949         (save-selected-window
3950           (pop-to-buffer "*Completions*")
3951           (buffer-disable-undo (current-buffer))
3952           (let ((buffer-read-only nil))
3953             (erase-buffer)
3954             (let ((standard-output (current-buffer)))
3955               (display-completion-list (sort completions 'string<)))
3956             (goto-char (point-min))
3957             (delete-region (point) (progn (forward-line 3) (point))))))))))
3958
3959 ;;; Help stuff.
3960
3961 (defun message-talkative-question (ask question show &rest text)
3962   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3963 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3964 The following arguments may contain lists of values."
3965   (if (and show
3966            (setq text (message-flatten-list text)))
3967       (save-window-excursion
3968         (save-excursion
3969           (with-output-to-temp-buffer " *MESSAGE information message*"
3970             (set-buffer " *MESSAGE information message*")
3971             (mapcar 'princ text)
3972             (goto-char (point-min))))
3973         (funcall ask question))
3974     (funcall ask question)))
3975
3976 (defun message-flatten-list (list)
3977   "Return a new, flat list that contains all elements of LIST.
3978
3979 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3980 => (1 2 3 4 5 6 7)"
3981   (cond ((consp list)
3982          (apply 'append (mapcar 'message-flatten-list list)))
3983         (list
3984          (list list))))
3985
3986 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3987   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3988 Then clone the local variables and values from the old buffer to the
3989 new one, cloning only the locals having a substring matching the
3990 regexp varstr."
3991   (let ((oldbuf (current-buffer)))
3992     (save-excursion
3993       (set-buffer (generate-new-buffer name))
3994       (message-clone-locals oldbuf)
3995       (current-buffer))))
3996
3997 (defun message-clone-locals (buffer)
3998   "Clone the local variables from BUFFER to the current buffer."
3999   (let ((locals (save-excursion
4000                   (set-buffer buffer)
4001                   (buffer-local-variables)))
4002         (regexp "^gnus\\|^nn\\|^message"))
4003     (mapcar
4004      (lambda (local)
4005        (when (and (consp local)
4006                   (car local)
4007                   (string-match regexp (symbol-name (car local))))
4008          (ignore-errors
4009            (set (make-local-variable (car local))
4010                 (cdr local)))))
4011      locals)))
4012
4013 ;;; Miscellaneous functions
4014
4015 ;; stolen (and renamed) from nnheader.el
4016 (defun message-replace-chars-in-string (string from to)
4017   "Replace characters in STRING from FROM to TO."
4018   (let ((string (substring string 0))   ;Copy string.
4019         (len (length string))
4020         (idx 0))
4021     ;; Replace all occurrences of FROM with TO.
4022     (while (< idx len)
4023       (when (= (aref string idx) from)
4024         (aset string idx to))
4025       (setq idx (1+ idx)))
4026     string))
4027
4028 ;;;
4029 ;;; MIME functions
4030 ;;;
4031
4032 (defun message-encode-message-body ()
4033   "Examine the message body, encode it, and add the requisite headers."
4034   (when (featurep 'mule)
4035     (save-excursion
4036       (save-restriction
4037         (message-narrow-to-headers)
4038         (message-remove-header
4039          "^Content-Transfer-Encoding:\\|^Content-Type:\\|^Mime-Version:" t)
4040         (goto-char (point-max))
4041         (widen)
4042         (narrow-to-region (point) (point-max))
4043         (let* ((charset (mm-encode-body))
4044                (encoding (mm-body-encoding)))
4045           (when (consp charset)
4046             (error "Can't encode messages with multiple charsets (yet)"))
4047           (widen)
4048           (message-narrow-to-headers)
4049           (goto-char (point-max))
4050           (mm-insert-rfc822-headers
4051            (or charset (mm-mule-charset-to-mime-charset 'ascii))
4052            encoding))))))
4053
4054 (run-hooks 'message-load-hook)
4055
4056 (provide 'message)
4057
4058 ;;; message.el ends here