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