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