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