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