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