c92e62b9041b71e67206f0ce285cb5a19aa2a499
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33
34 (require 'mailheader)
35 (require 'nnheader)
36 (require 'easymenu)
37 (require 'custom)
38 (if (string-match "XEmacs\\|Lucid" emacs-version)
39     (require 'mail-abbrevs)
40   (require 'mailabbrev))
41 (require 'rfc2047)
42 (require 'mm-bodies)
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 'mail-abbrev-in-expansion-header-p "mailabbrev")
954   (autoload 'nndraft-request-associate-buffer "nndraft")
955   (autoload 'nndraft-request-expire-articles "nndraft")
956   (autoload 'gnus-open-server "gnus-int")
957   (autoload 'gnus-request-post "gnus-int")
958   (autoload 'gnus-alive-p "gnus-util")
959   (autoload 'rmail-output "rmail"))
960
961 \f
962
963 ;;;
964 ;;; Utility functions.
965 ;;;
966
967 (defmacro message-y-or-n-p (question show &rest text)
968   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
969   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
970
971 ;; Delete the current line (and the next N lines.);
972 (defmacro message-delete-line (&optional n)
973   `(delete-region (progn (beginning-of-line) (point))
974                   (progn (forward-line ,(or n 1)) (point))))
975
976 (defun message-tokenize-header (header &optional separator)
977   "Split HEADER into a list of header elements.
978 \",\" is used as the separator."
979   (if (not header)
980       nil
981     (let ((regexp (format "[%s]+" (or separator ",")))
982           (beg 1)
983           (first t)
984           quoted elems paren)
985       (save-excursion
986         (message-set-work-buffer)
987         (insert header)
988         (goto-char (point-min))
989         (while (not (eobp))
990           (if first
991               (setq first nil)
992             (forward-char 1))
993           (cond ((and (> (point) beg)
994                       (or (eobp)
995                           (and (looking-at regexp)
996                                (not quoted)
997                                (not paren))))
998                  (push (buffer-substring beg (point)) elems)
999                  (setq beg (match-end 0)))
1000                 ((= (following-char) ?\")
1001                  (setq quoted (not quoted)))
1002                 ((and (= (following-char) ?\()
1003                       (not quoted))
1004                  (setq paren t))
1005                 ((and (= (following-char) ?\))
1006                       (not quoted))
1007                  (setq paren nil))))
1008         (nreverse elems)))))
1009
1010 (defun message-mail-file-mbox-p (file)
1011   "Say whether FILE looks like a Unix mbox file."
1012   (when (and (file-exists-p file)
1013              (file-readable-p file)
1014              (file-regular-p file))
1015     (with-temp-buffer
1016       (nnheader-insert-file-contents file)
1017       (goto-char (point-min))
1018       (looking-at message-unix-mail-delimiter))))
1019
1020 (defun message-fetch-field (header &optional not-all)
1021   "The same as `mail-fetch-field', only remove all newlines."
1022   (let* ((inhibit-point-motion-hooks t)
1023          (value (mail-fetch-field header nil (not not-all))))
1024     (when value
1025       (nnheader-replace-chars-in-string value ?\n ? ))))
1026
1027 (defun message-narrow-to-field ()
1028   "Narrow the buffer to the header on the current line."
1029   (beginning-of-line)
1030   (narrow-to-region
1031    (point)
1032    (progn
1033      (forward-line 1)
1034      (if (re-search-forward "^[^ \n\t]" nil t)
1035          (progn
1036            (beginning-of-line)
1037            (point))
1038        (point-max))))
1039   (goto-char (point-min)))
1040
1041 (defun message-add-header (&rest headers)
1042   "Add the HEADERS to the message header, skipping those already present."
1043   (while headers
1044     (let (hclean)
1045       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1046         (error "Invalid header `%s'" (car headers)))
1047       (setq hclean (match-string 1 (car headers)))
1048     (save-restriction
1049       (message-narrow-to-headers)
1050       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1051         (insert (car headers) ?\n))))
1052     (setq headers (cdr headers))))
1053
1054 (defun message-fetch-reply-field (header)
1055   "Fetch FIELD from the message we're replying to."
1056   (when (and message-reply-buffer
1057              (buffer-name message-reply-buffer))
1058     (save-excursion
1059       (set-buffer message-reply-buffer)
1060       (message-fetch-field header))))
1061
1062 (defun message-set-work-buffer ()
1063   (if (get-buffer " *message work*")
1064       (progn
1065         (set-buffer " *message work*")
1066         (erase-buffer))
1067     (set-buffer (get-buffer-create " *message work*"))
1068     (kill-all-local-variables)
1069     (mm-enable-multibyte)))
1070
1071 (defun message-functionp (form)
1072   "Return non-nil if FORM is funcallable."
1073   (or (and (symbolp form) (fboundp form))
1074       (and (listp form) (eq (car form) 'lambda))
1075       (byte-code-function-p form)))
1076
1077 (defun message-strip-subject-re (subject)
1078   "Remove \"Re:\" from subject lines."
1079   (if (string-match message-subject-re-regexp subject)
1080       (substring subject (match-end 0))
1081     subject))
1082
1083 (defun message-remove-header (header &optional is-regexp first reverse)
1084   "Remove HEADER in the narrowed buffer.
1085 If REGEXP, HEADER is a regular expression.
1086 If FIRST, only remove the first instance of the header.
1087 Return the number of headers removed."
1088   (goto-char (point-min))
1089   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1090         (number 0)
1091         (case-fold-search t)
1092         last)
1093     (while (and (not (eobp))
1094                 (not last))
1095       (if (if reverse
1096               (not (looking-at regexp))
1097             (looking-at regexp))
1098           (progn
1099             (incf number)
1100             (when first
1101               (setq last t))
1102             (delete-region
1103              (point)
1104              ;; There might be a continuation header, so we have to search
1105              ;; until we find a new non-continuation line.
1106              (progn
1107                (forward-line 1)
1108                (if (re-search-forward "^[^ \t]" nil t)
1109                    (goto-char (match-beginning 0))
1110                  (point-max)))))
1111         (forward-line 1)
1112         (if (re-search-forward "^[^ \t]" nil t)
1113             (goto-char (match-beginning 0))
1114           (point-max))))
1115     number))
1116
1117 (defun message-narrow-to-headers ()
1118   "Narrow the buffer to the head of the message."
1119   (widen)
1120   (narrow-to-region
1121    (goto-char (point-min))
1122    (if (re-search-forward
1123         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1124        (match-beginning 0)
1125      (point-max)))
1126   (goto-char (point-min)))
1127
1128 (defun message-narrow-to-head ()
1129   "Narrow the buffer to the head of the message.
1130 Point is left at the beginning of the narrowed-to region."
1131   (widen)
1132   (narrow-to-region
1133    (goto-char (point-min))
1134    (if (search-forward "\n\n" nil 1)
1135        (1- (point))
1136      (point-max)))
1137   (goto-char (point-min)))
1138
1139 (defun message-news-p ()
1140   "Say whether the current buffer contains a news message."
1141   (and (not message-this-is-mail)
1142        (or message-this-is-news
1143            (save-excursion
1144              (save-restriction
1145                (message-narrow-to-headers)
1146                (and (message-fetch-field "newsgroups")
1147                     (not (message-fetch-field "posted-to"))))))))
1148
1149 (defun message-mail-p ()
1150   "Say whether the current buffer contains a mail message."
1151   (and (not message-this-is-news)
1152        (or message-this-is-mail
1153            (save-excursion
1154              (save-restriction
1155                (message-narrow-to-headers)
1156                (or (message-fetch-field "to")
1157                    (message-fetch-field "cc")
1158                    (message-fetch-field "bcc")))))))
1159
1160 (defun message-next-header ()
1161   "Go to the beginning of the next header."
1162   (beginning-of-line)
1163   (or (eobp) (forward-char 1))
1164   (not (if (re-search-forward "^[^ \t]" nil t)
1165            (beginning-of-line)
1166          (goto-char (point-max)))))
1167
1168 (defun message-sort-headers-1 ()
1169   "Sort the buffer as headers using `message-rank' text props."
1170   (goto-char (point-min))
1171   (sort-subr
1172    nil 'message-next-header
1173    (lambda ()
1174      (message-next-header)
1175      (unless (bobp)
1176        (forward-char -1)))
1177    (lambda ()
1178      (or (get-text-property (point) 'message-rank)
1179          10000))))
1180
1181 (defun message-sort-headers ()
1182   "Sort the headers of the current message according to `message-header-format-alist'."
1183   (interactive)
1184   (save-excursion
1185     (save-restriction
1186       (let ((max (1+ (length message-header-format-alist)))
1187             rank)
1188         (message-narrow-to-headers)
1189         (while (re-search-forward "^[^ \n]+:" nil t)
1190           (put-text-property
1191            (match-beginning 0) (1+ (match-beginning 0))
1192            'message-rank
1193            (if (setq rank (length (memq (assq (intern (buffer-substring
1194                                                        (match-beginning 0)
1195                                                        (1- (match-end 0))))
1196                                               message-header-format-alist)
1197                                         message-header-format-alist)))
1198                (- max rank)
1199              (1+ max)))))
1200       (message-sort-headers-1))))
1201
1202 \f
1203
1204 ;;;
1205 ;;; Message mode
1206 ;;;
1207
1208 ;;; Set up keymap.
1209
1210 (defvar message-mode-map nil)
1211
1212 (unless message-mode-map
1213   (setq message-mode-map (copy-keymap text-mode-map))
1214   (define-key message-mode-map "\C-c?" 'describe-mode)
1215
1216   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1217   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1218   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1219   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1220   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1221   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1222   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1223   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1224   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1225   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1226   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1227   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1228   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1229
1230   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1231   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1232
1233   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1234   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1235   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1236   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1237   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1238   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1239
1240   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1241   (define-key message-mode-map "\C-c\C-s" 'message-send)
1242   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1243   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1244
1245   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1246   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1247   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1248   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1249
1250   (define-key message-mode-map "\t" 'message-tab))
1251
1252 (easy-menu-define
1253  message-mode-menu message-mode-map "Message Menu."
1254  '("Message"
1255    ["Sort Headers" message-sort-headers t]
1256    ["Yank Original" message-yank-original t]
1257    ["Fill Yanked Message" message-fill-yanked-message t]
1258    ["Insert Signature" message-insert-signature t]
1259    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1260    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1261    ["Elide Region" message-elide-region (mark t)]
1262    ["Delete Outside Region" message-delete-not-region (mark t)]
1263    ["Kill To Signature" message-kill-to-signature t]
1264    ["Newline and Reformat" message-newline-and-reformat t]
1265    ["Rename buffer" message-rename-buffer t]
1266    ["Spellcheck" ispell-message t]
1267    "----"
1268    ["Send Message" message-send-and-exit t]
1269    ["Abort Message" message-dont-send t]
1270    ["Kill Message" message-kill-buffer t]))
1271
1272 (easy-menu-define
1273  message-mode-field-menu message-mode-map ""
1274  '("Field"
1275    ["Fetch To" message-insert-to t]
1276    ["Fetch Newsgroups" message-insert-newsgroups t]
1277    "----"
1278    ["To" message-goto-to t]
1279    ["Subject" message-goto-subject t]
1280    ["Cc" message-goto-cc t]
1281    ["Reply-To" message-goto-reply-to t]
1282    ["Summary" message-goto-summary t]
1283    ["Keywords" message-goto-keywords t]
1284    ["Newsgroups" message-goto-newsgroups t]
1285    ["Followup-To" message-goto-followup-to t]
1286    ["Distribution" message-goto-distribution t]
1287    ["Body" message-goto-body t]
1288    ["Signature" message-goto-signature t]))
1289
1290 (defvar facemenu-add-face-function)
1291 (defvar facemenu-remove-face-function)
1292
1293 ;;;###autoload
1294 (defun message-mode ()
1295   "Major mode for editing mail and news to be sent.
1296 Like Text Mode but with these additional commands:
1297 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1298 C-c C-f  move to a header field (and create it if there isn't):
1299          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1300          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1301          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1302          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1303          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1304          C-c C-f C-f  move to Followup-To
1305 C-c C-t  message-insert-to (add a To header to a news followup)
1306 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1307 C-c C-b  message-goto-body (move to beginning of message text).
1308 C-c C-i  message-goto-signature (move to the beginning of the signature).
1309 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1310 C-c C-y  message-yank-original (insert current message, if any).
1311 C-c C-q  message-fill-yanked-message (fill what was yanked).
1312 C-c C-e  message-elide-region (elide the text between point and mark).
1313 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1314 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1315   (interactive)
1316   (kill-all-local-variables)
1317   (make-local-variable 'message-reply-buffer)
1318   (setq message-reply-buffer nil)
1319   (make-local-variable 'message-send-actions) 
1320   (make-local-variable 'message-exit-actions) 
1321   (make-local-variable 'message-kill-actions)
1322   (make-local-variable 'message-postpone-actions)
1323   (make-local-variable 'message-draft-article)
1324   (make-local-hook 'kill-buffer-hook)
1325   (set-syntax-table message-mode-syntax-table)
1326   (use-local-map message-mode-map)
1327   (setq local-abbrev-table message-mode-abbrev-table)
1328   (setq major-mode 'message-mode)
1329   (setq mode-name "Message")
1330   (setq buffer-offer-save t)
1331   (make-local-variable 'facemenu-add-face-function)
1332   (make-local-variable 'facemenu-remove-face-function)
1333   (setq facemenu-add-face-function
1334         (lambda (face end)
1335           (let ((face-fun (cdr (assq face message-face-alist))))
1336             (if face-fun
1337                 (funcall face-fun (point) end)
1338               (error "Face %s not configured for %s mode" face mode-name)))
1339           "")
1340         facemenu-remove-face-function t)
1341   (make-local-variable 'paragraph-separate)
1342   (make-local-variable 'paragraph-start)
1343   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1344   ;; lines that delimit forwarded messages.
1345   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1346   ;; are also sometimes used and should be separators.
1347   (setq paragraph-start
1348         (concat (regexp-quote mail-header-separator)
1349                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1350                 "-- $\\|---+$\\|"
1351                 page-delimiter
1352                 ;;!!! Uhm... shurely this can't be right?
1353                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1354   (setq paragraph-separate paragraph-start)
1355   (make-local-variable 'message-reply-headers)
1356   (setq message-reply-headers nil)
1357   (make-local-variable 'message-newsreader)
1358   (make-local-variable 'message-mailer)
1359   (make-local-variable 'message-post-method)
1360   (make-local-variable 'message-sent-message-via)
1361   (setq message-sent-message-via nil)
1362   (make-local-variable 'message-checksum)
1363   (setq message-checksum nil)
1364   ;;(when (fboundp 'mail-hist-define-keys)
1365   ;;  (mail-hist-define-keys))
1366   (when (string-match "XEmacs\\|Lucid" emacs-version)
1367     (message-setup-toolbar))
1368   (easy-menu-add message-mode-menu message-mode-map)
1369   (easy-menu-add message-mode-field-menu message-mode-map)
1370   ;; Allow mail alias things.
1371   (when (eq message-mail-alias-type 'abbrev)
1372     (if (fboundp 'mail-abbrevs-setup)
1373         (mail-abbrevs-setup)
1374       (mail-aliases-setup)))
1375   (message-set-auto-save-file-name)
1376   (unless (string-match "XEmacs" emacs-version)
1377     (set (make-local-variable 'font-lock-defaults)
1378          '(message-font-lock-keywords t)))
1379   (make-local-variable 'adaptive-fill-regexp)
1380   (setq adaptive-fill-regexp
1381         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1382   (unless (boundp 'adaptive-fill-first-line-regexp)
1383     (setq adaptive-fill-first-line-regexp nil))
1384   (make-local-variable 'adaptive-fill-first-line-regexp)
1385   (setq adaptive-fill-first-line-regexp
1386         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1387                 adaptive-fill-first-line-regexp))
1388   (mm-enable-multibyte)
1389   (run-hooks 'text-mode-hook 'message-mode-hook))
1390
1391 \f
1392
1393 ;;;
1394 ;;; Message mode commands
1395 ;;;
1396
1397 ;;; Movement commands
1398
1399 (defun message-goto-to ()
1400   "Move point to the To header."
1401   (interactive)
1402   (message-position-on-field "To"))
1403
1404 (defun message-goto-subject ()
1405   "Move point to the Subject header."
1406   (interactive)
1407   (message-position-on-field "Subject"))
1408
1409 (defun message-goto-cc ()
1410   "Move point to the Cc header."
1411   (interactive)
1412   (message-position-on-field "Cc" "To"))
1413
1414 (defun message-goto-bcc ()
1415   "Move point to the Bcc  header."
1416   (interactive)
1417   (message-position-on-field "Bcc" "Cc" "To"))
1418
1419 (defun message-goto-fcc ()
1420   "Move point to the Fcc header."
1421   (interactive)
1422   (message-position-on-field "Fcc" "To" "Newsgroups"))
1423
1424 (defun message-goto-reply-to ()
1425   "Move point to the Reply-To header."
1426   (interactive)
1427   (message-position-on-field "Reply-To" "Subject"))
1428
1429 (defun message-goto-newsgroups ()
1430   "Move point to the Newsgroups header."
1431   (interactive)
1432   (message-position-on-field "Newsgroups"))
1433
1434 (defun message-goto-distribution ()
1435   "Move point to the Distribution header."
1436   (interactive)
1437   (message-position-on-field "Distribution"))
1438
1439 (defun message-goto-followup-to ()
1440   "Move point to the Followup-To header."
1441   (interactive)
1442   (message-position-on-field "Followup-To" "Newsgroups"))
1443
1444 (defun message-goto-keywords ()
1445   "Move point to the Keywords header."
1446   (interactive)
1447   (message-position-on-field "Keywords" "Subject"))
1448
1449 (defun message-goto-summary ()
1450   "Move point to the Summary header."
1451   (interactive)
1452   (message-position-on-field "Summary" "Subject"))
1453
1454 (defun message-goto-body ()
1455   "Move point to the beginning of the message body."
1456   (interactive)
1457   (if (looking-at "[ \t]*\n") (expand-abbrev))
1458   (goto-char (point-min))
1459   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1460
1461 (defun message-goto-eoh ()
1462   "Move point to the end of the headers."
1463   (interactive)
1464   (message-goto-body)
1465   (forward-line -2))
1466
1467 (defun message-goto-signature ()
1468   "Move point to the beginning of the message signature.
1469 If there is no signature in the article, go to the end and
1470 return nil."
1471   (interactive)
1472   (goto-char (point-min))
1473   (if (re-search-forward message-signature-separator nil t)
1474       (forward-line 1)
1475     (goto-char (point-max))
1476     nil))
1477
1478 \f
1479
1480 (defun message-insert-to (&optional force)
1481   "Insert a To header that points to the author of the article being replied to.
1482 If the original author requested not to be sent mail, the function signals
1483 an error.
1484 With the prefix argument FORCE, insert the header anyway."
1485   (interactive "P")
1486   (let ((co (message-fetch-reply-field "mail-copies-to")))
1487     (when (and (null force)
1488                co
1489                (equal (downcase co) "never"))
1490       (error "The user has requested not to have copies sent via mail")))
1491   (when (and (message-position-on-field "To")
1492              (mail-fetch-field "to")
1493              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1494     (insert ", "))
1495   (insert (or (message-fetch-reply-field "reply-to")
1496               (message-fetch-reply-field "from") "")))
1497
1498 (defun message-insert-newsgroups ()
1499   "Insert the Newsgroups header from the article being replied to."
1500   (interactive)
1501   (when (and (message-position-on-field "Newsgroups")
1502              (mail-fetch-field "newsgroups")
1503              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1504     (insert ","))
1505   (insert (or (message-fetch-reply-field "newsgroups") "")))
1506
1507 \f
1508
1509 ;;; Various commands
1510
1511 (defun message-delete-not-region (beg end)
1512   "Delete everything in the body of the current message that is outside of the region."
1513   (interactive "r")
1514   (save-excursion
1515     (goto-char end)
1516     (delete-region (point) (if (not (message-goto-signature))
1517                                (point)
1518                              (forward-line -2)
1519                              (point)))
1520     (insert "\n")
1521     (goto-char beg)
1522     (delete-region beg (progn (message-goto-body)
1523                               (forward-line 2)
1524                               (point))))
1525   (when (message-goto-signature)
1526     (forward-line -2)))
1527
1528 (defun message-kill-to-signature ()
1529   "Deletes all text up to the signature."
1530   (interactive)
1531   (let ((point (point)))
1532     (message-goto-signature)
1533     (unless (eobp)
1534       (forward-line -2))
1535     (kill-region point (point))
1536     (unless (bolp)
1537       (insert "\n"))))
1538
1539 (defun message-newline-and-reformat ()
1540   "Insert four newlines, and then reformat if inside quoted text."
1541   (interactive)
1542   (let ((point (point))
1543         quoted)
1544     (save-excursion
1545       (beginning-of-line)
1546       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1547     (insert "\n\n\n\n")
1548     (when quoted
1549       (insert message-yank-prefix))
1550     (fill-paragraph nil)
1551     (goto-char point)
1552     (forward-line 2)))
1553
1554 (defun message-insert-signature (&optional force)
1555   "Insert a signature.  See documentation for the `message-signature' variable."
1556   (interactive (list 0))
1557   (let* ((signature
1558           (cond
1559            ((and (null message-signature)
1560                  (eq force 0))
1561             (save-excursion
1562               (goto-char (point-max))
1563               (not (re-search-backward
1564                     message-signature-separator nil t))))
1565            ((and (null message-signature)
1566                  force)
1567             t)
1568            ((message-functionp message-signature)
1569             (funcall message-signature))
1570            ((listp message-signature)
1571             (eval message-signature))
1572            (t message-signature)))
1573          (signature
1574           (cond ((stringp signature)
1575                  signature)
1576                 ((and (eq t signature)
1577                       message-signature-file
1578                       (file-exists-p message-signature-file))
1579                  signature))))
1580     (when signature
1581       (goto-char (point-max))
1582       ;; Insert the signature.
1583       (unless (bolp)
1584         (insert "\n"))
1585       (insert "\n-- \n")
1586       (if (eq signature t)
1587           (insert-file-contents message-signature-file)
1588         (insert signature))
1589       (goto-char (point-max))
1590       (or (bolp) (insert "\n")))))
1591
1592 (defun message-elide-region (b e)
1593   "Elide the text between point and mark.
1594 An ellipsis (from `message-elide-elipsis') will be inserted where the
1595 text was killed."
1596   (interactive "r")
1597   (kill-region b e)
1598   (unless (bolp)
1599     (insert "\n"))
1600   (insert message-elide-elipsis))
1601
1602 (defvar message-caesar-translation-table nil)
1603
1604 (defun message-caesar-region (b e &optional n)
1605   "Caesar rotation of region by N, default 13, for decrypting netnews."
1606   (interactive
1607    (list
1608     (min (point) (or (mark t) (point)))
1609     (max (point) (or (mark t) (point)))
1610     (when current-prefix-arg
1611       (prefix-numeric-value current-prefix-arg))))
1612
1613   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1614   (unless (or (zerop n)                 ; no action needed for a rot of 0
1615               (= b e))                  ; no region to rotate
1616     ;; We build the table, if necessary.
1617     (when (or (not message-caesar-translation-table)
1618               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1619         (setq message-caesar-translation-table
1620               (message-make-caesar-translation-table n)))
1621     ;; Then we translate the region.  Do it this way to retain
1622     ;; text properties.
1623     (while (< b e)
1624       (when (< (char-after b) 255)
1625         (subst-char-in-region
1626          b (1+ b) (char-after b)
1627          (aref message-caesar-translation-table (char-after b))))
1628       (incf b))))
1629
1630 (defun message-make-caesar-translation-table (n)
1631   "Create a rot table with offset N."
1632   (let ((i -1)
1633         (table (make-string 256 0)))
1634     (while (< (incf i) 256)
1635       (aset table i i))
1636     (concat
1637      (substring table 0 ?A)
1638      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1639      (substring table ?A (+ ?A n))
1640      (substring table (+ ?A 26) ?a)
1641      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1642      (substring table ?a (+ ?a n))
1643      (substring table (+ ?a 26) 255))))
1644
1645 (defun message-caesar-buffer-body (&optional rotnum)
1646   "Caesar rotates all letters in the current buffer by 13 places.
1647 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1648 With prefix arg, specifies the number of places to rotate each letter forward.
1649 Mail and USENET news headers are not rotated."
1650   (interactive (if current-prefix-arg
1651                    (list (prefix-numeric-value current-prefix-arg))
1652                  (list nil)))
1653   (save-excursion
1654     (save-restriction
1655       (when (message-goto-body)
1656         (narrow-to-region (point) (point-max)))
1657       (message-caesar-region (point-min) (point-max) rotnum))))
1658
1659 (defun message-pipe-buffer-body (program)
1660   "Pipe the message body in the current buffer through PROGRAM."
1661   (save-excursion
1662     (save-restriction
1663       (when (message-goto-body)
1664         (narrow-to-region (point) (point-max)))
1665       (let ((body (buffer-substring (point-min) (point-max))))
1666         (unless (equal 0 (call-process-region
1667                            (point-min) (point-max) program t t))
1668             (insert body)
1669             (message "%s failed." program))))))
1670
1671 (defun message-rename-buffer (&optional enter-string)
1672   "Rename the *message* buffer to \"*message* RECIPIENT\".
1673 If the function is run with a prefix, it will ask for a new buffer
1674 name, rather than giving an automatic name."
1675   (interactive "Pbuffer name: ")
1676   (save-excursion
1677     (save-restriction
1678       (goto-char (point-min))
1679       (narrow-to-region (point)
1680                         (search-forward mail-header-separator nil 'end))
1681       (let* ((mail-to (or
1682                        (if (message-news-p) (message-fetch-field "Newsgroups")
1683                          (message-fetch-field "To"))
1684                        ""))
1685              (mail-trimmed-to
1686               (if (string-match "," mail-to)
1687                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1688                 mail-to))
1689              (name-default (concat "*message* " mail-trimmed-to))
1690              (name (if enter-string
1691                        (read-string "New buffer name: " name-default)
1692                      name-default)))
1693         (rename-buffer name t)))))
1694
1695 (defun message-fill-yanked-message (&optional justifyp)
1696   "Fill the paragraphs of a message yanked into this one.
1697 Numeric argument means justify as well."
1698   (interactive "P")
1699   (save-excursion
1700     (goto-char (point-min))
1701     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1702     (let ((fill-prefix message-yank-prefix))
1703       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1704
1705 (defun message-indent-citation ()
1706   "Modify text just inserted from a message to be cited.
1707 The inserted text should be the region.
1708 When this function returns, the region is again around the modified text.
1709
1710 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1711 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1712   (let ((start (point)))
1713     ;; Remove unwanted headers.
1714     (when message-ignored-cited-headers
1715       (let (all-removed)
1716         (save-restriction
1717           (narrow-to-region
1718            (goto-char start)
1719            (if (search-forward "\n\n" nil t)
1720                (1- (point))
1721              (point)))
1722           (message-remove-header message-ignored-cited-headers t)
1723           (when (= (point-min) (point-max))
1724             (setq all-removed t))
1725           (goto-char (point-max)))
1726         (if all-removed
1727             (goto-char start)
1728           (forward-line 1))))
1729     ;; Delete blank lines at the start of the buffer.
1730     (while (and (point-min)
1731                 (eolp)
1732                 (not (eobp)))
1733       (message-delete-line))
1734     ;; Delete blank lines at the end of the buffer.
1735     (goto-char (point-max))
1736     (unless (eolp)
1737       (insert "\n"))
1738     (while (and (zerop (forward-line -1))
1739                 (looking-at "$"))
1740       (message-delete-line))
1741     ;; Do the indentation.
1742     (if (null message-yank-prefix)
1743         (indent-rigidly start (mark t) message-indentation-spaces)
1744       (save-excursion
1745         (goto-char start)
1746         (while (< (point) (mark t))
1747           (insert message-yank-prefix)
1748           (forward-line 1))))
1749     (goto-char start)))
1750
1751 (defun message-yank-original (&optional arg)
1752   "Insert the message being replied to, if any.
1753 Puts point before the text and mark after.
1754 Normally indents each nonblank line ARG spaces (default 3).  However,
1755 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1756
1757 This function uses `message-cite-function' to do the actual citing.
1758
1759 Just \\[universal-argument] as argument means don't indent, insert no
1760 prefix, and don't delete any headers."
1761   (interactive "P")
1762   (let ((modified (buffer-modified-p)))
1763     (when (and message-reply-buffer
1764                message-cite-function)
1765       (delete-windows-on message-reply-buffer t)
1766       (insert-buffer message-reply-buffer)
1767       (funcall message-cite-function)
1768       (message-exchange-point-and-mark)
1769       (unless (bolp)
1770         (insert ?\n))
1771       (unless modified
1772         (setq message-checksum (message-checksum))))))
1773
1774 (defun message-cite-original-without-signature ()
1775   "Cite function in the standard Message manner."
1776   (let ((start (point))
1777         (end (mark t))
1778         (functions
1779          (when message-indent-citation-function
1780            (if (listp message-indent-citation-function)
1781                message-indent-citation-function
1782              (list message-indent-citation-function)))))
1783     (goto-char end)
1784     (when (re-search-backward "^-- $" start t)
1785       ;; Also peel off any blank lines before the signature.
1786       (forward-line -1)
1787       (while (looking-at "^[ \t]*$")
1788         (forward-line -1))
1789       (forward-line 1)
1790       (delete-region (point) end))
1791     (goto-char start)
1792     (while functions
1793       (funcall (pop functions)))
1794     (when message-citation-line-function
1795       (unless (bolp)
1796         (insert "\n"))
1797       (funcall message-citation-line-function))))
1798
1799 (defvar mail-citation-hook) ;Compiler directive
1800 (defun message-cite-original ()
1801   "Cite function in the standard Message manner."
1802   (if (and (boundp 'mail-citation-hook)
1803            mail-citation-hook)
1804       (run-hooks 'mail-citation-hook)
1805     (let ((start (point))
1806           (functions
1807            (when message-indent-citation-function
1808              (if (listp message-indent-citation-function)
1809                  message-indent-citation-function
1810                (list message-indent-citation-function)))))
1811       (goto-char start)
1812       (while functions
1813         (funcall (pop functions)))
1814       (when message-citation-line-function
1815         (unless (bolp)
1816           (insert "\n"))
1817         (funcall message-citation-line-function)))))
1818
1819 (defun message-insert-citation-line ()
1820   "Function that inserts a simple citation line."
1821   (when message-reply-headers
1822     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1823
1824 (defun message-position-on-field (header &rest afters)
1825   (let ((case-fold-search t))
1826     (save-restriction
1827       (narrow-to-region
1828        (goto-char (point-min))
1829        (progn
1830          (re-search-forward
1831           (concat "^" (regexp-quote mail-header-separator) "$"))
1832          (match-beginning 0)))
1833       (goto-char (point-min))
1834       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1835           (progn
1836             (re-search-forward "^[^ \t]" nil 'move)
1837             (beginning-of-line)
1838             (skip-chars-backward "\n")
1839             t)
1840         (while (and afters
1841                     (not (re-search-forward
1842                           (concat "^" (regexp-quote (car afters)) ":")
1843                           nil t)))
1844           (pop afters))
1845         (when afters
1846           (re-search-forward "^[^ \t]" nil 'move)
1847           (beginning-of-line))
1848         (insert header ": \n")
1849         (forward-char -1)
1850         nil))))
1851
1852 (defun message-remove-signature ()
1853   "Remove the signature from the text between point and mark.
1854 The text will also be indented the normal way."
1855   (save-excursion
1856     (let ((start (point))
1857           mark)
1858       (if (not (re-search-forward message-signature-separator (mark t) t))
1859           ;; No signature here, so we just indent the cited text.
1860           (message-indent-citation)
1861         ;; Find the last non-empty line.
1862         (forward-line -1)
1863         (while (looking-at "[ \t]*$")
1864           (forward-line -1))
1865         (forward-line 1)
1866         (setq mark (set-marker (make-marker) (point)))
1867         (goto-char start)
1868         (message-indent-citation)
1869         ;; Enable undoing the deletion.
1870         (undo-boundary)
1871         (delete-region mark (mark t))
1872         (set-marker mark nil)))))
1873
1874 \f
1875
1876 ;;;
1877 ;;; Sending messages
1878 ;;;
1879
1880 (defun message-send-and-exit (&optional arg)
1881   "Send message like `message-send', then, if no errors, exit from mail buffer."
1882   (interactive "P")
1883   (let ((buf (current-buffer))
1884         (actions message-exit-actions))
1885     (when (and (message-send arg)
1886                (buffer-name buf))
1887       (if message-kill-buffer-on-exit
1888           (kill-buffer buf)
1889         (bury-buffer buf)
1890         (when (eq buf (current-buffer))
1891           (message-bury buf)))
1892       (message-do-actions actions)
1893       t)))
1894
1895 (defun message-dont-send ()
1896   "Don't send the message you have been editing."
1897   (interactive)
1898   (set-buffer-modified-p t)
1899   (save-buffer)
1900   (let ((actions message-postpone-actions))
1901     (message-bury (current-buffer))
1902     (message-do-actions actions)))
1903
1904 (defun message-kill-buffer ()
1905   "Kill the current buffer."
1906   (interactive)
1907   (when (or (not (buffer-modified-p))
1908             (yes-or-no-p "Message modified; kill anyway? "))
1909     (let ((actions message-kill-actions))
1910       (setq buffer-file-name nil)
1911       (kill-buffer (current-buffer))
1912       (message-do-actions actions))))
1913
1914 (defun message-bury (buffer)
1915   "Bury this mail buffer."
1916   (let ((newbuf (other-buffer buffer)))
1917     (bury-buffer buffer)
1918     (if (and (fboundp 'frame-parameters)
1919              (cdr (assq 'dedicated (frame-parameters)))
1920              (not (null (delq (selected-frame) (visible-frame-list)))))
1921         (delete-frame (selected-frame))
1922       (switch-to-buffer newbuf))))
1923
1924 (defun message-send (&optional arg)
1925   "Send the message in the current buffer.
1926 If `message-interactive' is non-nil, wait for success indication
1927 or error messages, and inform user.
1928 Otherwise any failure is reported in a message back to
1929 the user from the mailer."
1930   (interactive "P")
1931   ;; Disabled test.
1932   (when (or (buffer-modified-p)
1933             (message-check-element 'unchanged)
1934             (y-or-n-p "No changes in the buffer; really send? "))
1935     ;; Make it possible to undo the coming changes.
1936     (undo-boundary)
1937     (let ((inhibit-read-only t))
1938       (put-text-property (point-min) (point-max) 'read-only nil))
1939     (message-fix-before-sending)
1940     (run-hooks 'message-send-hook)
1941     (message "Sending...")
1942     (let ((alist message-send-method-alist)
1943           (success t)
1944           elem sent)
1945       (while (and success
1946                   (setq elem (pop alist)))
1947         (when (and (or (not (funcall (cadr elem)))
1948                        (and (or (not (memq (car elem)
1949                                            message-sent-message-via))
1950                                 (y-or-n-p
1951                                  (format
1952                                   "Already sent message via %s; resend? "
1953                                   (car elem))))
1954                             (setq success (funcall (caddr elem) arg)))))
1955           (setq sent t)))
1956       (when (and success sent)
1957         (message-do-fcc)
1958         ;;(when (fboundp 'mail-hist-put-headers-into-history)
1959         ;; (mail-hist-put-headers-into-history))
1960         (run-hooks 'message-sent-hook)
1961         (message "Sending...done")
1962         ;; Mark the buffer as unmodified and delete autosave.
1963         (set-buffer-modified-p nil)
1964         (delete-auto-save-file-if-necessary t)
1965         (message-disassociate-draft)
1966         ;; Delete other mail buffers and stuff.
1967         (message-do-send-housekeeping)
1968         (message-do-actions message-send-actions)
1969         ;; Return success.
1970         t))))
1971
1972 (defun message-send-via-mail (arg)
1973   "Send the current message via mail."
1974   (message-send-mail arg))
1975
1976 (defun message-send-via-news (arg)
1977   "Send the current message via news."
1978   (funcall message-send-news-function arg))
1979
1980 (defun message-fix-before-sending ()
1981   "Do various things to make the message nice before sending it."
1982   ;; Make sure there's a newline at the end of the message.
1983   (goto-char (point-max))
1984   (unless (bolp)
1985     (insert "\n"))
1986   ;; Delete all invisible text.
1987   (when (text-property-any (point-min) (point-max) 'invisible t)
1988     (put-text-property (point-min) (point-max) 'invisible nil)
1989     (unless (yes-or-no-p "Invisible text found and made visible; continue posting?")
1990       (error "Invisible text found and made visible"))))
1991
1992 (defun message-add-action (action &rest types)
1993   "Add ACTION to be performed when doing an exit of type TYPES."
1994   (let (var)
1995     (while types
1996       (set (setq var (intern (format "message-%s-actions" (pop types))))
1997            (nconc (symbol-value var) (list action))))))
1998
1999 (defun message-do-actions (actions)
2000   "Perform all actions in ACTIONS."
2001   ;; Now perform actions on successful sending.
2002   (while actions
2003     (ignore-errors
2004       (cond
2005        ;; A simple function.
2006        ((message-functionp (car actions))
2007         (funcall (car actions)))
2008        ;; Something to be evaled.
2009        (t
2010         (eval (car actions)))))
2011     (pop actions)))
2012
2013 (defun message-send-mail (&optional arg)
2014   (require 'mail-utils)
2015   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2016         (case-fold-search nil)
2017         (news (message-news-p))
2018         (mailbuf (current-buffer)))
2019     (save-restriction
2020       (message-narrow-to-headers)
2021       ;; Insert some headers.
2022       (let ((message-deletable-headers
2023              (if news nil message-deletable-headers)))
2024         (message-generate-headers message-required-mail-headers))
2025       (rfc2047-encode-message-header)
2026       ;; Let the user do all of the above.
2027       (run-hooks 'message-header-hook))
2028     (message-encode-message-body)
2029     (unwind-protect
2030         (save-excursion
2031           (set-buffer tembuf)
2032           (erase-buffer)
2033           ;; Avoid copying text props.
2034           (insert (format
2035                    "%s" (save-excursion
2036                           (set-buffer mailbuf)
2037                           (buffer-string))))
2038           ;; Remove some headers.
2039           (save-restriction
2040             (message-narrow-to-headers)
2041             ;; Remove some headers.
2042             (message-remove-header message-ignored-mail-headers t))
2043           (goto-char (point-max))
2044           ;; require one newline at the end.
2045           (or (= (preceding-char) ?\n)
2046               (insert ?\n))
2047           (when (and news
2048                      (or (message-fetch-field "cc")
2049                          (message-fetch-field "to")))
2050             (message-insert-courtesy-copy))
2051           (funcall message-send-mail-function))
2052       (kill-buffer tembuf))
2053     (set-buffer mailbuf)
2054     (push 'mail message-sent-message-via)))
2055
2056 (defun message-send-mail-with-sendmail ()
2057   "Send off the prepared buffer with sendmail."
2058   (let ((errbuf (if message-interactive
2059                     (generate-new-buffer " sendmail errors")
2060                   0))
2061         resend-to-addresses delimline)
2062     (let ((case-fold-search t))
2063       (save-restriction
2064         (message-narrow-to-headers)
2065         (setq resend-to-addresses (message-fetch-field "resent-to")))
2066       ;; Change header-delimiter to be what sendmail expects.
2067       (goto-char (point-min))
2068       (re-search-forward
2069        (concat "^" (regexp-quote mail-header-separator) "\n"))
2070       (replace-match "\n")
2071       (backward-char 1)
2072       (setq delimline (point-marker))
2073       (run-hooks 'message-send-mail-hook)
2074       ;; Insert an extra newline if we need it to work around
2075       ;; Sun's bug that swallows newlines.
2076       (goto-char (1+ delimline))
2077       (when (eval message-mailer-swallows-blank-line)
2078         (newline))
2079       (when message-interactive
2080         (save-excursion
2081           (set-buffer errbuf)
2082           (erase-buffer))))
2083     (let ((default-directory "/")
2084           (coding-system-for-write message-send-coding-system))
2085       (apply 'call-process-region
2086              (append (list (point-min) (point-max)
2087                            (if (boundp 'sendmail-program)
2088                                sendmail-program
2089                              "/usr/lib/sendmail")
2090                            nil errbuf nil "-oi")
2091                      ;; Always specify who from,
2092                      ;; since some systems have broken sendmails.
2093                      ;; But some systems are more broken with -f, so
2094                      ;; we'll let users override this.
2095                      (if (null message-sendmail-f-is-evil)
2096                          (list "-f" (user-login-name)))
2097                      ;; These mean "report errors by mail"
2098                      ;; and "deliver in background".
2099                      (if (null message-interactive) '("-oem" "-odb"))
2100                      ;; Get the addresses from the message
2101                      ;; unless this is a resend.
2102                      ;; We must not do that for a resend
2103                      ;; because we would find the original addresses.
2104                      ;; For a resend, include the specific addresses.
2105                      (if resend-to-addresses
2106                          (list resend-to-addresses)
2107                        '("-t")))))
2108     (when message-interactive
2109       (save-excursion
2110         (set-buffer errbuf)
2111         (goto-char (point-min))
2112         (while (re-search-forward "\n\n* *" nil t)
2113           (replace-match "; "))
2114         (if (not (zerop (buffer-size)))
2115             (error "Sending...failed to %s"
2116                    (buffer-substring (point-min) (point-max)))))
2117       (when (bufferp errbuf)
2118         (kill-buffer errbuf)))))
2119
2120 (defun message-send-mail-with-qmail ()
2121   "Pass the prepared message buffer to qmail-inject.
2122 Refer to the documentation for the variable `message-send-mail-function'
2123 to find out how to use this."
2124   ;; replace the header delimiter with a blank line
2125   (goto-char (point-min))
2126   (re-search-forward
2127    (concat "^" (regexp-quote mail-header-separator) "\n"))
2128   (replace-match "\n")
2129   (run-hooks 'message-send-mail-hook)
2130   ;; send the message
2131   (case
2132       (let ((coding-system-for-write message-send-coding-system))
2133         (apply
2134          'call-process-region 1 (point-max) message-qmail-inject-program
2135          nil nil nil
2136          ;; qmail-inject's default behaviour is to look for addresses on the
2137          ;; command line; if there're none, it scans the headers.
2138          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2139          ;;
2140          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2141          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2142          ;; message from stdin.
2143          ;;
2144          ;; qmail also has the advantage of not having been raped by
2145          ;; various vendors, so we don't have to allow for that, either --
2146          ;; compare this with message-send-mail-with-sendmail and weep
2147          ;; for sendmail's lost innocence.
2148          ;;
2149          ;; all this is way cool coz it lets us keep the arguments entirely
2150          ;; free for -inject-arguments -- a big win for the user and for us
2151          ;; since we don't have to play that double-guessing game and the user
2152          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2153          message-qmail-inject-args))
2154     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2155     ;; we have to look at the retval instead
2156     (0 nil)
2157     (1   (error "qmail-inject reported permanent failure"))
2158     (111 (error "qmail-inject reported transient failure"))
2159     ;; should never happen
2160     (t   (error "qmail-inject reported unknown failure"))))
2161
2162 (defun message-send-mail-with-mh ()
2163   "Send the prepared message buffer with mh."
2164   (let ((mh-previous-window-config nil)
2165         (name (mh-new-draft-name)))
2166     (setq buffer-file-name name)
2167     ;; MH wants to generate these headers itself.
2168     (when message-mh-deletable-headers
2169       (let ((headers message-mh-deletable-headers))
2170         (while headers
2171           (goto-char (point-min))
2172           (and (re-search-forward
2173                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2174                (message-delete-line))
2175           (pop headers))))
2176     (run-hooks 'message-send-mail-hook)
2177     ;; Pass it on to mh.
2178     (mh-send-letter)))
2179
2180 (defun message-send-news (&optional arg)
2181   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2182         (case-fold-search nil)
2183         (method (if (message-functionp message-post-method)
2184                     (funcall message-post-method arg)
2185                   message-post-method))
2186         (messbuf (current-buffer))
2187         (message-syntax-checks
2188          (if arg
2189              (cons '(existing-newsgroups . disabled)
2190                    message-syntax-checks)
2191            message-syntax-checks))
2192         result)
2193     (save-restriction
2194       (message-narrow-to-headers)
2195       ;; Insert some headers.
2196       (message-generate-headers message-required-news-headers)
2197       (rfc2047-encode-message-header)
2198       ;; Let the user do all of the above.
2199       (run-hooks 'message-header-hook))
2200     (message-encode-message-body)
2201     (message-cleanup-headers)
2202     (if (not (message-check-news-syntax))
2203         (progn
2204           ;;(message "Posting not performed")
2205           nil)
2206       (unwind-protect
2207           (save-excursion
2208             (set-buffer tembuf)
2209             (buffer-disable-undo (current-buffer))
2210             (erase-buffer)
2211             ;; Avoid copying text props.
2212             (insert (format
2213                      "%s" (save-excursion
2214                             (set-buffer messbuf)
2215                             (buffer-string))))
2216             ;; Remove some headers.
2217             (save-restriction
2218               (message-narrow-to-headers)
2219               ;; Remove some headers.
2220               (message-remove-header message-ignored-news-headers t))
2221             (goto-char (point-max))
2222             ;; require one newline at the end.
2223             (or (= (preceding-char) ?\n)
2224                 (insert ?\n))
2225             (let ((case-fold-search t))
2226               ;; Remove the delimiter.
2227               (goto-char (point-min))
2228               (re-search-forward
2229                (concat "^" (regexp-quote mail-header-separator) "\n"))
2230               (replace-match "\n")
2231               (backward-char 1))
2232             (run-hooks 'message-send-news-hook)
2233             ;;(require (car method))
2234             ;;(funcall (intern (format "%s-open-server" (car method)))
2235             ;;(cadr method) (cddr method))
2236             ;;(setq result
2237             ;;    (funcall (intern (format "%s-request-post" (car method)))
2238             ;;             (cadr method)))
2239             (gnus-open-server method)
2240             (setq result (gnus-request-post method)))
2241         (kill-buffer tembuf))
2242       (set-buffer messbuf)
2243       (if result
2244           (push 'news message-sent-message-via)
2245         (message "Couldn't send message via news: %s"
2246                  (nnheader-get-report (car method)))
2247         nil))))
2248
2249 ;;;
2250 ;;; Header generation & syntax checking.
2251 ;;;
2252
2253 (defmacro message-check (type &rest forms)
2254   "Eval FORMS if TYPE is to be checked."
2255   `(or (message-check-element ,type)
2256        (save-excursion
2257          ,@forms)))
2258
2259 (put 'message-check 'lisp-indent-function 1)
2260 (put 'message-check 'edebug-form-spec '(form body))
2261
2262 (defun message-check-element (type)
2263   "Returns non-nil if this type is not to be checked."
2264   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2265       t
2266     (let ((able (assq type message-syntax-checks)))
2267       (and (consp able)
2268            (eq (cdr able) 'disabled)))))
2269
2270 (defun message-check-news-syntax ()
2271   "Check the syntax of the message."
2272   (save-excursion
2273     (save-restriction
2274       (widen)
2275       (and
2276        ;; We narrow to the headers and check them first.
2277        (save-excursion
2278          (save-restriction
2279            (message-narrow-to-headers)
2280            (message-check-news-header-syntax)))
2281        ;; Check the body.
2282        (message-check-news-body-syntax)))))
2283
2284 (defun message-check-news-header-syntax ()
2285   (and
2286    ;; Check the Subject header.
2287    (message-check 'subject
2288      (let* ((case-fold-search t)
2289             (subject (message-fetch-field "subject")))
2290        (or
2291         (and subject
2292              (not (string-match "\\`[ \t]*\\'" subject)))
2293         (ignore
2294          (message
2295           "The subject field is empty or missing.  Posting is denied.")))))
2296    ;; Check for commands in Subject.
2297    (message-check 'subject-cmsg
2298      (if (string-match "^cmsg " (message-fetch-field "subject"))
2299          (y-or-n-p
2300           "The control code \"cmsg\" is in the subject.  Really post? ")
2301        t))
2302    ;; Check for multiple identical headers.
2303    (message-check 'multiple-headers
2304      (let (found)
2305        (while (and (not found)
2306                    (re-search-forward "^[^ \t:]+: " nil t))
2307          (save-excursion
2308            (or (re-search-forward
2309                 (concat "^"
2310                         (regexp-quote
2311                          (setq found
2312                                (buffer-substring
2313                                 (match-beginning 0) (- (match-end 0) 2))))
2314                         ":")
2315                 nil t)
2316                (setq found nil))))
2317        (if found
2318            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2319          t)))
2320    ;; Check for Version and Sendsys.
2321    (message-check 'sendsys
2322      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2323          (y-or-n-p
2324           (format "The article contains a %s command.  Really post? "
2325                   (buffer-substring (match-beginning 0)
2326                                     (1- (match-end 0)))))
2327        t))
2328    ;; See whether we can shorten Followup-To.
2329    (message-check 'shorten-followup-to
2330      (let ((newsgroups (message-fetch-field "newsgroups"))
2331            (followup-to (message-fetch-field "followup-to"))
2332            to)
2333        (when (and newsgroups
2334                   (string-match "," newsgroups)
2335                   (not followup-to)
2336                   (not
2337                    (zerop
2338                     (length
2339                      (setq to (completing-read
2340                                "Followups to: (default all groups) "
2341                                (mapcar (lambda (g) (list g))
2342                                        (cons "poster"
2343                                              (message-tokenize-header
2344                                               newsgroups)))))))))
2345          (goto-char (point-min))
2346          (insert "Followup-To: " to "\n"))
2347        t))
2348    ;; Check "Shoot me".
2349    (message-check 'shoot
2350      (if (re-search-forward
2351           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2352          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2353        t))
2354    ;; Check for Approved.
2355    (message-check 'approved
2356      (if (re-search-forward "^Approved:" nil t)
2357          (y-or-n-p "The article contains an Approved header.  Really post? ")
2358        t))
2359    ;; Check the Message-ID header.
2360    (message-check 'message-id
2361      (let* ((case-fold-search t)
2362             (message-id (message-fetch-field "message-id" t)))
2363        (or (not message-id)
2364            ;; Is there an @ in the ID?
2365            (and (string-match "@" message-id)
2366                 ;; Is there a dot in the ID?
2367                 (string-match "@[^.]*\\." message-id)
2368                 ;; Does the ID end with a dot?
2369                 (not (string-match "\\.>" message-id)))
2370            (y-or-n-p
2371             (format "The Message-ID looks strange: \"%s\".  Really post? "
2372                     message-id)))))
2373    ;; Check the Newsgroups & Followup-To headers.
2374    (message-check 'existing-newsgroups
2375      (let* ((case-fold-search t)
2376             (newsgroups (message-fetch-field "newsgroups"))
2377             (followup-to (message-fetch-field "followup-to"))
2378             (groups (message-tokenize-header
2379                      (if followup-to
2380                          (concat newsgroups "," followup-to)
2381                        newsgroups)))
2382             (hashtb (and (boundp 'gnus-active-hashtb)
2383                          gnus-active-hashtb))
2384             errors)
2385        (if (or (not hashtb)
2386                (not (boundp 'gnus-read-active-file))
2387                (not gnus-read-active-file)
2388                (eq gnus-read-active-file 'some))
2389            t
2390          (while groups
2391            (when (and (not (boundp (intern (car groups) hashtb)))
2392                       (not (equal (car groups) "poster")))
2393              (push (car groups) errors))
2394            (pop groups))
2395          (if (not errors)
2396              t
2397            (y-or-n-p
2398             (format
2399              "Really post to %s unknown group%s: %s "
2400              (if (= (length errors) 1) "this" "these")
2401              (if (= (length errors) 1) "" "s")
2402              (mapconcat 'identity errors ", ")))))))
2403    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2404    (message-check 'valid-newsgroups
2405      (let ((case-fold-search t)
2406            (headers '("Newsgroups" "Followup-To"))
2407            header error)
2408        (while (and headers (not error))
2409          (when (setq header (mail-fetch-field (car headers)))
2410            (if (or
2411                 (not
2412                  (string-match
2413                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2414                   header))
2415                 (memq
2416                  nil (mapcar
2417                       (lambda (g)
2418                         (not (string-match "\\.\\'\\|\\.\\." g)))
2419                       (message-tokenize-header header ","))))
2420                (setq error t)))
2421          (unless error
2422            (pop headers)))
2423        (if (not error)
2424            t
2425          (y-or-n-p
2426           (format "The %s header looks odd: \"%s\".  Really post? "
2427                   (car headers) header)))))
2428    (message-check 'repeated-newsgroups
2429      (let ((case-fold-search t)
2430            (headers '("Newsgroups" "Followup-To"))
2431            header error groups group)
2432        (while (and headers
2433                    (not error))
2434          (when (setq header (mail-fetch-field (pop headers)))
2435            (setq groups (message-tokenize-header header ","))
2436            (while (setq group (pop groups))
2437              (when (member group groups)
2438                (setq error group
2439                      groups nil)))))
2440        (if (not error)
2441            t
2442          (y-or-n-p
2443           (format "Group %s is repeated in headers.  Really post? " error)))))
2444    ;; Check the From header.
2445    (message-check 'from
2446      (let* ((case-fold-search t)
2447             (from (message-fetch-field "from"))
2448             (ad (nth 1 (mail-extract-address-components from))))
2449        (cond
2450         ((not from)
2451          (message "There is no From line.  Posting is denied.")
2452          nil)
2453         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2454              (string-match "\\.\\." ad) ;larsi@ifi..uio
2455              (string-match "@\\." ad)   ;larsi@.ifi.uio
2456              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2457              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2458              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2459          (message
2460           "Denied posting -- the From looks strange: \"%s\"." from)
2461          nil)
2462         (t t))))))
2463
2464 (defun message-check-news-body-syntax ()
2465   (and
2466    ;; Check for long lines.
2467    (message-check 'long-lines
2468      (goto-char (point-min))
2469      (re-search-forward
2470       (concat "^" (regexp-quote mail-header-separator) "$"))
2471      (while (and
2472              (progn
2473                (end-of-line)
2474                (< (current-column) 80))
2475              (zerop (forward-line 1))))
2476      (or (bolp)
2477          (eobp)
2478          (y-or-n-p
2479           "You have lines longer than 79 characters.  Really post? ")))
2480    ;; Check whether the article is empty.
2481    (message-check 'empty
2482      (goto-char (point-min))
2483      (re-search-forward
2484       (concat "^" (regexp-quote mail-header-separator) "$"))
2485      (forward-line 1)
2486      (let ((b (point)))
2487        (goto-char (point-max))
2488        (re-search-backward message-signature-separator nil t)
2489        (beginning-of-line)
2490        (or (re-search-backward "[^ \n\t]" b t)
2491            (y-or-n-p "Empty article.  Really post? "))))
2492    ;; Check for control characters.
2493    (message-check 'control-chars
2494      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2495          (y-or-n-p
2496           "The article contains control characters.  Really post? ")
2497        t))
2498    ;; Check excessive size.
2499    (message-check 'size
2500      (if (> (buffer-size) 60000)
2501          (y-or-n-p
2502           (format "The article is %d octets long.  Really post? "
2503                   (buffer-size)))
2504        t))
2505    ;; Check whether any new text has been added.
2506    (message-check 'new-text
2507      (or
2508       (not message-checksum)
2509       (not (eq (message-checksum) message-checksum))
2510       (y-or-n-p
2511        "It looks like no new text has been added.  Really post? ")))
2512    ;; Check the length of the signature.
2513    (message-check 'signature
2514      (goto-char (point-max))
2515      (if (or (not (re-search-backward message-signature-separator nil t))
2516              (search-forward message-forward-end-separator nil t))
2517          t
2518        (if (> (count-lines (point) (point-max)) 5)
2519            (y-or-n-p
2520             (format
2521              "Your .sig is %d lines; it should be max 4.  Really post? "
2522              (1- (count-lines (point) (point-max)))))
2523          t)))))
2524
2525 (defun message-checksum ()
2526   "Return a \"checksum\" for the current buffer."
2527   (let ((sum 0))
2528     (save-excursion
2529       (goto-char (point-min))
2530       (re-search-forward
2531        (concat "^" (regexp-quote mail-header-separator) "$"))
2532       (while (not (eobp))
2533         (when (not (looking-at "[ \t\n]"))
2534           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2535                             (following-char))))
2536         (forward-char 1)))
2537     sum))
2538
2539 (defun message-do-fcc ()
2540   "Process Fcc headers in the current buffer."
2541   (let ((case-fold-search t)
2542         (buf (current-buffer))
2543         list file)
2544     (save-excursion
2545       (set-buffer (get-buffer-create " *message temp*"))
2546       (buffer-disable-undo (current-buffer))
2547       (erase-buffer)
2548       (insert-buffer-substring buf)
2549       (save-restriction
2550         (message-narrow-to-headers)
2551         (while (setq file (message-fetch-field "fcc"))
2552           (push file list)
2553           (message-remove-header "fcc" nil t)))
2554       (goto-char (point-min))
2555       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2556       (replace-match "" t t)
2557       ;; Process FCC operations.
2558       (while list
2559         (setq file (pop list))
2560         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2561             ;; Pipe the article to the program in question.
2562             (call-process-region (point-min) (point-max) shell-file-name
2563                                  nil nil nil shell-command-switch
2564                                  (match-string 1 file))
2565           ;; Save the article.
2566           (setq file (expand-file-name file))
2567           (unless (file-exists-p (file-name-directory file))
2568             (make-directory (file-name-directory file) t))
2569           (if (and message-fcc-handler-function
2570                    (not (eq message-fcc-handler-function 'rmail-output)))
2571               (funcall message-fcc-handler-function file)
2572             (if (and (file-readable-p file) (mail-file-babyl-p file))
2573                 (rmail-output file 1 nil t)
2574               (let ((mail-use-rfc822 t))
2575                 (rmail-output file 1 t t))))))
2576
2577       (kill-buffer (current-buffer)))))
2578
2579 (defun message-output (filename)
2580   "Append this article to Unix/babyl mail file.."
2581   (if (and (file-readable-p filename)
2582            (mail-file-babyl-p filename))
2583       (rmail-output-to-rmail-file filename t)
2584     (gnus-output-to-mail filename t)))
2585
2586 (defun message-cleanup-headers ()
2587   "Do various automatic cleanups of the headers."
2588   ;; Remove empty lines in the header.
2589   (save-restriction
2590     (message-narrow-to-headers)
2591     ;; Remove blank lines.
2592     (while (re-search-forward "^[ \t]*\n" nil t)
2593       (replace-match "" t t))
2594
2595     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2596     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2597     ;; embedded line breaks.
2598     (goto-char (point-min))
2599     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2600       (save-restriction
2601         (narrow-to-region
2602          (point)
2603          (if (re-search-forward "^[^ \t]" nil t)
2604              (match-beginning 0)
2605            (forward-line 1)
2606            (point)))
2607         (goto-char (point-min))
2608         (while (re-search-forward "\n[ \t]+" nil t)
2609           (replace-match " " t t))      ;No line breaks (too confusing)
2610         (goto-char (point-min))
2611         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2612           (replace-match "," t t))
2613         (goto-char (point-min))
2614         ;; Remove trailing commas.
2615         (when (re-search-forward ",+$" nil t)
2616           (replace-match "" t t))))))
2617
2618 (defun message-make-date (&optional now)
2619   "Make a valid data header.
2620 If NOW, use that time instead."
2621   (let* ((now (or now (current-time)))
2622          (zone (nth 8 (decode-time now)))
2623          (sign "+"))
2624     ;; We do all of this because XEmacs doesn't have the %z spec.
2625     (when (> (/ zone 3600) 12)
2626       (setq sign "-"
2627             zone (- zone (* 3600 12))))
2628     (concat (format-time-string "%d %b %Y %H:%M:%S " (or now (current-time)))
2629             (format "%s%02d%02d"
2630                     sign (/ zone 3600)
2631                     (% zone 3600)))))
2632
2633 (defun message-make-message-id ()
2634   "Make a unique Message-ID."
2635   (concat "<" (message-unique-id)
2636           (let ((psubject (save-excursion (message-fetch-field "subject")))
2637                 (psupersedes
2638                  (save-excursion (message-fetch-field "supersedes"))))
2639             (if (or
2640                  (and message-reply-headers
2641                       (mail-header-references message-reply-headers)
2642                       (mail-header-subject message-reply-headers)
2643                       psubject
2644                       (mail-header-subject message-reply-headers)
2645                       (not (string=
2646                             (message-strip-subject-re
2647                              (mail-header-subject message-reply-headers))
2648                             (message-strip-subject-re psubject))))
2649                  (and psupersedes
2650                       (string-match "_-_@" psupersedes)))
2651                 "_-_" ""))
2652           "@" (message-make-fqdn) ">"))
2653
2654 (defvar message-unique-id-char nil)
2655
2656 ;; If you ever change this function, make sure the new version
2657 ;; cannot generate IDs that the old version could.
2658 ;; You might for example insert a "." somewhere (not next to another dot
2659 ;; or string boundary), or modify the "fsf" string.
2660 (defun message-unique-id ()
2661   ;; Don't use microseconds from (current-time), they may be unsupported.
2662   ;; Instead we use this randomly inited counter.
2663   (setq message-unique-id-char
2664         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2665            ;; (current-time) returns 16-bit ints,
2666            ;; and 2^16*25 just fits into 4 digits i base 36.
2667            (* 25 25)))
2668   (let ((tm (current-time)))
2669     (concat
2670      (if (memq system-type '(ms-dos emx vax-vms))
2671          (let ((user (downcase (user-login-name))))
2672            (while (string-match "[^a-z0-9_]" user)
2673              (aset user (match-beginning 0) ?_))
2674            user)
2675        (message-number-base36 (user-uid) -1))
2676      (message-number-base36 (+ (car   tm)
2677                                (lsh (% message-unique-id-char 25) 16)) 4)
2678      (message-number-base36 (+ (nth 1 tm)
2679                                (lsh (/ message-unique-id-char 25) 16)) 4)
2680      ;; Append the newsreader name, because while the generated
2681      ;; ID is unique to this newsreader, other newsreaders might
2682      ;; otherwise generate the same ID via another algorithm.
2683      ".fsf")))
2684
2685 (defun message-number-base36 (num len)
2686   (if (if (< len 0)
2687           (<= num 0)
2688         (= len 0))
2689       ""
2690     (concat (message-number-base36 (/ num 36) (1- len))
2691             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2692                                   (% num 36))))))
2693
2694 (defun message-make-organization ()
2695   "Make an Organization header."
2696   (let* ((organization
2697           (when message-user-organization
2698                 (if (message-functionp message-user-organization)
2699                     (funcall message-user-organization)
2700                   message-user-organization))))
2701     (save-excursion
2702       (message-set-work-buffer)
2703       (cond ((stringp organization)
2704              (insert organization))
2705             ((and (eq t organization)
2706                   message-user-organization-file
2707                   (file-exists-p message-user-organization-file))
2708              (insert-file-contents message-user-organization-file)))
2709       (goto-char (point-min))
2710       (while (re-search-forward "[\t\n]+" nil t)
2711         (replace-match "" t t))
2712       (unless (zerop (buffer-size))
2713         (buffer-string)))))
2714
2715 (defun message-make-lines ()
2716   "Count the number of lines and return numeric string."
2717   (save-excursion
2718     (save-restriction
2719       (widen)
2720       (goto-char (point-min))
2721       (re-search-forward
2722        (concat "^" (regexp-quote mail-header-separator) "$"))
2723       (forward-line 1)
2724       (int-to-string (count-lines (point) (point-max))))))
2725
2726 (defun message-make-in-reply-to ()
2727   "Return the In-Reply-To header for this message."
2728   (when message-reply-headers
2729     (let ((from (mail-header-from message-reply-headers))
2730           (date (mail-header-date message-reply-headers)))
2731       (when from
2732         (let ((stop-pos
2733                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2734           (concat (if (and stop-pos
2735                            (not (zerop stop-pos)))
2736                       (substring from 0 stop-pos) from)
2737                   "'s message of \""
2738                   (if (or (not date) (string= date ""))
2739                       "(unknown date)" date)
2740                   "\""))))))
2741
2742 (defun message-make-distribution ()
2743   "Make a Distribution header."
2744   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2745     (cond ((message-functionp message-distribution-function)
2746            (funcall message-distribution-function))
2747           (t orig-distribution))))
2748
2749 (defun message-make-expires ()
2750   "Return an Expires header based on `message-expires'."
2751   (let ((current (current-time))
2752         (future (* 1.0 message-expires 60 60 24)))
2753     ;; Add the future to current.
2754     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2755     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2756     (message-make-date current)))
2757
2758 (defun message-make-path ()
2759   "Return uucp path."
2760   (let ((login-name (user-login-name)))
2761     (cond ((null message-user-path)
2762            (concat (system-name) "!" login-name))
2763           ((stringp message-user-path)
2764            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2765            (concat message-user-path "!" login-name))
2766           (t login-name))))
2767
2768 (defun message-make-from ()
2769   "Make a From header."
2770   (let* ((style message-from-style)
2771          (login (message-make-address))
2772          (fullname
2773           (or (and (boundp 'user-full-name)
2774                    user-full-name)
2775               (user-full-name))))
2776     (when (string= fullname "&")
2777       (setq fullname (user-login-name)))
2778     (save-excursion
2779       (message-set-work-buffer)
2780       (cond
2781        ((or (null style)
2782             (equal fullname ""))
2783         (insert login))
2784        ((or (eq style 'angles)
2785             (and (not (eq style 'parens))
2786                  ;; Use angles if no quoting is needed, or if parens would
2787                  ;; need quoting too.
2788                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2789                      (let ((tmp (concat fullname nil)))
2790                        (while (string-match "([^()]*)" tmp)
2791                          (aset tmp (match-beginning 0) ?-)
2792                          (aset tmp (1- (match-end 0)) ?-))
2793                        (string-match "[\\()]" tmp)))))
2794         (insert fullname)
2795         (goto-char (point-min))
2796         ;; Look for a character that cannot appear unquoted
2797         ;; according to RFC 822.
2798         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2799           ;; Quote fullname, escaping specials.
2800           (goto-char (point-min))
2801           (insert "\"")
2802           (while (re-search-forward "[\"\\]" nil 1)
2803             (replace-match "\\\\\\&" t))
2804           (insert "\""))
2805         (insert " <" login ">"))
2806        (t                               ; 'parens or default
2807         (insert login " (")
2808         (let ((fullname-start (point)))
2809           (insert fullname)
2810           (goto-char fullname-start)
2811           ;; RFC 822 says \ and nonmatching parentheses
2812           ;; must be escaped in comments.
2813           ;; Escape every instance of ()\ ...
2814           (while (re-search-forward "[()\\]" nil 1)
2815             (replace-match "\\\\\\&" t))
2816           ;; ... then undo escaping of matching parentheses,
2817           ;; including matching nested parentheses.
2818           (goto-char fullname-start)
2819           (while (re-search-forward
2820                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2821                   nil 1)
2822             (replace-match "\\1(\\3)" t)
2823             (goto-char fullname-start)))
2824         (insert ")")))
2825       (buffer-string))))
2826
2827 (defun message-make-sender ()
2828   "Return the \"real\" user address.
2829 This function tries to ignore all user modifications, and
2830 give as trustworthy answer as possible."
2831   (concat (user-login-name) "@" (system-name)))
2832
2833 (defun message-make-address ()
2834   "Make the address of the user."
2835   (or (message-user-mail-address)
2836       (concat (user-login-name) "@" (message-make-domain))))
2837
2838 (defun message-user-mail-address ()
2839   "Return the pertinent part of `user-mail-address'."
2840   (when user-mail-address
2841     (if (string-match " " user-mail-address)
2842         (nth 1 (mail-extract-address-components user-mail-address))
2843       user-mail-address)))
2844
2845 (defun message-make-fqdn ()
2846   "Return user's fully qualified domain name."
2847   (let ((system-name (system-name))
2848         (user-mail (message-user-mail-address)))
2849     (cond
2850      ((string-match "[^.]\\.[^.]" system-name)
2851       ;; `system-name' returned the right result.
2852       system-name)
2853      ;; Try `mail-host-address'.
2854      ((and (boundp 'mail-host-address)
2855            (stringp mail-host-address)
2856            (string-match "\\." mail-host-address))
2857       mail-host-address)
2858      ;; We try `user-mail-address' as a backup.
2859      ((and user-mail
2860            (string-match "\\." user-mail)
2861            (string-match "@\\(.*\\)\\'" user-mail))
2862       (match-string 1 user-mail))
2863      ;; Default to this bogus thing.
2864      (t
2865       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2866
2867 (defun message-make-host-name ()
2868   "Return the name of the host."
2869   (let ((fqdn (message-make-fqdn)))
2870     (string-match "^[^.]+\\." fqdn)
2871     (substring fqdn 0 (1- (match-end 0)))))
2872
2873 (defun message-make-domain ()
2874   "Return the domain name."
2875   (or mail-host-address
2876       (message-make-fqdn)))
2877
2878 (defun message-generate-headers (headers)
2879   "Prepare article HEADERS.
2880 Headers already prepared in the buffer are not modified."
2881   (save-restriction
2882     (message-narrow-to-headers)
2883     (let* ((Date (message-make-date))
2884            (Message-ID (message-make-message-id))
2885            (Organization (message-make-organization))
2886            (From (message-make-from))
2887            (Path (message-make-path))
2888            (Subject nil)
2889            (Newsgroups nil)
2890            (In-Reply-To (message-make-in-reply-to))
2891            (To nil)
2892            (Distribution (message-make-distribution))
2893            (Lines (message-make-lines))
2894            (X-Newsreader message-newsreader)
2895            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2896                           message-mailer))
2897            (Expires (message-make-expires))
2898            (case-fold-search t)
2899            header value elem)
2900       ;; First we remove any old generated headers.
2901       (let ((headers message-deletable-headers))
2902         (unless (buffer-modified-p)
2903           (setq headers (delq 'Message-ID (copy-sequence headers))))
2904         (while headers
2905           (goto-char (point-min))
2906           (and (re-search-forward
2907                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2908                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2909                (message-delete-line))
2910           (pop headers)))
2911       ;; Go through all the required headers and see if they are in the
2912       ;; articles already.  If they are not, or are empty, they are
2913       ;; inserted automatically - except for Subject, Newsgroups and
2914       ;; Distribution.
2915       (while headers
2916         (goto-char (point-min))
2917         (setq elem (pop headers))
2918         (if (consp elem)
2919             (if (eq (car elem) 'optional)
2920                 (setq header (cdr elem))
2921               (setq header (car elem)))
2922           (setq header elem))
2923         (when (or (not (re-search-forward
2924                         (concat "^"
2925                                 (regexp-quote
2926                                  (downcase
2927                                   (if (stringp header)
2928                                       header
2929                                     (symbol-name header))))
2930                                 ":")
2931                         nil t))
2932                   (progn
2933                     ;; The header was found.  We insert a space after the
2934                     ;; colon, if there is none.
2935                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2936                     ;; Find out whether the header is empty...
2937                     (looking-at "[ \t]*$")))
2938           ;; So we find out what value we should insert.
2939           (setq value
2940                 (cond
2941                  ((and (consp elem) (eq (car elem) 'optional))
2942                   ;; This is an optional header.  If the cdr of this
2943                   ;; is something that is nil, then we do not insert
2944                   ;; this header.
2945                   (setq header (cdr elem))
2946                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2947                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2948                  ((consp elem)
2949                   ;; The element is a cons.  Either the cdr is a
2950                   ;; string to be inserted verbatim, or it is a
2951                   ;; function, and we insert the value returned from
2952                   ;; this function.
2953                   (or (and (stringp (cdr elem)) (cdr elem))
2954                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2955                  ((and (boundp header) (symbol-value header))
2956                   ;; The element is a symbol.  We insert the value
2957                   ;; of this symbol, if any.
2958                   (symbol-value header))
2959                  (t
2960                   ;; We couldn't generate a value for this header,
2961                   ;; so we just ask the user.
2962                   (read-from-minibuffer
2963                    (format "Empty header for %s; enter value: " header)))))
2964           ;; Finally insert the header.
2965           (when (and value
2966                      (not (equal value "")))
2967             (save-excursion
2968               (if (bolp)
2969                   (progn
2970                     ;; This header didn't exist, so we insert it.
2971                     (goto-char (point-max))
2972                     (insert (if (stringp header) header (symbol-name header))
2973                             ": " value "\n")
2974                     (forward-line -1))
2975                 ;; The value of this header was empty, so we clear
2976                 ;; totally and insert the new value.
2977                 (delete-region (point) (gnus-point-at-eol))
2978                 (insert value))
2979               ;; Add the deletable property to the headers that require it.
2980               (and (memq header message-deletable-headers)
2981                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2982                    (add-text-properties
2983                     (point) (match-end 0)
2984                     '(message-deletable t face italic) (current-buffer)))))))
2985       ;; Insert new Sender if the From is strange.
2986       (let ((from (message-fetch-field "from"))
2987             (sender (message-fetch-field "sender"))
2988             (secure-sender (message-make-sender)))
2989         (when (and from
2990                    (not (message-check-element 'sender))
2991                    (not (string=
2992                          (downcase
2993                           (cadr (mail-extract-address-components from)))
2994                          (downcase secure-sender)))
2995                    (or (null sender)
2996                        (not
2997                         (string=
2998                          (downcase
2999                           (cadr (mail-extract-address-components sender)))
3000                          (downcase secure-sender)))))
3001           (goto-char (point-min))
3002           ;; Rename any old Sender headers to Original-Sender.
3003           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3004             (beginning-of-line)
3005             (insert "Original-")
3006             (beginning-of-line))
3007           (when (or (message-news-p)
3008                     (string-match "@.+\\.." secure-sender))
3009             (insert "Sender: " secure-sender "\n")))))))
3010
3011 (defun message-insert-courtesy-copy ()
3012   "Insert a courtesy message in mail copies of combined messages."
3013   (let (newsgroups)
3014     (save-excursion
3015       (save-restriction
3016         (message-narrow-to-headers)
3017         (when (setq newsgroups (message-fetch-field "newsgroups"))
3018           (goto-char (point-max))
3019           (insert "Posted-To: " newsgroups "\n")))
3020       (forward-line 1)
3021       (when message-courtesy-message
3022         (cond
3023          ((string-match "%s" message-courtesy-message)
3024           (insert (format message-courtesy-message newsgroups)))
3025          (t
3026           (insert message-courtesy-message)))))))
3027
3028 ;;;
3029 ;;; Setting up a message buffer
3030 ;;;
3031
3032 (defun message-fill-address (header value)
3033   (save-restriction
3034     (narrow-to-region (point) (point))
3035     (insert (capitalize (symbol-name header))
3036             ": "
3037             (if (consp value) (car value) value)
3038             "\n")
3039     (narrow-to-region (point-min) (1- (point-max)))
3040     (let (quoted last)
3041       (goto-char (point-min))
3042       (while (not (eobp))
3043         (skip-chars-forward "^,\"" (point-max))
3044         (if (or (= (following-char) ?,)
3045                 (eobp))
3046             (when (not quoted)
3047               (if (and (> (current-column) 78)
3048                        last)
3049                   (progn
3050                     (save-excursion
3051                       (goto-char last)
3052                       (insert "\n\t"))
3053                     (setq last (1+ (point))))
3054                 (setq last (1+ (point)))))
3055           (setq quoted (not quoted)))
3056         (unless (eobp)
3057           (forward-char 1))))
3058     (goto-char (point-max))
3059     (widen)
3060     (forward-line 1)))
3061
3062 (defun message-fill-header (header value)
3063   (let ((begin (point))
3064         (fill-column 990)
3065         (fill-prefix "\t"))
3066     (insert (capitalize (symbol-name header))
3067             ": "
3068             (if (consp value) (car value) value)
3069             "\n")
3070     (save-restriction
3071       (narrow-to-region begin (point))
3072       (fill-region-as-paragraph begin (point))
3073       ;; Tapdance around looong Message-IDs.
3074       (forward-line -1)
3075       (when (looking-at "[ \t]*$")
3076         (message-delete-line))
3077       (goto-char begin)
3078       (re-search-forward ":" nil t)
3079       (when (looking-at "\n[ \t]+")
3080         (replace-match " " t t))
3081       (goto-char (point-max)))))
3082
3083 (defun message-shorten-references (header references)
3084   "Limit REFERENCES to be shorter than 988 characters."
3085   (let ((max 988)
3086         (cut 4)
3087         refs)
3088     (with-temp-buffer
3089       (insert references)
3090       (goto-char (point-min))
3091       (while (re-search-forward "<[^>]+>" nil t)
3092         (push (match-string 0) refs))
3093       (setq refs (nreverse refs))
3094       (while (> (length (mapconcat 'identity refs " ")) max)
3095         (when (< (length refs) (1+ cut))
3096           (decf cut))
3097         (setcdr (nthcdr cut refs) (cddr (nthcdr cut refs)))))
3098     (insert (capitalize (symbol-name header)) ": "
3099             (mapconcat 'identity refs " ") "\n")))
3100
3101 (defun message-position-point ()
3102   "Move point to where the user probably wants to find it."
3103   (message-narrow-to-headers)
3104   (cond
3105    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3106     (search-backward ":" )
3107     (widen)
3108     (forward-char 1)
3109     (if (= (following-char) ? )
3110         (forward-char 1)
3111       (insert " ")))
3112    (t
3113     (goto-char (point-max))
3114     (widen)
3115     (forward-line 1)
3116     (unless (looking-at "$")
3117       (forward-line 2)))
3118    (sit-for 0)))
3119
3120 (defun message-buffer-name (type &optional to group)
3121   "Return a new (unique) buffer name based on TYPE and TO."
3122   (cond
3123    ;; Check whether `message-generate-new-buffers' is a function,
3124    ;; and if so, call it.
3125    ((message-functionp message-generate-new-buffers)
3126     (funcall message-generate-new-buffers type to group))
3127    ;; Generate a new buffer name The Message Way.
3128    (message-generate-new-buffers
3129     (generate-new-buffer-name
3130      (concat "*" type
3131              (if to
3132                  (concat " to "
3133                          (or (car (mail-extract-address-components to))
3134                              to) "")
3135                "")
3136              (if (and group (not (string= group ""))) (concat " on " group) "")
3137              "*")))
3138    ;; Use standard name.
3139    (t
3140     (format "*%s message*" type))))
3141
3142 (defun message-pop-to-buffer (name)
3143   "Pop to buffer NAME, and warn if it already exists and is modified."
3144   (let ((buffer (get-buffer name)))
3145     (if (and buffer
3146              (buffer-name buffer))
3147         (progn
3148           (set-buffer (pop-to-buffer buffer))
3149           (when (and (buffer-modified-p)
3150                      (not (y-or-n-p
3151                            "Message already being composed; erase? ")))
3152             (error "Message being composed")))
3153       (set-buffer (pop-to-buffer name)))
3154     (erase-buffer)
3155     (message-mode)))
3156
3157 (defun message-do-send-housekeeping ()
3158   "Kill old message buffers."
3159   ;; We might have sent this buffer already.  Delete it from the
3160   ;; list of buffers.
3161   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3162   (while (and message-max-buffers
3163               message-buffer-list
3164               (>= (length message-buffer-list) message-max-buffers))
3165     ;; Kill the oldest buffer -- unless it has been changed.
3166     (let ((buffer (pop message-buffer-list)))
3167       (when (and (buffer-name buffer)
3168                  (not (buffer-modified-p buffer)))
3169         (kill-buffer buffer))))
3170   ;; Rename the buffer.
3171   (if message-send-rename-function
3172       (funcall message-send-rename-function)
3173     (when (string-match "\\`\\*" (buffer-name))
3174       (rename-buffer
3175        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3176   ;; Push the current buffer onto the list.
3177   (when message-max-buffers
3178     (setq message-buffer-list
3179           (nconc message-buffer-list (list (current-buffer))))))
3180
3181 (defvar mc-modes-alist)
3182 (defun message-setup (headers &optional replybuffer actions)
3183   (when (and (boundp 'mc-modes-alist)
3184              (not (assq 'message-mode mc-modes-alist)))
3185     (push '(message-mode (encrypt . mc-encrypt-message)
3186                          (sign . mc-sign-message))
3187           mc-modes-alist))
3188   (when actions
3189     (setq message-send-actions actions))
3190   (setq message-reply-buffer replybuffer)
3191   (goto-char (point-min))
3192   ;; Insert all the headers.
3193   (mail-header-format
3194    (let ((h headers)
3195          (alist message-header-format-alist))
3196      (while h
3197        (unless (assq (caar h) message-header-format-alist)
3198          (push (list (caar h)) alist))
3199        (pop h))
3200      alist)
3201    headers)
3202   (delete-region (point) (progn (forward-line -1) (point)))
3203   (when message-default-headers
3204     (insert message-default-headers)
3205     (or (bolp) (insert ?\n)))
3206   (put-text-property
3207    (point)
3208    (progn
3209      (insert mail-header-separator "\n")
3210      (1- (point)))
3211    'read-only nil)
3212   (forward-line -1)
3213   (when (message-news-p)
3214     (when message-default-news-headers
3215       (insert message-default-news-headers)
3216       (or (bolp) (insert ?\n)))
3217     (when message-generate-headers-first
3218       (message-generate-headers
3219        (delq 'Lines
3220              (delq 'Subject
3221                    (copy-sequence message-required-news-headers))))))
3222   (when (message-mail-p)
3223     (when message-default-mail-headers
3224       (insert message-default-mail-headers)
3225       (or (bolp) (insert ?\n)))
3226     (when message-generate-headers-first
3227       (message-generate-headers
3228        (delq 'Lines
3229              (delq 'Subject
3230                    (copy-sequence message-required-mail-headers))))))
3231   (run-hooks 'message-signature-setup-hook)
3232   (message-insert-signature)
3233   (save-restriction
3234     (message-narrow-to-headers)
3235     (run-hooks 'message-header-setup-hook))
3236   (set-buffer-modified-p nil)
3237   (setq buffer-undo-list nil)
3238   (run-hooks 'message-setup-hook)
3239   (message-position-point)
3240   (undo-boundary))
3241
3242 (defun message-set-auto-save-file-name ()
3243   "Associate the message buffer with a file in the drafts directory."
3244   (when message-autosave-directory
3245     (if (gnus-alive-p)
3246         (setq message-draft-article
3247               (nndraft-request-associate-buffer "drafts"))
3248       (setq buffer-file-name (expand-file-name "*message*"
3249                                                message-autosave-directory))
3250       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3251     (clear-visited-file-modtime)))
3252
3253 (defun message-disassociate-draft ()
3254   "Disassociate the message buffer from the drafts directory."
3255   (when message-draft-article
3256     (nndraft-request-expire-articles
3257      (list message-draft-article) "drafts" nil t)))
3258
3259 \f
3260
3261 ;;;
3262 ;;; Commands for interfacing with message
3263 ;;;
3264
3265 ;;;###autoload
3266 (defun message-mail (&optional to subject
3267                                other-headers continue switch-function
3268                                yank-action send-actions)
3269   "Start editing a mail message to be sent.
3270 OTHER-HEADERS is an alist of header/value pairs."
3271   (interactive)
3272   (let ((message-this-is-mail t))
3273     (message-pop-to-buffer (message-buffer-name "mail" to))
3274     (message-setup
3275      (nconc
3276       `((To . ,(or to "")) (Subject . ,(or subject "")))
3277       (when other-headers other-headers)))))
3278
3279 ;;;###autoload
3280 (defun message-news (&optional newsgroups subject)
3281   "Start editing a news article to be sent."
3282   (interactive)
3283   (let ((message-this-is-news t))
3284     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3285     (message-setup `((Newsgroups . ,(or newsgroups ""))
3286                      (Subject . ,(or subject ""))))))
3287
3288 ;;;###autoload
3289 (defun message-reply (&optional to-address wide)
3290   "Start editing a reply to the article in the current buffer."
3291   (interactive)
3292   (let ((cur (current-buffer))
3293         from subject date reply-to to cc
3294         references message-id follow-to
3295         (inhibit-point-motion-hooks t)
3296         mct never-mct gnus-warning)
3297     (save-restriction
3298       (message-narrow-to-head)
3299       ;; Allow customizations to have their say.
3300       (if (not wide)
3301           ;; This is a regular reply.
3302           (if (message-functionp message-reply-to-function)
3303               (setq follow-to (funcall message-reply-to-function)))
3304         ;; This is a followup.
3305         (if (message-functionp message-wide-reply-to-function)
3306             (save-excursion
3307               (setq follow-to
3308                     (funcall message-wide-reply-to-function)))))
3309       ;; Find all relevant headers we need.
3310       (setq from (message-fetch-field "from")
3311             date (message-fetch-field "date")
3312             subject (or (message-fetch-field "subject") "none")
3313             to (message-fetch-field "to")
3314             cc (message-fetch-field "cc")
3315             mct (message-fetch-field "mail-copies-to")
3316             reply-to (message-fetch-field "reply-to")
3317             references (message-fetch-field "references")
3318             message-id (message-fetch-field "message-id" t))
3319       ;; Remove any (buggy) Re:'s that are present and make a
3320       ;; proper one.
3321       (when (string-match message-subject-re-regexp subject)
3322         (setq subject (substring subject (match-end 0))))
3323       (setq subject (concat "Re: " subject))
3324
3325       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3326                  (string-match "<[^>]+>" gnus-warning))
3327         (setq message-id (match-string 0 gnus-warning)))
3328
3329       ;; Handle special values of Mail-Copies-To.
3330       (when mct
3331         (cond ((equal (downcase mct) "never")
3332                (setq never-mct t)
3333                (setq mct nil))
3334               ((equal (downcase mct) "always")
3335                (setq mct (or reply-to from)))))
3336
3337       (unless follow-to
3338         (if (or (not wide)
3339                 to-address)
3340             (progn
3341               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3342               (when (and wide mct)
3343                 (push (cons 'Cc mct) follow-to)))
3344           (let (ccalist)
3345             (save-excursion
3346               (message-set-work-buffer)
3347               (unless never-mct
3348                 (insert (or reply-to from "")))
3349               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3350               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3351               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3352               (goto-char (point-min))
3353               (while (re-search-forward "[ \t]+" nil t)
3354                 (replace-match " " t t))
3355               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3356               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3357                         (erase-buffer)))
3358               (goto-char (point-min))
3359               ;; Perhaps Mail-Copies-To: never removed the only address?
3360               (when (eobp)
3361                 (insert (or reply-to from "")))
3362               (setq ccalist
3363                     (mapcar
3364                      (lambda (addr)
3365                        (cons (mail-strip-quoted-names addr) addr))
3366                      (message-tokenize-header (buffer-string))))
3367               (let ((s ccalist))
3368                 (while s
3369                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3370             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3371             (when ccalist
3372               (let ((ccs (cons 'Cc (mapconcat
3373                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3374                 (when (string-match "^ +" (cdr ccs))
3375                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3376                 (push ccs follow-to))))))
3377       (widen))
3378
3379     (message-pop-to-buffer (message-buffer-name
3380                             (if wide "wide reply" "reply") from
3381                             (if wide to-address nil)))
3382
3383     (setq message-reply-headers
3384           (vector 0 subject from date message-id references 0 0 ""))
3385
3386     (message-setup
3387      `((Subject . ,subject)
3388        ,@follow-to
3389        ,@(if (or references message-id)
3390              `((References . ,(concat (or references "") (and references " ")
3391                                       (or message-id ""))))
3392            nil))
3393      cur)))
3394
3395 ;;;###autoload
3396 (defun message-wide-reply (&optional to-address)
3397   "Make a \"wide\" reply to the message in the current buffer."
3398   (interactive)
3399   (message-reply to-address t))
3400
3401 ;;;###autoload
3402 (defun message-followup (&optional to-newsgroups)
3403   "Follow up to the message in the current buffer.
3404 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3405   (interactive)
3406   (let ((cur (current-buffer))
3407         from subject date reply-to mct
3408         references message-id follow-to
3409         (inhibit-point-motion-hooks t)
3410         (message-this-is-news t)
3411         followup-to distribution newsgroups gnus-warning posted-to)
3412     (save-restriction
3413       (narrow-to-region
3414        (goto-char (point-min))
3415        (if (search-forward "\n\n" nil t)
3416            (1- (point))
3417          (point-max)))
3418       (when (message-functionp message-followup-to-function)
3419         (setq follow-to
3420               (funcall message-followup-to-function)))
3421       (setq from (message-fetch-field "from")
3422             date (message-fetch-field "date")
3423             subject (or (message-fetch-field "subject") "none")
3424             references (message-fetch-field "references")
3425             message-id (message-fetch-field "message-id" t)
3426             followup-to (message-fetch-field "followup-to")
3427             newsgroups (message-fetch-field "newsgroups")
3428             posted-to (message-fetch-field "posted-to")
3429             reply-to (message-fetch-field "reply-to")
3430             distribution (message-fetch-field "distribution")
3431             mct (message-fetch-field "mail-copies-to"))
3432       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3433                  (string-match "<[^>]+>" gnus-warning))
3434         (setq message-id (match-string 0 gnus-warning)))
3435       ;; Remove bogus distribution.
3436       (when (and (stringp distribution)
3437                  (let ((case-fold-search t))
3438                    (string-match "world" distribution)))
3439         (setq distribution nil))
3440       ;; Remove any (buggy) Re:'s that are present and make a
3441       ;; proper one.
3442       (when (string-match message-subject-re-regexp subject)
3443         (setq subject (substring subject (match-end 0))))
3444       (setq subject (concat "Re: " subject))
3445       (widen))
3446
3447     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3448
3449     (message-setup
3450      `((Subject . ,subject)
3451        ,@(cond
3452           (to-newsgroups
3453            (list (cons 'Newsgroups to-newsgroups)))
3454           (follow-to follow-to)
3455           ((and followup-to message-use-followup-to)
3456            (list
3457             (cond
3458              ((equal (downcase followup-to) "poster")
3459               (if (or (eq message-use-followup-to 'use)
3460                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3461 You should normally obey the Followup-To: header.
3462
3463 `Followup-To: poster' sends your response via e-mail instead of news.
3464
3465 A typical situation where `Followup-To: poster' is used is when the poster
3466 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3467                   (progn
3468                     (setq message-this-is-news nil)
3469                     (cons 'To (or reply-to from "")))
3470                 (cons 'Newsgroups newsgroups)))
3471              (t
3472               (if (or (equal followup-to newsgroups)
3473                       (not (eq message-use-followup-to 'ask))
3474                       (message-y-or-n-p
3475                        (concat "Obey Followup-To: " followup-to "? ") t "\
3476 You should normally obey the Followup-To: header.
3477
3478         `Followup-To: " followup-to "'
3479 directs your response to " (if (string-match "," followup-to)
3480                                "the specified newsgroups"
3481                              "that newsgroup only") ".
3482
3483 If a message is posted to several newsgroups, Followup-To is often
3484 used to direct the following discussion to one newsgroup only,
3485 because discussions that are spread over several newsgroup tend to
3486 be fragmented and very difficult to follow.
3487
3488 Also, some source/announcement newsgroups are not indented for discussion;
3489 responses here are directed to other newsgroups."))
3490                   (cons 'Newsgroups followup-to)
3491                 (cons 'Newsgroups newsgroups))))))
3492           (posted-to
3493            `((Newsgroups . ,posted-to)))
3494           (t
3495            `((Newsgroups . ,newsgroups))))
3496        ,@(and distribution (list (cons 'Distribution distribution)))
3497        ,@(if (or references message-id)
3498              `((References . ,(concat (or references "") (and references " ")
3499                                       (or message-id "")))))
3500        ,@(when (and mct
3501                     (not (equal (downcase mct) "never")))
3502            (list (cons 'Cc (if (equal (downcase mct) "always")
3503                                (or reply-to from "")
3504                              mct)))))
3505
3506      cur)
3507
3508     (setq message-reply-headers
3509           (vector 0 subject from date message-id references 0 0 ""))))
3510
3511
3512 ;;;###autoload
3513 (defun message-cancel-news ()
3514   "Cancel an article you posted."
3515   (interactive)
3516   (unless (message-news-p)
3517     (error "This is not a news article; canceling is impossible"))
3518   (when (yes-or-no-p "Do you really want to cancel this article? ")
3519     (let (from newsgroups message-id distribution buf sender)
3520       (save-excursion
3521         ;; Get header info. from original article.
3522         (save-restriction
3523           (message-narrow-to-head)
3524           (setq from (message-fetch-field "from")
3525                 sender (message-fetch-field "sender")
3526                 newsgroups (message-fetch-field "newsgroups")
3527                 message-id (message-fetch-field "message-id" t)
3528                 distribution (message-fetch-field "distribution")))
3529         ;; Make sure that this article was written by the user.
3530         (unless (or (and sender
3531                          (string-equal
3532                           (downcase sender)
3533                           (downcase (message-make-sender))))
3534                     (string-equal
3535                      (downcase (cadr (mail-extract-address-components from)))
3536                      (downcase (cadr (mail-extract-address-components
3537                                       (message-make-from))))))
3538           (error "This article is not yours"))
3539         ;; Make control message.
3540         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3541         (buffer-disable-undo (current-buffer))
3542         (erase-buffer)
3543         (insert "Newsgroups: " newsgroups "\n"
3544                 "From: " (message-make-from) "\n"
3545                 "Subject: cmsg cancel " message-id "\n"
3546                 "Control: cancel " message-id "\n"
3547                 (if distribution
3548                     (concat "Distribution: " distribution "\n")
3549                   "")
3550                 mail-header-separator "\n"
3551                 message-cancel-message)
3552         (message "Canceling your article...")
3553         (if (let ((message-syntax-checks
3554                    'dont-check-for-anything-just-trust-me))
3555               (funcall message-send-news-function))
3556             (message "Canceling your article...done"))
3557         (kill-buffer buf)))))
3558
3559 ;;;###autoload
3560 (defun message-supersede ()
3561   "Start composing a message to supersede the current message.
3562 This is done simply by taking the old article and adding a Supersedes
3563 header line with the old Message-ID."
3564   (interactive)
3565   (let ((cur (current-buffer))
3566         (sender (message-fetch-field "sender"))
3567         (from (message-fetch-field "from")))
3568     ;; Check whether the user owns the article that is to be superseded.
3569     (unless (or (and sender
3570                      (string-equal
3571                       (downcase sender)
3572                       (downcase (message-make-sender))))
3573                 (string-equal
3574                  (downcase (cadr (mail-extract-address-components from)))
3575                  (downcase (cadr (mail-extract-address-components
3576                                   (message-make-from))))))
3577       (error "This article is not yours"))
3578     ;; Get a normal message buffer.
3579     (message-pop-to-buffer (message-buffer-name "supersede"))
3580     (insert-buffer-substring cur)
3581     (message-narrow-to-head)
3582     ;; Remove unwanted headers.
3583     (when message-ignored-supersedes-headers
3584       (message-remove-header message-ignored-supersedes-headers t))
3585     (goto-char (point-min))
3586     (if (not (re-search-forward "^Message-ID: " nil t))
3587         (error "No Message-ID in this article")
3588       (replace-match "Supersedes: " t t))
3589     (goto-char (point-max))
3590     (insert mail-header-separator)
3591     (widen)
3592     (forward-line 1)))
3593
3594 ;;;###autoload
3595 (defun message-recover ()
3596   "Reread contents of current buffer from its last auto-save file."
3597   (interactive)
3598   (let ((file-name (make-auto-save-file-name)))
3599     (cond ((save-window-excursion
3600              (if (not (eq system-type 'vax-vms))
3601                  (with-output-to-temp-buffer "*Directory*"
3602                    (buffer-disable-undo standard-output)
3603                    (let ((default-directory "/"))
3604                      (call-process
3605                       "ls" nil standard-output nil "-l" file-name))))
3606              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3607            (let ((buffer-read-only nil))
3608              (erase-buffer)
3609              (insert-file-contents file-name nil)))
3610           (t (error "message-recover cancelled")))))
3611
3612 ;;; Washing Subject:
3613
3614 (defun message-wash-subject (subject)
3615   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3616   (with-temp-buffer
3617     (insert-string subject)
3618     (goto-char (point-min))
3619     ;; strip Re/Fwd stuff off the beginning
3620     (while (re-search-forward
3621             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3622       (replace-match ""))
3623
3624     ;; and gnus-style forwards [foo@bar.com] subject
3625     (goto-char (point-min))
3626     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
3627       (replace-match ""))
3628
3629     ;; and off the end
3630     (goto-char (point-max))
3631     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
3632       (replace-match ""))
3633
3634     ;; and finally, any whitespace that was left-over
3635     (goto-char (point-min))
3636     (while (re-search-forward "^[ \t]+" nil t)
3637       (replace-match ""))
3638     (goto-char (point-max))
3639     (while (re-search-backward "[ \t]+$" nil t)
3640       (replace-match ""))
3641
3642     (buffer-string)))
3643     
3644 ;;; Forwarding messages.
3645
3646 (defun message-forward-subject-author-subject (subject)
3647   "Generate a subject for a forwarded message.
3648 The form is: [Source] Subject, where if the original message was mail,
3649 Source is the sender, and if the original message was news, Source is
3650 the list of newsgroups is was posted to."
3651   (concat "["
3652           (or (message-fetch-field
3653                (if (message-news-p) "newsgroups" "from"))
3654               "(nowhere)")
3655           "] " subject))
3656
3657 (defun message-forward-subject-fwd (subject)
3658   "Generate a subject for a forwarded message.
3659 The form is: Fwd: Subject, where Subject is the original subject of
3660 the message."
3661   (concat "Fwd: " subject))
3662
3663 (defun message-make-forward-subject ()
3664   "Return a Subject header suitable for the message in the current buffer."
3665   (save-excursion
3666     (save-restriction
3667       (current-buffer)
3668       (message-narrow-to-head)
3669       (let ((funcs message-make-forward-subject-function)
3670             (subject (if message-wash-forwarded-subjects
3671                          (message-wash-subject
3672                           (or (message-fetch-field "Subject") ""))
3673                        (or (message-fetch-field "Subject") ""))))
3674         ;; Make sure funcs is a list.
3675         (and funcs
3676              (not (listp funcs))
3677              (setq funcs (list funcs)))
3678         ;; Apply funcs in order, passing subject generated by previous
3679         ;; func to the next one.
3680         (while funcs
3681           (when (message-functionp (car funcs))
3682             (setq subject (funcall (car funcs) subject)))
3683           (setq funcs (cdr funcs)))
3684         subject))))
3685
3686 ;;;###autoload
3687 (defun message-forward (&optional news)
3688   "Forward the current message via mail.
3689 Optional NEWS will use news to forward instead of mail."
3690   (interactive "P")
3691   (let ((cur (current-buffer))
3692         (subject (message-make-forward-subject))
3693         art-beg)
3694     (if news (message-news nil subject) (message-mail nil subject))
3695     ;; Put point where we want it before inserting the forwarded
3696     ;; message.
3697     (if message-signature-before-forwarded-message
3698         (goto-char (point-max))
3699       (message-goto-body))
3700     ;; Make sure we're at the start of the line.
3701     (unless (eolp)
3702       (insert "\n"))
3703     ;; Narrow to the area we are to insert.
3704     (narrow-to-region (point) (point))
3705     ;; Insert the separators and the forwarded buffer.
3706     (insert message-forward-start-separator)
3707     (setq art-beg (point))
3708     (insert-buffer-substring cur)
3709     (goto-char (point-max))
3710     (insert message-forward-end-separator)
3711     (set-text-properties (point-min) (point-max) nil)
3712     ;; Remove all unwanted headers.
3713     (goto-char art-beg)
3714     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3715                                   (1- (point))
3716                                 (point)))
3717     (goto-char (point-min))
3718     (message-remove-header message-included-forward-headers t nil t)
3719     (widen)
3720     (message-position-point)))
3721
3722 ;;;###autoload
3723 (defun message-resend (address)
3724   "Resend the current article to ADDRESS."
3725   (interactive "sResend message to: ")
3726   (message "Resending message to %s..." address)
3727   (save-excursion
3728     (let ((cur (current-buffer))
3729           beg)
3730       ;; We first set up a normal mail buffer.
3731       (set-buffer (get-buffer-create " *message resend*"))
3732       (buffer-disable-undo (current-buffer))
3733       (erase-buffer)
3734       (message-setup `((To . ,address)))
3735       ;; Insert our usual headers.
3736       (message-generate-headers '(From Date To))
3737       (message-narrow-to-headers)
3738       ;; Rename them all to "Resent-*".
3739       (while (re-search-forward "^[A-Za-z]" nil t)
3740         (forward-char -1)
3741         (insert "Resent-"))
3742       (widen)
3743       (forward-line)
3744       (delete-region (point) (point-max))
3745       (setq beg (point))
3746       ;; Insert the message to be resent.
3747       (insert-buffer-substring cur)
3748       (goto-char (point-min))
3749       (search-forward "\n\n")
3750       (forward-char -1)
3751       (save-restriction
3752         (narrow-to-region beg (point))
3753         (message-remove-header message-ignored-resent-headers t)
3754         (goto-char (point-max)))
3755       (insert mail-header-separator)
3756       ;; Rename all old ("Also-")Resent headers.
3757       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3758         (beginning-of-line)
3759         (insert "Also-"))
3760       ;; Quote any "From " lines at the beginning.
3761       (goto-char beg)
3762       (when (looking-at "From ")
3763         (replace-match "X-From-Line: "))
3764       ;; Send it.
3765       (message-send-mail)
3766       (kill-buffer (current-buffer)))
3767     (message "Resending message to %s...done" address)))
3768
3769 ;;;###autoload
3770 (defun message-bounce ()
3771   "Re-mail the current message.
3772 This only makes sense if the current message is a bounce message than
3773 contains some mail you have written which has been bounced back to
3774 you."
3775   (interactive)
3776   (let ((cur (current-buffer))
3777         boundary)
3778     (message-pop-to-buffer (message-buffer-name "bounce"))
3779     (insert-buffer-substring cur)
3780     (undo-boundary)
3781     (message-narrow-to-head)
3782     (if (and (message-fetch-field "Mime-Version")
3783              (setq boundary (message-fetch-field "Content-Type")))
3784         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3785             (setq boundary (concat (match-string 1 boundary) " *\n"
3786                                    "Content-Type: message/rfc822"))
3787           (setq boundary nil)))
3788     (widen)
3789     (goto-char (point-min))
3790     (search-forward "\n\n" nil t)
3791     (or (and boundary
3792              (re-search-forward boundary nil t)
3793              (forward-line 2))
3794         (and (re-search-forward message-unsent-separator nil t)
3795              (forward-line 1))
3796         (re-search-forward "^Return-Path:.*\n" nil t))
3797     ;; We remove everything before the bounced mail.
3798     (delete-region
3799      (point-min)
3800      (if (re-search-forward "^[^ \n\t]+:" nil t)
3801          (match-beginning 0)
3802        (point)))
3803     (save-restriction
3804       (message-narrow-to-head)
3805       (message-remove-header message-ignored-bounced-headers t)
3806       (goto-char (point-max))
3807       (insert mail-header-separator))
3808     (message-position-point)))
3809
3810 ;;;
3811 ;;; Interactive entry points for new message buffers.
3812 ;;;
3813
3814 ;;;###autoload
3815 (defun message-mail-other-window (&optional to subject)
3816   "Like `message-mail' command, but display mail buffer in another window."
3817   (interactive)
3818   (let ((pop-up-windows t)
3819         (special-display-buffer-names nil)
3820         (special-display-regexps nil)
3821         (same-window-buffer-names nil)
3822         (same-window-regexps nil))
3823     (message-pop-to-buffer (message-buffer-name "mail" to)))
3824   (let ((message-this-is-mail t))
3825     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3826
3827 ;;;###autoload
3828 (defun message-mail-other-frame (&optional to subject)
3829   "Like `message-mail' command, but display mail buffer in another frame."
3830   (interactive)
3831   (let ((pop-up-frames t)
3832         (special-display-buffer-names nil)
3833         (special-display-regexps nil)
3834         (same-window-buffer-names nil)
3835         (same-window-regexps nil))
3836     (message-pop-to-buffer (message-buffer-name "mail" to)))
3837   (let ((message-this-is-mail t))
3838     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
3839
3840 ;;;###autoload
3841 (defun message-news-other-window (&optional newsgroups subject)
3842   "Start editing a news article to be sent."
3843   (interactive)
3844   (let ((pop-up-windows t)
3845         (special-display-buffer-names nil)
3846         (special-display-regexps nil)
3847         (same-window-buffer-names nil)
3848         (same-window-regexps nil))
3849     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3850   (let ((message-this-is-news t))
3851     (message-setup `((Newsgroups . ,(or newsgroups ""))
3852                      (Subject . ,(or subject ""))))))
3853
3854 ;;;###autoload
3855 (defun message-news-other-frame (&optional newsgroups subject)
3856   "Start editing a news article to be sent."
3857   (interactive)
3858   (let ((pop-up-frames t)
3859         (special-display-buffer-names nil)
3860         (special-display-regexps nil)
3861         (same-window-buffer-names nil)
3862         (same-window-regexps nil))
3863     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3864   (let ((message-this-is-news t))
3865     (message-setup `((Newsgroups . ,(or newsgroups ""))
3866                      (Subject . ,(or subject ""))))))
3867
3868 ;;; underline.el
3869
3870 ;; This code should be moved to underline.el (from which it is stolen).
3871
3872 ;;;###autoload
3873 (defun bold-region (start end)
3874   "Bold all nonblank characters in the region.
3875 Works by overstriking characters.
3876 Called from program, takes two arguments START and END
3877 which specify the range to operate on."
3878   (interactive "r")
3879   (save-excursion
3880     (let ((end1 (make-marker)))
3881       (move-marker end1 (max start end))
3882       (goto-char (min start end))
3883       (while (< (point) end1)
3884         (or (looking-at "[_\^@- ]")
3885             (insert (following-char) "\b"))
3886         (forward-char 1)))))
3887
3888 ;;;###autoload
3889 (defun unbold-region (start end)
3890   "Remove all boldness (overstruck characters) in the region.
3891 Called from program, takes two arguments START and END
3892 which specify the range to operate on."
3893   (interactive "r")
3894   (save-excursion
3895     (let ((end1 (make-marker)))
3896       (move-marker end1 (max start end))
3897       (goto-char (min start end))
3898       (while (re-search-forward "\b" end1 t)
3899         (if (eq (following-char) (char-after (- (point) 2)))
3900             (delete-char -2))))))
3901
3902 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3903
3904 ;; Support for toolbar
3905 (when (string-match "XEmacs\\|Lucid" emacs-version)
3906   (require 'messagexmas))
3907
3908 ;;; Group name completion.
3909
3910 (defvar message-newgroups-header-regexp
3911   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3912   "Regexp that match headers that lists groups.")
3913
3914 (defun message-tab ()
3915   "Expand group names in Newsgroups and Followup-To headers.
3916 Do a `tab-to-tab-stop' if not in those headers."
3917   (interactive)
3918   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3919         (mail-abbrev-in-expansion-header-p))
3920       (message-expand-group)
3921     (tab-to-tab-stop)))
3922
3923 (defvar gnus-active-hashtb)
3924 (defun message-expand-group ()
3925   "Expand the group name under point."
3926   (let* ((b (save-excursion
3927               (save-restriction
3928                 (narrow-to-region
3929                  (save-excursion
3930                    (beginning-of-line)
3931                    (skip-chars-forward "^:")
3932                    (1+ (point)))
3933                  (point))
3934                 (skip-chars-backward "^, \t\n") (point))))
3935          (completion-ignore-case t)
3936          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
3937                                             (point))))
3938          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3939          (completions (all-completions string hashtb))
3940          comp)
3941     (delete-region b (point))
3942     (cond
3943      ((= (length completions) 1)
3944       (if (string= (car completions) string)
3945           (progn
3946             (insert string)
3947             (message "Only matching group"))
3948         (insert (car completions))))
3949      ((and (setq comp (try-completion string hashtb))
3950            (not (string= comp string)))
3951       (insert comp))
3952      (t
3953       (insert string)
3954       (if (not comp)
3955           (message "No matching groups")
3956         (save-selected-window
3957           (pop-to-buffer "*Completions*")
3958           (buffer-disable-undo (current-buffer))
3959           (let ((buffer-read-only nil))
3960             (erase-buffer)
3961             (let ((standard-output (current-buffer)))
3962               (display-completion-list (sort completions 'string<)))
3963             (goto-char (point-min))
3964             (delete-region (point) (progn (forward-line 3) (point))))))))))
3965
3966 ;;; Help stuff.
3967
3968 (defun message-talkative-question (ask question show &rest text)
3969   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3970 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3971 The following arguments may contain lists of values."
3972   (if (and show
3973            (setq text (message-flatten-list text)))
3974       (save-window-excursion
3975         (save-excursion
3976           (with-output-to-temp-buffer " *MESSAGE information message*"
3977             (set-buffer " *MESSAGE information message*")
3978             (mapcar 'princ text)
3979             (goto-char (point-min))))
3980         (funcall ask question))
3981     (funcall ask question)))
3982
3983 (defun message-flatten-list (list)
3984   "Return a new, flat list that contains all elements of LIST.
3985
3986 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3987 => (1 2 3 4 5 6 7)"
3988   (cond ((consp list)
3989          (apply 'append (mapcar 'message-flatten-list list)))
3990         (list
3991          (list list))))
3992
3993 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3994   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3995 Then clone the local variables and values from the old buffer to the
3996 new one, cloning only the locals having a substring matching the
3997 regexp varstr."
3998   (let ((oldbuf (current-buffer)))
3999     (save-excursion
4000       (set-buffer (generate-new-buffer name))
4001       (message-clone-locals oldbuf)
4002       (current-buffer))))
4003
4004 (defun message-clone-locals (buffer)
4005   "Clone the local variables from BUFFER to the current buffer."
4006   (let ((locals (save-excursion
4007                   (set-buffer buffer)
4008                   (buffer-local-variables)))
4009         (regexp "^gnus\\|^nn\\|^message"))
4010     (mapcar
4011      (lambda (local)
4012        (when (and (consp local)
4013                   (car local)
4014                   (string-match regexp (symbol-name (car local))))
4015          (ignore-errors
4016            (set (make-local-variable (car local))
4017                 (cdr local)))))
4018      locals)))
4019
4020 ;;; Miscellaneous functions
4021
4022 ;; stolen (and renamed) from nnheader.el
4023 (defun message-replace-chars-in-string (string from to)
4024   "Replace characters in STRING from FROM to TO."
4025   (let ((string (substring string 0))   ;Copy string.
4026         (len (length string))
4027         (idx 0))
4028     ;; Replace all occurrences of FROM with TO.
4029     (while (< idx len)
4030       (when (= (aref string idx) from)
4031         (aset string idx to))
4032       (setq idx (1+ idx)))
4033     string))
4034
4035 ;;;
4036 ;;; MIME functions
4037 ;;;
4038
4039 (defun message-encode-message-body ()
4040   "Examine the message body, encode it, and add the requisite headers."
4041   (when (featurep 'mule)
4042     (save-excursion
4043       (save-restriction
4044         (message-narrow-to-headers)
4045         (message-remove-header
4046          "^Content-Transfer-Encoding:\\|^Content-Type:\\|^Mime-Version:" t)
4047         (goto-char (point-max))
4048         (widen)
4049         (narrow-to-region (point) (point-max))
4050         (let* ((charset (mm-encode-body))
4051                (encoding (mm-body-encoding)))
4052           (when (consp charset)
4053             (error "Can't encode messages with multiple charsets (yet)"))
4054           (widen)
4055           (message-narrow-to-headers)
4056           (goto-char (point-max))
4057           (setq charset (or charset (mm-mule-charset-to-mime-charset 'ascii)))
4058           ;; We don't insert MIME headers if they only say the default.
4059           (unless (and (eq charset 'ascii)
4060                        (eq encoding '7bit))
4061             (mm-insert-rfc822-headers charset encoding))
4062           (mm-encode-body))))))
4063
4064 (run-hooks 'message-load-hook)
4065
4066 (provide 'message)
4067
4068 ;;; message.el ends here