*** 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 `message-output' which saves in Unix
116 mailbox format."
117   :type '(radio (function-item message-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           (if (and message-fcc-handler-function
2145                    (not (eq message-fcc-handler-function 'rmail-output)))
2146               (funcall message-fcc-handler-function file)
2147             (if (and (file-readable-p file) (mail-file-babyl-p file))
2148                 (rmail-output file 1 nil t)
2149               (let ((mail-use-rfc822 t))
2150                 (rmail-output file 1 t t))))))
2151       
2152       (kill-buffer (current-buffer)))))
2153
2154 (defun message-output (filename)
2155   "Append this article to Unix/babyl mail file.."
2156   (if (and (file-readable-p filename)
2157            (mail-file-babyl-p filename))
2158       (gnus-output-to-rmail filename t)
2159     (gnus-output-to-mail filename t)))
2160
2161 (defun message-cleanup-headers ()
2162   "Do various automatic cleanups of the headers."
2163   ;; Remove empty lines in the header.
2164   (save-restriction
2165     (message-narrow-to-headers)
2166     (while (re-search-forward "^[ \t]*\n" nil t)
2167       (replace-match "" t t)))
2168
2169   ;; Correct Newsgroups and Followup-To headers: change sequence of
2170   ;; spaces to comma and eliminate spaces around commas.  Eliminate
2171   ;; embedded line breaks.
2172   (goto-char (point-min))
2173   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2174     (save-restriction
2175       (narrow-to-region
2176        (point)
2177        (if (re-search-forward "^[^ \t]" nil t)
2178            (match-beginning 0)
2179          (forward-line 1)
2180          (point)))
2181       (goto-char (point-min))
2182       (while (re-search-forward "\n[ \t]+" nil t)
2183         (replace-match " " t t))        ;No line breaks (too confusing)
2184       (goto-char (point-min))
2185       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2186         (replace-match "," t t))
2187       (goto-char (point-min))
2188       ;; Remove trailing commas.
2189       (when (re-search-forward ",+$" nil t)
2190         (replace-match "" t t)))))
2191
2192 (defun message-make-date ()
2193   "Make a valid data header."
2194   (let ((now (current-time)))
2195     (timezone-make-date-arpa-standard 
2196      (current-time-string now) (current-time-zone now))))
2197
2198 (defun message-make-message-id ()
2199   "Make a unique Message-ID."
2200   (concat "<" (message-unique-id) 
2201           (let ((psubject (save-excursion (message-fetch-field "subject"))))
2202             (if (and message-reply-headers
2203                      (mail-header-references message-reply-headers)
2204                      (mail-header-subject message-reply-headers)
2205                      psubject
2206                      (mail-header-subject message-reply-headers)
2207                      (not (string= 
2208                            (message-strip-subject-re
2209                             (mail-header-subject message-reply-headers))
2210                            (message-strip-subject-re psubject))))
2211                 "_-_" ""))
2212           "@" (message-make-fqdn) ">"))
2213
2214 (defvar message-unique-id-char nil)
2215
2216 ;; If you ever change this function, make sure the new version
2217 ;; cannot generate IDs that the old version could.
2218 ;; You might for example insert a "." somewhere (not next to another dot
2219 ;; or string boundary), or modify the "fsf" string.
2220 (defun message-unique-id ()
2221   ;; Don't use microseconds from (current-time), they may be unsupported.
2222   ;; Instead we use this randomly inited counter.
2223   (setq message-unique-id-char
2224         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2225            ;; (current-time) returns 16-bit ints,
2226            ;; and 2^16*25 just fits into 4 digits i base 36.
2227            (* 25 25)))
2228   (let ((tm (current-time)))
2229     (concat
2230      (if (memq system-type '(ms-dos emx vax-vms))
2231          (let ((user (downcase (user-login-name))))
2232            (while (string-match "[^a-z0-9_]" user)
2233              (aset user (match-beginning 0) ?_))
2234            user)
2235        (message-number-base36 (user-uid) -1))
2236      (message-number-base36 (+ (car   tm) 
2237                                (lsh (% message-unique-id-char 25) 16)) 4)
2238      (message-number-base36 (+ (nth 1 tm)
2239                                (lsh (/ message-unique-id-char 25) 16)) 4)
2240      ;; Append the newsreader name, because while the generated
2241      ;; ID is unique to this newsreader, other newsreaders might
2242      ;; otherwise generate the same ID via another algorithm.
2243      ".fsf")))
2244
2245 (defun message-number-base36 (num len)
2246   (if (if (< len 0) (<= num 0) (= len 0))
2247       ""
2248     (concat (message-number-base36 (/ num 36) (1- len))
2249             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2250                                   (% num 36))))))
2251
2252 (defun message-make-organization ()
2253   "Make an Organization header."
2254   (let* ((organization 
2255           (or (getenv "ORGANIZATION")
2256               (when message-user-organization
2257                 (if (message-functionp message-user-organization)
2258                     (funcall message-user-organization)
2259                   message-user-organization)))))
2260     (save-excursion
2261       (message-set-work-buffer)
2262       (cond ((stringp organization)
2263              (insert organization))
2264             ((and (eq t organization)
2265                   message-user-organization-file
2266                   (file-exists-p message-user-organization-file))
2267              (insert-file-contents message-user-organization-file)))
2268       (goto-char (point-min))
2269       (while (re-search-forward "[\t\n]+" nil t)
2270         (replace-match "" t t))
2271       (unless (zerop (buffer-size))
2272         (buffer-string)))))
2273
2274 (defun message-make-lines ()
2275   "Count the number of lines and return numeric string."
2276   (save-excursion
2277     (save-restriction
2278       (widen)
2279       (goto-char (point-min))
2280       (re-search-forward 
2281        (concat "^" (regexp-quote mail-header-separator) "$"))
2282       (forward-line 1)
2283       (int-to-string (count-lines (point) (point-max))))))
2284
2285 (defun message-make-in-reply-to ()
2286   "Return the In-Reply-To header for this message."
2287   (when message-reply-headers
2288     (let ((from (mail-header-from message-reply-headers))
2289           (date (mail-header-date message-reply-headers)))
2290       (when from
2291         (let ((stop-pos 
2292                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2293           (concat (if stop-pos (substring from 0 stop-pos) from)
2294                   "'s message of " 
2295                   (if (or (not date) (string= date ""))
2296                       "(unknown date)" date)))))))
2297
2298 (defun message-make-distribution ()
2299   "Make a Distribution header."
2300   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2301     (cond ((message-functionp message-distribution-function)
2302            (funcall message-distribution-function))
2303           (t orig-distribution))))
2304
2305 (defun message-make-expires ()
2306   "Return an Expires header based on `message-expires'."
2307   (let ((current (current-time))
2308         (future (* 1.0 message-expires 60 60 24)))
2309     ;; Add the future to current.
2310     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2311     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2312     ;; Return the date in the future in UT.
2313     (timezone-make-date-arpa-standard 
2314      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2315
2316 (defun message-make-path ()
2317   "Return uucp path."
2318   (let ((login-name (user-login-name)))
2319     (cond ((null message-user-path)
2320            (concat (system-name) "!" login-name))
2321           ((stringp message-user-path)
2322            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2323            (concat message-user-path "!" login-name))
2324           (t login-name))))
2325
2326 (defun message-make-from ()
2327   "Make a From header."
2328   (let* ((login (message-make-address))
2329          (fullname 
2330           (or (and (boundp 'user-full-name)
2331                    user-full-name)
2332               (user-full-name))))
2333     (when (string= fullname "&")
2334       (setq fullname (user-login-name)))
2335     (save-excursion
2336       (message-set-work-buffer)
2337       (cond 
2338        ((or (null message-from-style)
2339             (equal fullname ""))
2340         (insert login))
2341        ((or (eq message-from-style 'angles)
2342             (and (not (eq message-from-style 'parens))
2343                  ;; Use angles if no quoting is needed, or if parens would
2344                  ;; need quoting too.
2345                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2346                      (let ((tmp (concat fullname nil)))
2347                        (while (string-match "([^()]*)" tmp)
2348                          (aset tmp (match-beginning 0) ?-)
2349                          (aset tmp (1- (match-end 0)) ?-))
2350                        (string-match "[\\()]" tmp)))))
2351         (insert fullname)
2352         (goto-char (point-min))
2353         ;; Look for a character that cannot appear unquoted
2354         ;; according to RFC 822.
2355         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2356           ;; Quote fullname, escaping specials.
2357           (goto-char (point-min))
2358           (insert "\"")
2359           (while (re-search-forward "[\"\\]" nil 1)
2360             (replace-match "\\\\\\&" t))
2361           (insert "\""))
2362         (insert " <" login ">"))
2363        (t                               ; 'parens or default
2364         (insert login " (")
2365         (let ((fullname-start (point)))
2366           (insert fullname)
2367           (goto-char fullname-start)
2368           ;; RFC 822 says \ and nonmatching parentheses
2369           ;; must be escaped in comments.
2370           ;; Escape every instance of ()\ ...
2371           (while (re-search-forward "[()\\]" nil 1)
2372             (replace-match "\\\\\\&" t))
2373           ;; ... then undo escaping of matching parentheses,
2374           ;; including matching nested parentheses.
2375           (goto-char fullname-start)
2376           (while (re-search-forward 
2377                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2378                   nil 1)
2379             (replace-match "\\1(\\3)" t)
2380             (goto-char fullname-start)))
2381         (insert ")")))
2382       (buffer-string))))
2383
2384 (defun message-make-sender ()
2385   "Return the \"real\" user address.
2386 This function tries to ignore all user modifications, and 
2387 give as trustworthy answer as possible."
2388   (concat (user-login-name) "@" (system-name)))
2389
2390 (defun message-make-address ()
2391   "Make the address of the user."
2392   (or (message-user-mail-address)
2393       (concat (user-login-name) "@" (message-make-domain))))
2394
2395 (defun message-user-mail-address ()
2396   "Return the pertinent part of `user-mail-address'."
2397   (when user-mail-address
2398     (if (string-match " " user-mail-address)
2399         (nth 1 (mail-extract-address-components user-mail-address))
2400       user-mail-address)))
2401
2402 (defun message-make-fqdn ()
2403   "Return user's fully qualified domain name."
2404   (let ((system-name (system-name))
2405         (user-mail (message-user-mail-address)))
2406     (cond 
2407      ((string-match "[^.]\\.[^.]" system-name)
2408       ;; `system-name' returned the right result.
2409       system-name)
2410      ;; Try `mail-host-address'.
2411      ((and (boundp 'mail-host-address)
2412            (stringp mail-host-address)
2413            (string-match "\\." mail-host-address))
2414       mail-host-address)
2415      ;; We try `user-mail-address' as a backup.
2416      ((and (string-match "\\." user-mail)
2417            (string-match "@\\(.*\\)\\'" user-mail))
2418       (match-string 1 user-mail))
2419      ;; Default to this bogus thing.
2420      (t
2421       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2422
2423 (defun message-make-host-name ()
2424   "Return the name of the host."
2425   (let ((fqdn (message-make-fqdn)))
2426     (string-match "^[^.]+\\." fqdn)
2427     (substring fqdn 0 (1- (match-end 0)))))
2428
2429 (defun message-make-domain ()
2430   "Return the domain name."
2431   (or mail-host-address
2432       (message-make-fqdn)))
2433
2434 (defun message-generate-headers (headers)
2435   "Prepare article HEADERS.
2436 Headers already prepared in the buffer are not modified."
2437   (save-restriction
2438     (message-narrow-to-headers)
2439     (let* ((Date (message-make-date))
2440            (Message-ID (message-make-message-id))
2441            (Organization (message-make-organization))
2442            (From (message-make-from))
2443            (Path (message-make-path))
2444            (Subject nil)
2445            (Newsgroups nil)
2446            (In-Reply-To (message-make-in-reply-to))
2447            (To nil)
2448            (Distribution (message-make-distribution))
2449            (Lines (message-make-lines))
2450            (X-Newsreader message-newsreader)
2451            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2452                           message-mailer))
2453            (Expires (message-make-expires))
2454            (case-fold-search t)
2455            header value elem)
2456       ;; First we remove any old generated headers.
2457       (let ((headers message-deletable-headers))
2458         (while headers
2459           (goto-char (point-min))
2460           (and (re-search-forward 
2461                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2462                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2463                (message-delete-line))
2464           (pop headers)))
2465       ;; Go through all the required headers and see if they are in the
2466       ;; articles already.  If they are not, or are empty, they are
2467       ;; inserted automatically - except for Subject, Newsgroups and
2468       ;; Distribution. 
2469       (while headers
2470         (goto-char (point-min))
2471         (setq elem (pop headers))
2472         (if (consp elem)
2473             (if (eq (car elem) 'optional)
2474                 (setq header (cdr elem))
2475               (setq header (car elem)))
2476           (setq header elem))
2477         (when (or (not (re-search-forward 
2478                         (concat "^" (downcase (symbol-name header)) ":") 
2479                         nil t))
2480                   (progn
2481                     ;; The header was found.  We insert a space after the
2482                     ;; colon, if there is none.
2483                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2484                     ;; Find out whether the header is empty...
2485                     (looking-at "[ \t]*$")))
2486           ;; So we find out what value we should insert.
2487           (setq value
2488                 (cond 
2489                  ((and (consp elem) (eq (car elem) 'optional))
2490                   ;; This is an optional header.  If the cdr of this
2491                   ;; is something that is nil, then we do not insert
2492                   ;; this header.
2493                   (setq header (cdr elem))
2494                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2495                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2496                  ((consp elem)
2497                   ;; The element is a cons.  Either the cdr is a
2498                   ;; string to be inserted verbatim, or it is a
2499                   ;; function, and we insert the value returned from
2500                   ;; this function.
2501                   (or (and (stringp (cdr elem)) (cdr elem))
2502                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2503                  ((and (boundp header) (symbol-value header))
2504                   ;; The element is a symbol.  We insert the value
2505                   ;; of this symbol, if any.
2506                   (symbol-value header))
2507                  (t
2508                   ;; We couldn't generate a value for this header,
2509                   ;; so we just ask the user.
2510                   (read-from-minibuffer
2511                    (format "Empty header for %s; enter value: " header)))))
2512           ;; Finally insert the header.
2513           (when (and value 
2514                      (not (equal value "")))
2515             (save-excursion
2516               (if (bolp)
2517                   (progn
2518                     ;; This header didn't exist, so we insert it.
2519                     (goto-char (point-max))
2520                     (insert (symbol-name header) ": " value "\n")
2521                     (forward-line -1))
2522                 ;; The value of this header was empty, so we clear
2523                 ;; totally and insert the new value.
2524                 (delete-region (point) (message-point-at-eol))
2525                 (insert value))
2526               ;; Add the deletable property to the headers that require it.
2527               (and (memq header message-deletable-headers)
2528                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2529                    (add-text-properties 
2530                     (point) (match-end 0)
2531                     '(message-deletable t face italic) (current-buffer)))))))
2532       ;; Insert new Sender if the From is strange. 
2533       (let ((from (message-fetch-field "from"))
2534             (sender (message-fetch-field "sender"))
2535             (secure-sender (message-make-sender)))
2536         (when (and from 
2537                    (not (message-check-element 'sender))
2538                    (not (string=
2539                          (downcase
2540                           (cadr (mail-extract-address-components from)))
2541                          (downcase secure-sender)))
2542                    (or (null sender)
2543                        (not 
2544                         (string=
2545                          (downcase
2546                           (cadr (mail-extract-address-components sender)))
2547                          (downcase secure-sender)))))
2548           (goto-char (point-min))    
2549           ;; Rename any old Sender headers to Original-Sender.
2550           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
2551             (beginning-of-line)
2552             (insert "Original-")
2553             (beginning-of-line))
2554           (insert "Sender: " secure-sender "\n"))))))
2555
2556 (defun message-insert-courtesy-copy ()
2557   "Insert a courtesy message in mail copies of combined messages."
2558   (let (newsgroups)
2559     (save-excursion
2560       (save-restriction
2561         (message-narrow-to-headers)
2562         (when (setq newsgroups (message-fetch-field "newsgroups"))
2563           (goto-char (point-max))
2564           (insert "Posted-To: " newsgroups "\n")))
2565       (forward-line 1)
2566       (when message-courtesy-message
2567         (cond
2568          ((string-match "%s" message-courtesy-message)
2569           (insert (format message-courtesy-message newsgroups)))
2570          (t
2571           (insert message-courtesy-message)))))))
2572     
2573 ;;;
2574 ;;; Setting up a message buffer
2575 ;;;
2576
2577 (defun message-fill-address (header value)
2578   (save-restriction
2579     (narrow-to-region (point) (point))
2580     (insert (capitalize (symbol-name header))
2581             ": "
2582             (if (consp value) (car value) value)
2583             "\n")
2584     (narrow-to-region (point-min) (1- (point-max)))
2585     (let (quoted last)
2586       (goto-char (point-min))
2587       (while (not (eobp))
2588         (skip-chars-forward "^,\"" (point-max))
2589         (if (or (= (following-char) ?,)
2590                 (eobp))
2591             (when (not quoted)
2592               (if (and (> (current-column) 78)
2593                        last)
2594                   (progn
2595                     (save-excursion
2596                       (goto-char last)
2597                       (insert "\n\t"))
2598                     (setq last (1+ (point))))
2599                 (setq last (1+ (point)))))
2600           (setq quoted (not quoted)))
2601         (unless (eobp)
2602           (forward-char 1))))
2603     (goto-char (point-max))
2604     (widen)
2605     (forward-line 1)))
2606
2607 (defun message-fill-header (header value)
2608   (let ((begin (point))
2609         (fill-column 78)
2610         (fill-prefix "\t"))
2611     (insert (capitalize (symbol-name header))
2612             ": "
2613             (if (consp value) (car value) value)
2614             "\n")
2615     (save-restriction
2616       (narrow-to-region begin (point))
2617       (fill-region-as-paragraph begin (point))
2618       ;; Tapdance around looong Message-IDs.
2619       (forward-line -1)
2620       (when (looking-at "[ \t]*$")
2621         (message-delete-line))
2622       (goto-char begin)
2623       (re-search-forward ":" nil t)
2624       (when (looking-at "\n[ \t]+")
2625         (replace-match " " t t))
2626       (goto-char (point-max)))))
2627
2628 (defun message-position-point ()
2629   "Move point to where the user probably wants to find it."
2630   (message-narrow-to-headers)
2631   (cond 
2632    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2633     (search-backward ":" )
2634     (widen)
2635     (forward-char 1)
2636     (if (= (following-char) ? )
2637         (forward-char 1)
2638       (insert " ")))
2639    (t
2640     (goto-char (point-max))
2641     (widen)
2642     (forward-line 1)
2643     (unless (looking-at "$")
2644       (forward-line 2)))
2645    (sit-for 0)))
2646
2647 (defun message-buffer-name (type &optional to group)
2648   "Return a new (unique) buffer name based on TYPE and TO."
2649   (cond
2650    ;; Check whether `message-generate-new-buffers' is a function, 
2651    ;; and if so, call it.
2652    ((message-functionp message-generate-new-buffers)
2653     (funcall message-generate-new-buffers type to group))
2654    ;; Generate a new buffer name The Message Way.
2655    (message-generate-new-buffers
2656     (generate-new-buffer-name
2657      (concat "*" type
2658              (if to
2659                  (concat " to "
2660                          (or (car (mail-extract-address-components to))
2661                              to) "")
2662                "")
2663              (if (and group (not (string= group ""))) (concat " on " group) "")
2664              "*")))
2665    ;; Use standard name.
2666    (t
2667     (format "*%s message*" type))))
2668
2669 (defun message-pop-to-buffer (name)
2670   "Pop to buffer NAME, and warn if it already exists and is modified."
2671   (let ((buffer (get-buffer name)))
2672     (if (and buffer
2673              (buffer-name buffer))
2674         (progn
2675           (set-buffer (pop-to-buffer buffer))
2676           (when (and (buffer-modified-p)
2677                      (not (y-or-n-p
2678                            "Message already being composed; erase? ")))
2679             (error "Message being composed")))
2680       (set-buffer (pop-to-buffer name))))
2681   (erase-buffer)
2682   (message-mode))
2683
2684 (defun message-do-send-housekeeping ()
2685   "Kill old message buffers."
2686   ;; We might have sent this buffer already.  Delete it from the
2687   ;; list of buffers.
2688   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2689   (while (and message-max-buffers
2690               message-buffer-list
2691               (>= (length message-buffer-list) message-max-buffers))
2692     ;; Kill the oldest buffer -- unless it has been changed.
2693     (let ((buffer (pop message-buffer-list)))
2694       (when (and (buffer-name buffer)
2695                  (not (buffer-modified-p buffer)))
2696         (kill-buffer buffer))))
2697   ;; Rename the buffer.
2698   (if message-send-rename-function
2699       (funcall message-send-rename-function)
2700     (when (string-match "\\`\\*" (buffer-name))
2701       (rename-buffer 
2702        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2703   ;; Push the current buffer onto the list.
2704   (when message-max-buffers
2705     (setq message-buffer-list 
2706           (nconc message-buffer-list (list (current-buffer))))))
2707
2708 (defvar mc-modes-alist)
2709 (defun message-setup (headers &optional replybuffer actions)
2710   (when (and (boundp 'mc-modes-alist)
2711              (not (assq 'message-mode mc-modes-alist)))
2712     (push '(message-mode (encrypt . mc-encrypt-message)
2713                          (sign . mc-sign-message))
2714           mc-modes-alist))
2715   (when actions
2716     (setq message-send-actions actions))
2717   (setq message-reply-buffer replybuffer)
2718   (goto-char (point-min))
2719   ;; Insert all the headers.
2720   (mail-header-format 
2721    (let ((h headers)
2722          (alist message-header-format-alist))
2723      (while h
2724        (unless (assq (caar h) message-header-format-alist)
2725          (push (list (caar h)) alist))
2726        (pop h))
2727      alist)
2728    headers)
2729   (delete-region (point) (progn (forward-line -1) (point)))
2730   (when message-default-headers
2731     (insert message-default-headers))
2732   (put-text-property
2733    (point)
2734    (progn
2735      (insert mail-header-separator "\n")
2736      (1- (point)))
2737    'read-only nil)
2738   (forward-line -1)
2739   (when (message-news-p)
2740     (when message-default-news-headers
2741       (insert message-default-news-headers))
2742     (when message-generate-headers-first
2743       (message-generate-headers
2744        (delq 'Lines
2745              (delq 'Subject
2746                    (copy-sequence message-required-news-headers))))))
2747   (when (message-mail-p)
2748     (when message-default-mail-headers
2749       (insert message-default-mail-headers))
2750     (when message-generate-headers-first
2751       (message-generate-headers
2752        (delq 'Lines
2753              (delq 'Subject
2754                    (copy-sequence message-required-mail-headers))))))
2755   (run-hooks 'message-signature-setup-hook)
2756   (message-insert-signature)
2757   (message-set-auto-save-file-name)
2758   (save-restriction
2759     (message-narrow-to-headers)
2760     (run-hooks 'message-header-setup-hook))
2761   (set-buffer-modified-p nil)
2762   (run-hooks 'message-setup-hook)
2763   (message-position-point)
2764   (undo-boundary))
2765
2766 (defun message-set-auto-save-file-name ()
2767   "Associate the message buffer with a file in the drafts directory."
2768   (when message-autosave-directory
2769     (unless (file-exists-p message-autosave-directory)
2770       (make-directory message-autosave-directory t))
2771     (let ((name (make-temp-name
2772                  (concat (file-name-as-directory message-autosave-directory)
2773                          "msg."))))
2774       (setq buffer-auto-save-file-name
2775             (save-excursion
2776               (prog1
2777                   (progn
2778                     (set-buffer (get-buffer-create " *draft tmp*"))
2779                     (setq buffer-file-name name)
2780                     (make-auto-save-file-name))
2781                 (kill-buffer (current-buffer)))))
2782       (clear-visited-file-modtime))))
2783
2784 \f
2785
2786 ;;;
2787 ;;; Commands for interfacing with message
2788 ;;;
2789
2790 ;;;###autoload
2791 (defun message-mail (&optional to subject
2792                                other-headers continue switch-function
2793                                yank-action send-actions)
2794   "Start editing a mail message to be sent."
2795   (interactive)
2796   (let ((message-this-is-mail t))
2797     (message-pop-to-buffer (message-buffer-name "mail" to))
2798     (message-setup 
2799      (nconc
2800       `((To . ,(or to "")) (Subject . ,(or subject "")))
2801       (when other-headers (list other-headers))))))
2802
2803 ;;;###autoload
2804 (defun message-news (&optional newsgroups subject)
2805   "Start editing a news article to be sent."
2806   (interactive)
2807   (let ((message-this-is-news t))
2808     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2809     (message-setup `((Newsgroups . ,(or newsgroups "")) 
2810                      (Subject . ,(or subject ""))))))
2811
2812 ;;;###autoload
2813 (defun message-reply (&optional to-address wide ignore-reply-to)
2814   "Start editing a reply to the article in the current buffer."
2815   (interactive)
2816   (let ((cur (current-buffer))
2817         from subject date reply-to to cc
2818         references message-id follow-to 
2819         (inhibit-point-motion-hooks t)
2820         mct never-mct gnus-warning)
2821     (save-restriction
2822       (message-narrow-to-head)
2823       ;; Allow customizations to have their say.
2824       (if (not wide)
2825           ;; This is a regular reply.
2826           (if (message-functionp message-reply-to-function)
2827               (setq follow-to (funcall message-reply-to-function)))
2828         ;; This is a followup.
2829         (if (message-functionp message-wide-reply-to-function)
2830             (save-excursion
2831               (setq follow-to
2832                     (funcall message-wide-reply-to-function)))))
2833       ;; Find all relevant headers we need.
2834       (setq from (message-fetch-field "from")
2835             date (message-fetch-field "date") 
2836             subject (or (message-fetch-field "subject") "none")
2837             to (message-fetch-field "to")
2838             cc (message-fetch-field "cc")
2839             mct (message-fetch-field "mail-copies-to")
2840             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2841             references (message-fetch-field "references")
2842             message-id (message-fetch-field "message-id"))
2843       ;; Remove any (buggy) Re:'s that are present and make a
2844       ;; proper one.
2845       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2846         (setq subject (substring subject (match-end 0))))
2847       (setq subject (concat "Re: " subject))
2848
2849       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2850                  (string-match "<[^>]+>" gnus-warning))
2851         (setq message-id (match-string 0 gnus-warning)))
2852             
2853       ;; Handle special values of Mail-Copies-To.
2854       (when mct
2855         (cond ((equal (downcase mct) "never")
2856                (setq never-mct t)
2857                (setq mct nil))
2858               ((equal (downcase mct) "always")
2859                (setq mct (or reply-to from)))))
2860
2861       (unless follow-to
2862         (if (or (not wide)
2863                 to-address)
2864             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2865           (let (ccalist)
2866             (save-excursion
2867               (message-set-work-buffer)
2868               (unless never-mct
2869                 (insert (or reply-to from "")))
2870               (insert (if (bolp) "" ", ") (or to ""))
2871               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2872               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2873               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2874               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2875                         (erase-buffer)))
2876               (goto-char (point-min))
2877               (setq ccalist
2878                     (mapcar
2879                      (lambda (addr)
2880                        (cons (mail-strip-quoted-names addr) addr))
2881                      (message-tokenize-header (buffer-string))))
2882               (let ((s ccalist))
2883                 (while s
2884                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2885             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2886             (when ccalist
2887               (let ((ccs (cons 'Cc (mapconcat 
2888                                     (lambda (addr) (cdr addr)) ccalist ", "))))
2889                 (when (string-match "^ +" (cdr ccs))
2890                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
2891                 (push ccs follow-to))))))
2892       (widen))
2893
2894     (message-pop-to-buffer (message-buffer-name
2895                             (if wide "wide reply" "reply") from
2896                             (if wide to-address nil)))
2897
2898     (setq message-reply-headers
2899           (vector 0 subject from date message-id references 0 0 ""))
2900
2901     (message-setup
2902      `((Subject . ,subject)
2903        ,@follow-to 
2904        ,@(if (or references message-id)
2905              `((References . ,(concat (or references "") (and references " ")
2906                                       (or message-id ""))))
2907            nil))
2908      cur)))
2909
2910 ;;;###autoload
2911 (defun message-wide-reply (&optional to-address)
2912   "Make a \"wide\" reply to the message in the current buffer."
2913   (interactive)
2914   (message-reply to-address t))
2915
2916 ;;;###autoload
2917 (defun message-followup (&optional to-newsgroups)
2918   "Follow up to the message in the current buffer.
2919 If TO-NEWSGROUPS, use that as the new Newsgroups line."
2920   (interactive)
2921   (let ((cur (current-buffer))
2922         from subject date reply-to mct
2923         references message-id follow-to 
2924         (inhibit-point-motion-hooks t)
2925         (message-this-is-news t)
2926         followup-to distribution newsgroups gnus-warning)
2927     (save-restriction
2928       (narrow-to-region
2929        (goto-char (point-min))
2930        (if (search-forward "\n\n" nil t)
2931            (1- (point))
2932          (point-max)))
2933       (when (message-functionp message-followup-to-function)
2934         (setq follow-to
2935               (funcall message-followup-to-function)))
2936       (setq from (message-fetch-field "from")
2937             date (message-fetch-field "date") 
2938             subject (or (message-fetch-field "subject") "none")
2939             references (message-fetch-field "references")
2940             message-id (message-fetch-field "message-id")
2941             followup-to (message-fetch-field "followup-to")
2942             newsgroups (message-fetch-field "newsgroups")
2943             reply-to (message-fetch-field "reply-to")
2944             distribution (message-fetch-field "distribution")
2945             mct (message-fetch-field "mail-copies-to"))
2946       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2947                  (string-match "<[^>]+>" gnus-warning))
2948         (setq message-id (match-string 0 gnus-warning)))
2949       ;; Remove bogus distribution.
2950       (when (and (stringp distribution)
2951                  (let ((case-fold-search t))
2952                    (string-match "world" distribution)))
2953         (setq distribution nil))
2954       ;; Remove any (buggy) Re:'s that are present and make a
2955       ;; proper one.
2956       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2957         (setq subject (substring subject (match-end 0))))
2958       (setq subject (concat "Re: " subject))
2959       (widen))
2960
2961     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2962
2963     (message-setup
2964      `((Subject . ,subject)
2965        ,@(cond 
2966           (to-newsgroups
2967            (list (cons 'Newsgroups to-newsgroups)))
2968           (follow-to follow-to)
2969           ((and followup-to message-use-followup-to)
2970            (list
2971             (cond 
2972              ((equal (downcase followup-to) "poster")
2973               (if (or (eq message-use-followup-to 'use)
2974                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2975 You should normally obey the Followup-To: header.
2976
2977 `Followup-To: poster' sends your response via e-mail instead of news.
2978
2979 A typical situation where `Followup-To: poster' is used is when the poster
2980 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2981                   (cons 'To (or reply-to from ""))
2982                 (cons 'Newsgroups newsgroups)))
2983              (t
2984               (if (or (equal followup-to newsgroups)
2985                       (not (eq message-use-followup-to 'ask))
2986                       (message-y-or-n-p
2987                        (concat "Obey Followup-To: " followup-to "? ") t "\
2988 You should normally obey the Followup-To: header.
2989
2990         `Followup-To: " followup-to "'
2991 directs your response to " (if (string-match "," followup-to)
2992                                "the specified newsgroups"
2993                              "that newsgroup only") ".
2994
2995 If a message is posted to several newsgroups, Followup-To is often
2996 used to direct the following discussion to one newsgroup only,
2997 because discussions that are spread over several newsgroup tend to
2998 be fragmented and very difficult to follow.
2999
3000 Also, some source/announcement newsgroups are not indented for discussion;
3001 responses here are directed to other newsgroups."))
3002                   (cons 'Newsgroups followup-to)
3003                 (cons 'Newsgroups newsgroups))))))
3004           (t
3005            `((Newsgroups . ,newsgroups))))
3006        ,@(and distribution (list (cons 'Distribution distribution)))
3007        ,@(if (or references message-id)
3008              `((References . ,(concat (or references "") (and references " ")
3009                                       (or message-id "")))))
3010        ,@(when (and mct
3011                     (not (equal (downcase mct) "never")))
3012            (list (cons 'Cc (if (equal (downcase mct) "always")
3013                                (or reply-to from "")
3014                              mct)))))
3015
3016      cur)
3017
3018     (setq message-reply-headers
3019           (vector 0 subject from date message-id references 0 0 ""))))
3020
3021
3022 ;;;###autoload
3023 (defun message-cancel-news ()
3024   "Cancel an article you posted."
3025   (interactive)
3026   (unless (message-news-p)
3027     (error "This is not a news article; canceling is impossible"))
3028   (when (yes-or-no-p "Do you really want to cancel this article? ")
3029     (let (from newsgroups message-id distribution buf)
3030       (save-excursion
3031         ;; Get header info. from original article.
3032         (save-restriction
3033           (message-narrow-to-head)
3034           (setq from (message-fetch-field "from")
3035                 newsgroups (message-fetch-field "newsgroups")
3036                 message-id (message-fetch-field "message-id")
3037                 distribution (message-fetch-field "distribution")))
3038         ;; Make sure that this article was written by the user.
3039         (unless (string-equal
3040                  (downcase (cadr (mail-extract-address-components from)))
3041                  (downcase (message-make-address)))
3042           (error "This article is not yours"))
3043         ;; Make control message.
3044         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3045         (buffer-disable-undo (current-buffer))
3046         (erase-buffer)
3047         (insert "Newsgroups: " newsgroups "\n"
3048                 "From: " (message-make-from) "\n"
3049                 "Subject: cmsg cancel " message-id "\n"
3050                 "Control: cancel " message-id "\n"
3051                 (if distribution
3052                     (concat "Distribution: " distribution "\n")
3053                   "")
3054                 mail-header-separator "\n"
3055                 message-cancel-message)
3056         (message "Canceling your article...")
3057         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
3058           (funcall message-send-news-function))
3059         (message "Canceling your article...done")
3060         (kill-buffer buf)))))
3061
3062 ;;;###autoload
3063 (defun message-supersede ()
3064   "Start composing a message to supersede the current message.
3065 This is done simply by taking the old article and adding a Supersedes
3066 header line with the old Message-ID."
3067   (interactive)
3068   (let ((cur (current-buffer)))
3069     ;; Check whether the user owns the article that is to be superseded. 
3070     (unless (string-equal
3071              (downcase (cadr (mail-extract-address-components
3072                               (message-fetch-field "from"))))
3073              (downcase (message-make-address)))
3074       (error "This article is not yours"))
3075     ;; Get a normal message buffer.
3076     (message-pop-to-buffer (message-buffer-name "supersede"))
3077     (insert-buffer-substring cur)
3078     (message-narrow-to-head)
3079     ;; Remove unwanted headers.
3080     (when message-ignored-supersedes-headers
3081       (message-remove-header message-ignored-supersedes-headers t))
3082     (goto-char (point-min))
3083     (if (not (re-search-forward "^Message-ID: " nil t))
3084         (error "No Message-ID in this article")
3085       (replace-match "Supersedes: " t t))
3086     (goto-char (point-max))
3087     (insert mail-header-separator)
3088     (widen)
3089     (forward-line 1)))
3090
3091 ;;;###autoload
3092 (defun message-recover ()
3093   "Reread contents of current buffer from its last auto-save file."
3094   (interactive)
3095   (let ((file-name (make-auto-save-file-name)))
3096     (cond ((save-window-excursion
3097              (if (not (eq system-type 'vax-vms))
3098                  (with-output-to-temp-buffer "*Directory*"
3099                    (buffer-disable-undo standard-output)
3100                    (let ((default-directory "/"))
3101                      (call-process
3102                       "ls" nil standard-output nil "-l" file-name))))
3103              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3104            (let ((buffer-read-only nil))
3105              (erase-buffer)
3106              (insert-file-contents file-name nil)))
3107           (t (error "message-recover cancelled")))))
3108
3109 ;;; Forwarding messages.
3110
3111 (defun message-make-forward-subject ()
3112   "Return a Subject header suitable for the message in the current buffer."
3113   (save-excursion
3114     (save-restriction
3115       (current-buffer)
3116       (message-narrow-to-head)
3117       (concat "[" (or (message-fetch-field 
3118                        (if (message-news-p) "newsgroups" "from"))
3119                       "(nowhere)")
3120               "] " (or (message-fetch-field "Subject") "")))))
3121
3122 ;;;###autoload
3123 (defun message-forward (&optional news)
3124   "Forward the current message via mail.  
3125 Optional NEWS will use news to forward instead of mail."
3126   (interactive "P")
3127   (let ((cur (current-buffer))
3128         (subject (message-make-forward-subject))
3129         art-beg)
3130     (if news (message-news nil subject) (message-mail nil subject))
3131     ;; Put point where we want it before inserting the forwarded
3132     ;; message. 
3133     (if message-signature-before-forwarded-message
3134         (goto-char (point-max))
3135       (message-goto-body))
3136     ;; Make sure we're at the start of the line.
3137     (unless (eolp)
3138       (insert "\n"))
3139     ;; Narrow to the area we are to insert.
3140     (narrow-to-region (point) (point))
3141     ;; Insert the separators and the forwarded buffer.
3142     (insert message-forward-start-separator)
3143     (setq art-beg (point))
3144     (insert-buffer-substring cur)
3145     (goto-char (point-max))
3146     (insert message-forward-end-separator)
3147     (set-text-properties (point-min) (point-max) nil)
3148     ;; Remove all unwanted headers.
3149     (goto-char art-beg)
3150     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3151                                   (1- (point))
3152                                 (point)))
3153     (goto-char (point-min))
3154     (message-remove-header message-included-forward-headers t nil t)
3155     (widen)
3156     (message-position-point)))
3157
3158 ;;;###autoload
3159 (defun message-resend (address)
3160   "Resend the current article to ADDRESS."
3161   (interactive "sResend message to: ")
3162   (message "Resending message to %s..." address)
3163   (save-excursion
3164     (let ((cur (current-buffer))
3165           beg)
3166       ;; We first set up a normal mail buffer.
3167       (set-buffer (get-buffer-create " *message resend*"))
3168       (buffer-disable-undo (current-buffer))
3169       (erase-buffer)
3170       (message-setup `((To . ,address)))
3171       ;; Insert our usual headers.
3172       (message-generate-headers '(From Date To))
3173       (message-narrow-to-headers)
3174       ;; Rename them all to "Resent-*".
3175       (while (re-search-forward "^[A-Za-z]" nil t)
3176         (forward-char -1)
3177         (insert "Resent-"))
3178       (widen)
3179       (forward-line)
3180       (delete-region (point) (point-max))
3181       (setq beg (point))
3182       ;; Insert the message to be resent.
3183       (insert-buffer-substring cur)
3184       (goto-char (point-min))
3185       (search-forward "\n\n")
3186       (forward-char -1)
3187       (save-restriction
3188         (narrow-to-region beg (point))
3189         (message-remove-header message-ignored-resent-headers t)
3190         (goto-char (point-max)))
3191       (insert mail-header-separator)
3192       ;; Rename all old ("Also-")Resent headers.
3193       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
3194         (beginning-of-line)
3195         (insert "Also-"))
3196       ;; Quote any "From " lines at the beginning.
3197       (goto-char beg)
3198       (when (looking-at "From ")
3199         (replace-match "X-From-Line: "))
3200       ;; Send it.
3201       (message-send-mail)
3202       (kill-buffer (current-buffer)))
3203     (message "Resending message to %s...done" address)))
3204
3205 ;;;###autoload
3206 (defun message-bounce ()
3207   "Re-mail the current message.
3208 This only makes sense if the current message is a bounce message than
3209 contains some mail you have written which has been bounced back to
3210 you."
3211   (interactive)
3212   (let ((cur (current-buffer))
3213         boundary)
3214     (message-pop-to-buffer (message-buffer-name "bounce"))
3215     (insert-buffer-substring cur)
3216     (undo-boundary)
3217     (message-narrow-to-head)
3218     (if (and (message-fetch-field "Mime-Version")
3219              (setq boundary (message-fetch-field "Content-Type")))
3220         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3221             (setq boundary (concat (match-string 1 boundary) " *\n"
3222                                    "Content-Type: message/rfc822"))
3223           (setq boundary nil)))
3224     (widen)
3225     (goto-char (point-min))
3226     (search-forward "\n\n" nil t)
3227     (or (and boundary
3228              (re-search-forward boundary nil t)
3229              (forward-line 2))
3230         (and (re-search-forward message-unsent-separator nil t)
3231              (forward-line 1))
3232         (and (search-forward "\n\n" nil t)
3233              (re-search-forward "^Return-Path:.*\n" nil t)))
3234     ;; We remove everything before the bounced mail.
3235     (delete-region 
3236      (point-min)
3237      (if (re-search-forward "^[^ \n\t]+:" nil t)
3238          (match-beginning 0)
3239        (point)))
3240     (save-restriction
3241       (message-narrow-to-head)
3242       (message-remove-header message-ignored-bounced-headers t)
3243       (goto-char (point-max))
3244       (insert mail-header-separator))
3245     (message-position-point)))
3246
3247 ;;;
3248 ;;; Interactive entry points for new message buffers.
3249 ;;;
3250
3251 ;;;###autoload
3252 (defun message-mail-other-window (&optional to subject)
3253   "Like `message-mail' command, but display mail buffer in another window."
3254   (interactive)
3255   (let ((pop-up-windows t)
3256         (special-display-buffer-names nil)
3257         (special-display-regexps nil)
3258         (same-window-buffer-names nil)
3259         (same-window-regexps nil))
3260     (message-pop-to-buffer (message-buffer-name "mail" to)))
3261   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3262
3263 ;;;###autoload
3264 (defun message-mail-other-frame (&optional to subject)
3265   "Like `message-mail' command, but display mail buffer in another frame."
3266   (interactive)
3267   (let ((pop-up-frames t)
3268         (special-display-buffer-names nil)
3269         (special-display-regexps nil)
3270         (same-window-buffer-names nil)
3271         (same-window-regexps nil))
3272     (message-pop-to-buffer (message-buffer-name "mail" to)))
3273   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3274
3275 ;;;###autoload
3276 (defun message-news-other-window (&optional newsgroups subject)
3277   "Start editing a news article to be sent."
3278   (interactive)
3279   (let ((pop-up-windows t)
3280         (special-display-buffer-names nil)
3281         (special-display-regexps nil)
3282         (same-window-buffer-names nil)
3283         (same-window-regexps nil))
3284     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3285   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3286                    (Subject . ,(or subject "")))))
3287
3288 ;;;###autoload
3289 (defun message-news-other-frame (&optional newsgroups subject)
3290   "Start editing a news article to be sent."
3291   (interactive)
3292   (let ((pop-up-frames t)
3293         (special-display-buffer-names nil)
3294         (special-display-regexps nil)
3295         (same-window-buffer-names nil)
3296         (same-window-regexps nil))
3297     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3298   (message-setup `((Newsgroups . ,(or newsgroups "")) 
3299                    (Subject . ,(or subject "")))))
3300
3301 ;;; underline.el
3302
3303 ;; This code should be moved to underline.el (from which it is stolen). 
3304
3305 ;;;###autoload
3306 (defun bold-region (start end)
3307   "Bold all nonblank characters in the region.
3308 Works by overstriking characters.
3309 Called from program, takes two arguments START and END
3310 which specify the range to operate on."
3311   (interactive "r")
3312   (save-excursion
3313     (let ((end1 (make-marker)))
3314       (move-marker end1 (max start end))
3315       (goto-char (min start end))
3316       (while (< (point) end1)
3317         (or (looking-at "[_\^@- ]")
3318             (insert (following-char) "\b"))
3319         (forward-char 1)))))
3320
3321 ;;;###autoload
3322 (defun unbold-region (start end)
3323   "Remove all boldness (overstruck characters) in the region.
3324 Called from program, takes two arguments START and END
3325 which specify the range to operate on."
3326   (interactive "r")
3327   (save-excursion
3328     (let ((end1 (make-marker)))
3329       (move-marker end1 (max start end))
3330       (goto-char (min start end)) 
3331       (while (re-search-forward "\b" end1 t)
3332         (if (eq (following-char) (char-after (- (point) 2)))
3333             (delete-char -2))))))
3334
3335 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3336
3337 ;; Support for toolbar
3338 (when (string-match "XEmacs\\|Lucid" emacs-version)
3339   (require 'messagexmas))
3340
3341 ;;; Group name completion.
3342
3343 (defvar message-newgroups-header-regexp
3344   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
3345   "Regexp that match headers that lists groups.")
3346
3347 (defun message-tab ()
3348   "Expand group names in Newsgroups and Followup-To headers.
3349 Do a `tab-to-tab-stop' if not in those headers."
3350   (interactive)
3351   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3352         (mail-abbrev-in-expansion-header-p))
3353       (message-expand-group)
3354     (tab-to-tab-stop)))
3355
3356 (defvar gnus-active-hashtb)
3357 (defun message-expand-group ()
3358   (let* ((b (save-excursion 
3359               (save-restriction
3360                 (narrow-to-region 
3361                  (save-excursion
3362                    (beginning-of-line)
3363                    (skip-chars-forward "^:")
3364                    (1+ (point)))
3365                  (point))
3366                 (skip-chars-backward "^, \t\n") (point))))
3367          (completion-ignore-case t)
3368          (string (buffer-substring b (point)))
3369          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3370          (completions (all-completions string hashtb))
3371          (cur (current-buffer))
3372          comp)
3373     (delete-region b (point))
3374     (cond 
3375      ((= (length completions) 1)
3376       (if (string= (car completions) string)
3377           (progn
3378             (insert string)
3379             (message "Only matching group"))
3380         (insert (car completions))))
3381      ((and (setq comp (try-completion string hashtb))
3382            (not (string= comp string)))
3383       (insert comp))
3384      (t
3385       (insert string)
3386       (if (not comp)
3387           (message "No matching groups")
3388         (pop-to-buffer "*Completions*")
3389         (buffer-disable-undo (current-buffer))
3390         (let ((buffer-read-only nil))
3391           (erase-buffer)
3392           (let ((standard-output (current-buffer)))
3393             (display-completion-list (sort completions 'string<)))
3394           (goto-char (point-min))
3395           (pop-to-buffer cur)))))))
3396
3397 ;;; Help stuff.
3398
3399 (defun message-talkative-question (ask question show &rest text)
3400   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
3401 The following arguments may contain lists of values."
3402   (if (and show
3403            (setq text (message-flatten-list text)))
3404       (save-window-excursion
3405         (save-excursion
3406           (with-output-to-temp-buffer " *MESSAGE information message*"
3407             (set-buffer " *MESSAGE information message*")
3408             (mapcar 'princ text)
3409             (goto-char (point-min))))
3410         (funcall ask question))
3411     (funcall ask question)))
3412
3413 (defun message-flatten-list (list)
3414   "Return a new, flat list that contains all elements of LIST.
3415
3416 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3417 => (1 2 3 4 5 6 7)"
3418   (cond ((consp list) 
3419          (apply 'append (mapcar 'message-flatten-list list)))
3420         (list
3421          (list list))))
3422
3423 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
3424   "Create and return a buffer with a name based on NAME using generate-new-buffer.
3425 Then clone the local variables and values from the old buffer to the
3426 new one, cloning only the locals having a substring matching the
3427 regexp varstr."
3428   (let ((oldlocals (buffer-local-variables)))
3429     (save-excursion
3430       (set-buffer (generate-new-buffer name))
3431       (mapcar (lambda (dude)
3432                 (when (and (car dude)
3433                            (or (not varstr)
3434                                (string-match varstr (symbol-name (car dude)))))
3435                   (ignore-errors
3436                     (set (make-local-variable (car dude))
3437                          (cdr dude)))))
3438               oldlocals)
3439       (current-buffer))))
3440
3441 (run-hooks 'message-load-hook)
3442
3443 (provide 'message)
3444
3445 ;;; message.el ends here