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