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