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