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