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