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