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