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