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