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