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