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