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