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