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