*** 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 ()
979   "Send message like `message-send', then, if no errors, exit from mail buffer."
980   (interactive)
981   (let ((buf (current-buffer)))
982     (when (message-send)
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 "@\\(\\W+\\)\\(\\'\\|\\W\\)" user-mail-address)
1649       (match-string 1 user-mail-address))
1650      (t
1651       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
1652
1653 (defun message-make-host-name ()
1654   "Return the name of the host."
1655   (let ((fqdm (message-make-fqdm)))
1656     (string-match "^[^.]+\\." fqdm)
1657     (substring fqdm 0 (1- (match-end 0)))))
1658
1659 (defun message-make-domain ()
1660   "Return the domain name."
1661   (or mail-host-address
1662       (message-make-fqdm)))
1663
1664 (defun message-generate-headers (headers)
1665   "Prepare article HEADERS.
1666 Headers already prepared in the buffer are not modified."
1667   (save-restriction
1668     (message-narrow-to-headers)
1669     (let* ((Date (message-make-date))
1670            (Message-ID (message-make-message-id))
1671            (Organization (message-make-organization))
1672            (From (message-make-from))
1673            (Path (message-make-path))
1674            (Subject nil)
1675            (Newsgroups nil)
1676            (In-Reply-To (message-make-in-reply-to))
1677            (To nil)
1678            (Distribution (message-make-distribution))
1679            (Lines (message-make-lines))
1680            (X-Newsreader message-newsreader)
1681            (X-Mailer message-mailer)
1682            (Expires (message-make-expires))
1683            (case-fold-search t)
1684            header value elem)
1685       ;; First we remove any old generated headers.
1686       (let ((headers message-deletable-headers))
1687         (while headers
1688           (goto-char (point-min))
1689           (and (re-search-forward 
1690                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1691                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
1692                (message-delete-line))
1693           (pop headers)))
1694       ;; Go through all the required headers and see if they are in the
1695       ;; articles already. If they are not, or are empty, they are
1696       ;; inserted automatically - except for Subject, Newsgroups and
1697       ;; Distribution. 
1698       (while headers
1699         (goto-char (point-min))
1700         (setq elem (pop headers))
1701         (if (consp elem)
1702             (if (eq (car elem) 'optional)
1703                 (setq header (cdr elem))
1704               (setq header (car elem)))
1705           (setq header elem))
1706         (when (or (not (re-search-forward 
1707                         (concat "^" (downcase (symbol-name header)) ":") 
1708                         nil t))
1709                   (progn
1710                     ;; The header was found. We insert a space after the
1711                     ;; colon, if there is none.
1712                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
1713                     ;; Find out whether the header is empty...
1714                     (looking-at "[ \t]*$")))
1715           ;; So we find out what value we should insert.
1716           (setq value
1717                 (cond 
1718                  ((and (consp elem) (eq (car elem) 'optional))
1719                   ;; This is an optional header.  If the cdr of this
1720                   ;; is something that is nil, then we do not insert
1721                   ;; this header.
1722                   (setq header (cdr elem))
1723                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
1724                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
1725                  ((consp elem)
1726                   ;; The element is a cons.  Either the cdr is a
1727                   ;; string to be inserted verbatim, or it is a
1728                   ;; function, and we insert the value returned from
1729                   ;; this function.
1730                   (or (and (stringp (cdr elem)) (cdr elem))
1731                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
1732                  ((and (boundp header) (symbol-value header))
1733                   ;; The element is a symbol.  We insert the value
1734                   ;; of this symbol, if any.
1735                   (symbol-value header))
1736                  (t
1737                   ;; We couldn't generate a value for this header,
1738                   ;; so we just ask the user.
1739                   (read-from-minibuffer
1740                    (format "Empty header for %s; enter value: " header)))))
1741           ;; Finally insert the header.
1742           (when (and value 
1743                      (not (equal value "")))
1744             (save-excursion
1745               (if (bolp)
1746                   (progn
1747                     ;; This header didn't exist, so we insert it.
1748                     (goto-char (point-max))
1749                     (insert (symbol-name header) ": " value "\n")
1750                     (forward-line -1))
1751                 ;; The value of this header was empty, so we clear
1752                 ;; totally and insert the new value.
1753                 (delete-region (point) (message-point-at-eol))
1754                 (insert value))
1755               ;; Add the deletable property to the headers that require it.
1756               (and (memq header message-deletable-headers)
1757                    (progn (beginning-of-line) (looking-at "[^:]+: "))
1758                    (add-text-properties 
1759                     (point) (match-end 0)
1760                     '(message-deletable t face italic) (current-buffer)))))))
1761       ;; Insert new Sender if the From is strange. 
1762       (let ((from (mail-fetch-field "from"))
1763             (sender (mail-fetch-field "sender"))
1764             (secure-sender (message-make-sender)))
1765         (when (and from 
1766                    (not (message-check-element 'sender))
1767                    (not (string=
1768                          (downcase
1769                           (cadr (mail-extract-address-components from)))
1770                          (downcase secure-sender)))
1771                    (or (null sender)
1772                        (not 
1773                         (string=
1774                          (downcase
1775                           (cadr (mail-extract-address-components sender)))
1776                          (downcase secure-sender)))))
1777           (goto-char (point-min))    
1778           ;; Rename any old Sender headers to Original-Sender.
1779           (when (re-search-forward "^Sender:" nil t)
1780             (beginning-of-line)
1781             (insert "Original-")
1782             (beginning-of-line))
1783           (insert "Sender: " secure-sender "\n"))))))
1784
1785 (defun message-insert-courtesy-copy ()
1786   "Insert a courtesy message in mail copies of combined messages."
1787   (save-excursion
1788     (save-restriction
1789       (message-narrow-to-headers)
1790       (let ((newsgroups (mail-fetch-field "newsgroups")))
1791         (when newsgroups
1792           (goto-char (point-max))
1793           (insert "Posted-To: " newsgroups "\n"))))
1794     (forward-line 1)
1795     (insert message-courtesy-message)))
1796     
1797 ;;;
1798 ;;; Setting up a message buffer
1799 ;;;
1800
1801 (defun message-fill-header (header value)
1802   (let ((begin (point))
1803         (fill-column 78)
1804         (fill-prefix "\t")
1805         end)
1806     (insert (capitalize (symbol-name header))
1807             ": "
1808             (if (consp value) (car value) value)
1809             "\n")
1810     (save-restriction
1811       (narrow-to-region begin (point))
1812       (fill-region-as-paragraph begin (point))
1813       ;; Tapdance around looong Message-IDs.
1814       (forward-line -1)
1815       (when (eolp)
1816         (message-delete-line))
1817       (goto-char begin)
1818       (re-search-forward ":" nil t)
1819       (when (looking-at "\n[ \t]+")
1820         (replace-match " " t t))
1821       (goto-char (point-max)))))
1822
1823 (defun sendmail-synch-aliases ()
1824   (let ((modtime (nth 5 (file-attributes message-personal-alias-file))))
1825     (or (equal message-alias-modtime modtime)
1826         (setq message-alias-modtime modtime
1827               message-aliases t))))
1828
1829 (defun message-position-point ()
1830   "Move point to where the user probably wants to find it."
1831   (message-narrow-to-headers)
1832   (cond 
1833    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
1834     (search-backward ":" )
1835     (widen)
1836     (forward-char 1)
1837     (if (= (following-char) ? )
1838         (forward-char 1)
1839       (insert " ")))
1840    (t
1841     (goto-char (point-max))
1842     (widen)
1843     (forward-line 1)
1844     (unless (looking-at "$")
1845       (forward-line 2)))
1846    (sit-for 0)))
1847
1848 (defun message-pop-to-buffer (name)
1849   "Pop to buffer NAME, and warn if it already exists and is modified."
1850   (let ((buffer (get-buffer name)))
1851     (if (and buffer
1852              (buffer-name buffer))
1853         (progn
1854           (set-buffer (pop-to-buffer buffer))
1855           (when (and (buffer-modified-p)
1856                      (not (y-or-n-p
1857                            "Message already being composed; erase? ")))
1858             (error "Message being composed")))
1859       (set-buffer (pop-to-buffer name)))
1860     (erase-buffer)
1861     (message-mode)))
1862
1863 (defun message-setup (headers &optional replybuffer actions)
1864   (setq message-send-actions actions)
1865   (setq message-reply-buffer replybuffer)
1866   (goto-char (point-min))
1867   ;; Insert all the headers.
1868   (mail-header-format 
1869    (let ((h headers)
1870          (alist message-header-format-alist))
1871      (while h
1872        (unless (assq (caar h) message-header-format-alist)
1873          (push (list (caar h)) alist))
1874        (pop h))
1875      alist)
1876    headers)
1877   (forward-line -1)
1878   (when message-default-headers
1879     (insert message-default-headers))
1880   (insert mail-header-separator "\n")
1881   (forward-line -1)
1882   (when (and (message-news-p)
1883              message-default-news-headers)
1884     (when message-generate-headers-first
1885       (message-generate-headers message-required-news-headers))
1886     (insert message-default-news-headers))
1887   (when (and (message-mail-p)
1888              message-default-mail-headers)
1889     (when message-generate-headers-first
1890       (message-generate-headers message-required-mail-headers))
1891     (insert message-default-mail-headers))
1892   (message-insert-signature)
1893   (message-set-auto-save-file-name)
1894   (save-restriction
1895     (message-narrow-to-headers)
1896     (run-hooks 'message-header-setup-hook))
1897   (set-buffer-modified-p nil)
1898   (run-hooks 'message-setup-hook)
1899   (message-position-point)
1900   (undo-boundary))
1901
1902 (defun message-set-auto-save-file-name ()
1903   "Associate the message buffer with a file in the drafts directory."
1904   (when message-autosave-directory
1905     (unless (file-exists-p message-autosave-directory)
1906       (make-directory message-autosave-directory t))
1907     (let ((name (make-temp-name
1908                  (concat (file-name-as-directory message-autosave-directory)
1909                          "msg."))))
1910       (setq buffer-auto-save-file-name
1911             (save-excursion
1912               (prog1
1913                   (progn
1914                     (set-buffer (get-buffer-create " *draft tmp*"))
1915                     (setq buffer-file-name name)
1916                     (make-auto-save-file-name))
1917                 (kill-buffer (current-buffer)))))
1918       (clear-visited-file-modtime))))
1919
1920 \f
1921
1922 ;;;
1923 ;;; Commands for interfacing with message
1924 ;;;
1925
1926 ;;;###autoload
1927 (defun message-mail (&optional to subject)
1928   "Start editing a mail message to be sent."
1929   (interactive)
1930   (message-pop-to-buffer "*mail message*")
1931   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
1932
1933 ;;;###autoload
1934 (defun message-news (&optional newsgroups subject)
1935   "Start editing a news article to be sent."
1936   (interactive)
1937   (message-pop-to-buffer "*news message*")
1938   (message-setup `((Newsgroups . ,(or newsgroups "")) 
1939                    (Subject . ,(or subject "")))))
1940
1941 ;;;###autoload
1942 (defun message-reply (&optional to-address wide)
1943   "Start editing a reply to the article in the current buffer."
1944   (interactive)
1945   (let ((cur (current-buffer))
1946         from subject date reply-to message-of to cc
1947         references message-id sender follow-to sendto elt new-cc new-to
1948         mct never-mct gnus-warning)
1949     (save-restriction
1950       (narrow-to-region
1951        (goto-char (point-min))
1952        (if (search-forward "\n\n" nil t)
1953            (1- (point))
1954          (point-max)))
1955       ;; Allow customizations to have their say.
1956       (if (not wide)
1957           ;; This is a regular reply.
1958           (if (message-functionp message-reply-to-function)
1959               (setq follow-to (funcall message-reply-to-function)))
1960         ;; This is a followup.
1961         (if (message-functionp message-wide-reply-to-function)
1962             (save-excursion
1963               (setq follow-to
1964                     (funcall message-wide-reply-to-function)))))
1965       ;; Find all relevant headers we need.
1966       (setq from (mail-fetch-field "from")
1967             date (mail-fetch-field "date") 
1968             sender (mail-fetch-field "sender")
1969             subject (or (mail-fetch-field "subject") "none")
1970             to (mail-fetch-field "to")
1971             cc (mail-fetch-field "cc")
1972             mct (mail-fetch-field "mail-copies-to")
1973             reply-to (mail-fetch-field "reply-to")
1974             references (mail-fetch-field "references")
1975             message-id (mail-fetch-field "message-id"))
1976       ;; Remove any (buggy) Re:'s that are present and make a
1977       ;; proper one.
1978       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
1979         (setq subject (substring subject (match-end 0))))
1980       (setq subject (concat "Re: " subject))
1981
1982       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
1983                  (string-match "<[^>]+>" gnus-warning))
1984         (setq message-id (match-string 0 gnus-warning)))
1985             
1986       ;; Handle special values of Mail-Copies-To.
1987       (when mct
1988         (cond ((equal (downcase mct) "never")
1989                (setq never-mct t)
1990                (setq mct nil))
1991               ((equal (downcase mct) "always")
1992                (setq mct (or reply-to from)))))
1993
1994       (unless follow-to
1995         (if (or (not wide)
1996                 to-address)
1997             (setq follow-to (list (cons 'To (or to-address reply-to from))))
1998           (let (ccalist)
1999             (save-excursion
2000               (message-set-work-buffer)
2001               (unless never-mct
2002                 (insert (or reply-to from "")))
2003               (insert 
2004                (if (bolp) "" ", ") (or to "")
2005                (if mct (concat (if (bolp) "" ", ") mct) "")
2006                (if cc (concat (if (bolp) "" ", ") cc) ""))
2007               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2008               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2009                         (erase-buffer)))
2010               (goto-char (point-min))
2011               (setq ccalist
2012                     (mapcar
2013                      (lambda (addr)
2014                        (cons (mail-strip-quoted-names addr) addr))
2015                      (nreverse (mail-parse-comma-list))))
2016               (let ((s ccalist))
2017                 (while s
2018                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2019             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2020             (when ccalist
2021               (push (cons 'Cc
2022                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2023                     follow-to)))))
2024       (widen))
2025
2026     (message-pop-to-buffer "*mail message*")
2027
2028     (setq message-reply-headers
2029           (vector 0 subject from date message-id references 0 0 ""))
2030
2031     (message-setup
2032      `((Subject . ,subject)
2033        ,@follow-to 
2034        (References . ,(concat (or references "") (and references " ")
2035                               (or message-id ""))))
2036      cur)))
2037
2038 ;;;###autoload
2039 (defun message-wide-reply (&optional to-address)
2040   (interactive)
2041   (message-reply to-address t))
2042
2043 ;;;###autoload
2044 (defun message-followup ()
2045   (interactive)
2046   (let ((cur (current-buffer))
2047         from subject date message-of reply-to mct
2048         references message-id follow-to sendto elt 
2049         followup-to distribution newsgroups gnus-warning)
2050     (save-restriction
2051       (narrow-to-region
2052        (goto-char (point-min))
2053        (if (search-forward "\n\n" nil t)
2054            (1- (point))
2055          (point-max)))
2056       (when (message-functionp message-followup-to-function)
2057         (setq follow-to
2058               (funcall message-followup-to-function)))
2059       (setq from (mail-fetch-field "from")
2060             date (mail-fetch-field "date") 
2061             subject (or (mail-fetch-field "subject") "none")
2062             references (mail-fetch-field "references")
2063             message-id (mail-fetch-field "message-id")
2064             followup-to (mail-fetch-field "followup-to")
2065             newsgroups (mail-fetch-field "newsgroups")
2066             reply-to (mail-fetch-field "reply-to")
2067             distribution (mail-fetch-field "distribution")
2068             mct (mail-fetch-field "mail-copies-to"))
2069       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
2070                  (string-match "<[^>]+>" gnus-warning))
2071         (setq message-id (match-string 0 gnus-warning)))
2072       ;; Remove bogus distribution.
2073       (and (stringp distribution)
2074            (string-match "world" distribution)
2075            (setq distribution nil))
2076       ;; Remove any (buggy) Re:'s that are present and make a
2077       ;; proper one.
2078       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
2079         (setq subject (substring subject (match-end 0))))
2080       (setq subject (concat "Re: " subject))
2081       (widen))
2082
2083     (message-pop-to-buffer "*news message*")
2084
2085     (message-setup
2086      `((Subject . ,subject)
2087        ,@(cond 
2088           (follow-to follow-to)
2089           ((and followup-to message-use-followup-to)
2090            (list
2091             (cond 
2092              ((equal (downcase followup-to) "poster")
2093               (if (or (eq message-use-followup-to 'use)
2094                       (y-or-n-p "Use Followup-To \"poster\"? "))
2095                   (cons 'To (or reply-to from ""))
2096                 (cons 'Newsgroups newsgroups)))
2097              (t
2098               (if (or (equal followup-to newsgroups)
2099                       (not (eq message-use-followup-to 'ask))
2100                       (y-or-n-p (format "Use Followup-To %s? " followup-to)))
2101                   (cons 'Newsgroups followup-to)
2102                 (cons 'Newsgroups newsgroups))))))
2103           (t
2104            `((Newsgroups . ,newsgroups))))
2105        ,@(and distribution (list (cons 'Distribution distribution)))
2106        (References . ,(concat (or references "") (and references " ")
2107                               (or message-id "")))
2108        ,@(when (and mct
2109                     (not (equal (downcase mct) "never")))
2110            (list (cons 'Cc (if (equal (downcase mct) "always")
2111                                (or reply-to from "")
2112                              mct)))))
2113      cur)))
2114
2115 ;;;###autoload
2116 (defun message-cancel-news ()
2117   "Cancel an article you posted."
2118   (interactive)
2119   (unless (message-news-p)
2120     (error "This is not a news article; canceling is impossible"))
2121   (when (yes-or-no-p "Do you really want to cancel this article? "))
2122   (let (from newsgroups message-id distribution buf)
2123     (save-excursion
2124       ;; Get header info. from original article.
2125       (save-restriction
2126         (message-narrow-to-head)
2127         (setq from (mail-fetch-field "from")
2128               newsgroups (mail-fetch-field "newsgroups")
2129               message-id (mail-fetch-field "message-id")
2130               distribution (mail-fetch-field "distribution")))
2131       ;; Make sure that this article was written by the user.
2132       (unless (string-equal
2133                (downcase (mail-strip-quoted-names from))
2134                (downcase (message-make-address)))
2135         (error "This article is not yours"))
2136       ;; Make control message.
2137       (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2138       (buffer-disable-undo (current-buffer))
2139       (erase-buffer)
2140       (insert "Newsgroups: " newsgroups "\n"
2141               "From: " (message-make-from) "\n"
2142               "Subject: cmsg cancel " message-id "\n"
2143               "Control: cancel " message-id "\n"
2144               (if distribution
2145                   (concat "Distribution: " distribution "\n")
2146                 "")
2147               mail-header-separator "\n"
2148               "This is a cancel message from " from ".\n")
2149       (message "Canceling your article...")
2150       (funcall message-send-news-function)
2151       (message "Canceling your article...done")
2152       (kill-buffer buf))))
2153
2154 ;;;###autoload
2155 (defun message-supersede ()
2156   "Start composing a message to supersede the current message.
2157 This is done simply by taking the old article and adding a Supersedes
2158 header line with the old Message-ID."
2159   (interactive)
2160   (let ((cur (current-buffer)))
2161     ;; Check whether the user owns the article that is to be superseded. 
2162     (unless (string-equal
2163              (downcase (mail-strip-quoted-names (mail-fetch-field "from")))
2164              (downcase (mail-strip-quoted-names (message-make-address))))
2165       (error "This article is not yours"))
2166     ;; Get a normal message buffer.
2167     (message-pop-to-buffer "*supersede message*")
2168     (insert-buffer-substring cur)
2169     (message-narrow-to-head)
2170     ;; Remove unwanted headers.
2171     (when message-ignored-supersedes-headers
2172       (message-remove-header message-ignored-supersedes-headers t))
2173     (goto-char (point-min))
2174     (if (not (re-search-forward "^Message-ID: " nil t))
2175         (error "No Message-ID in this article")
2176       (replace-match "Supersedes: " t t))
2177     (goto-char (point-max))
2178     (insert mail-header-separator)
2179     (widen)
2180     (forward-line 1)))
2181
2182 ;;;###autoload
2183 (defun message-recover ()
2184   "Reread contents of current buffer from its last auto-save file."
2185   (interactive)
2186   (let ((file-name (make-auto-save-file-name)))
2187     (cond ((save-window-excursion
2188              (if (not (eq system-type 'vax-vms))
2189                  (with-output-to-temp-buffer "*Directory*"
2190                    (buffer-disable-undo standard-output)
2191                    (let ((default-directory "/"))
2192                      (call-process
2193                       "ls" nil standard-output nil "-l" file-name))))
2194              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2195            (let ((buffer-read-only nil))
2196              (erase-buffer)
2197              (insert-file-contents file-name nil)))
2198           (t (error "message-recover cancelled")))))
2199
2200 ;;; Forwarding messages.
2201
2202 (defun message-make-forward-subject ()
2203   "Return a Subject header suitable for the message in the current buffer."
2204   (concat "[" (mail-fetch-field (if (message-news-p) "newsgroups" "from"))
2205           "] " (or (mail-fetch-field "Subject") "")))
2206
2207 ;;;###autoload
2208 (defun message-forward (&optional news)
2209   "Forward the current message via mail.  
2210 Optional NEWS will use news to forward instead of mail."
2211   (interactive "P")
2212   (let ((cur (current-buffer))
2213         (subject (message-make-forward-subject)))
2214     (if news (message-news nil subject) (message-mail nil subject))
2215     ;; Put point where we want it before inserting the forwarded
2216     ;; message. 
2217     (if message-signature-before-forwarded-message
2218         (goto-char (point-max))
2219       (message-goto-body))
2220     ;; Narrow to the area we are to insert.
2221     (narrow-to-region (point) (point))
2222     ;; Insert the separators and the forwarded buffer.
2223     (insert message-forward-start-separator)
2224     (insert-buffer-substring cur)
2225     (goto-char (point-max))
2226     (insert message-forward-end-separator)
2227     (set-text-properties (point-min) (point-max) nil)
2228     ;; Remove all unwanted headers.
2229     (goto-char (point-min))
2230     (forward-line 1)
2231     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2232                                   (1- (point))
2233                                 (point)))
2234     (goto-char (point-min))
2235     (message-remove-header message-included-forward-headers t nil t)
2236     (widen)
2237     (message-position-point)))
2238
2239 ;;;###autoload
2240 (defun message-resend (address)
2241   "Resend the current article to ADDRESS."
2242   (interactive "sResend message to: ")
2243   (save-excursion
2244     (let ((cur (current-buffer))
2245           beg)
2246       ;; We first set up a normal mail buffer.
2247       (message-set-work-buffer)
2248       (message-setup `((To . ,address)))
2249       ;; Insert our usual headers.
2250       (message-narrow-to-headers)
2251       (message-generate-headers '(From Date To))
2252       (goto-char (point-min))
2253       ;; Rename them all to "Resent-*".
2254       (while (re-search-forward "^[A-Za-z]" nil t)
2255         (forward-char -1)
2256         (insert "Resent-"))
2257       (widen)
2258       (forward-line)
2259       (delete-region (point) (point-max))
2260       (setq beg (point))
2261       ;; Insert the message to be resent.
2262       (insert-buffer-substring cur)
2263       (goto-char (point-min))
2264       (search-forward "\n\n")
2265       (forward-char -1)
2266       (save-restriction
2267         (narrow-to-region beg (point))
2268         (message-remove-header message-ignored-resent-headers t)
2269         (goto-char (point-max)))
2270       (insert mail-header-separator)
2271       ;; Rename all old ("Also-")Resent headers.
2272       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2273         (beginning-of-line)
2274         (insert "Also-"))
2275       ;; Send it.
2276       (funcall message-send-mail-function))))
2277
2278 ;;;###autoload
2279 (defun message-bounce ()
2280   "Re-mail the current message.
2281 This only makes sense if the current message is a bounce message than
2282 contains some mail you have written which has been bounced back to
2283 you."
2284   (interactive "P")
2285   (let ((cur (current-buffer)))
2286     (message-pop-to-buffer "*mail message*")
2287     (insert-buffer-substring cur)
2288     (goto-char (point-min))
2289     (or (and (re-search-forward mail-unsent-separator nil t)
2290              (forward-line 1))
2291         (and (search-forward "\n\n" nil t)
2292              (re-search-forward "^Return-Path:.*\n" nil t)))
2293     ;; We remove everything before the bounced mail.
2294     (delete-region 
2295      (point-min)
2296      (if (re-search-forward "[^ \t]*:" nil t)
2297          (match-beginning 0)
2298        (point)))
2299     (save-restriction
2300       (message-narrow-to-head)
2301       (message-remove-header message-ignored-bounced-headers t)
2302       (goto-char (point-max))
2303       (insert mail-header-separator))
2304     (message-position-point)))
2305
2306 ;;;
2307 ;;; Interactive entry points for new message buffers.
2308 ;;;
2309
2310 ;;;###autoload
2311 (defun message-mail-other-window (&optional to subject)
2312   "Like `message-mail' command, but display mail buffer in another window."
2313   (interactive)
2314   (let ((pop-up-windows t)
2315         (special-display-buffer-names nil)
2316         (special-display-regexps nil)
2317         (same-window-buffer-names nil)
2318         (same-window-regexps nil))
2319     (message-pop-to-buffer "*mail message*"))
2320   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2321
2322 ;;;###autoload
2323 (defun message-mail-other-frame (&optional to subject)
2324   "Like `message-mail' command, but display mail buffer in another frame."
2325   (interactive)
2326   (let ((pop-up-frames t)
2327         (special-display-buffer-names nil)
2328         (special-display-regexps nil)
2329         (same-window-buffer-names nil)
2330         (same-window-regexps nil))
2331     (message-pop-to-buffer "*mail message*"))
2332   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2333
2334 ;;;###autoload
2335 (defun message-news-other-window (&optional newsgroups subject)
2336   "Start editing a news article to be sent."
2337   (interactive)
2338   (let ((pop-up-windows t)
2339         (special-display-buffer-names nil)
2340         (special-display-regexps nil)
2341         (same-window-buffer-names nil)
2342         (same-window-regexps nil))
2343     (message-pop-to-buffer "*news message*"))
2344   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2345                    (Subject . ,(or subject "")))))
2346
2347 ;;;###autoload
2348 (defun message-news-other-frame (&optional newsgroups subject)
2349   "Start editing a news article to be sent."
2350   (interactive)
2351   (let ((pop-up-frames t)
2352         (special-display-buffer-names nil)
2353         (special-display-regexps nil)
2354         (same-window-buffer-names nil)
2355         (same-window-regexps nil))
2356     (message-pop-to-buffer "*news message*"))
2357   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2358                    (Subject . ,(or subject "")))))
2359
2360 ;;; underline.el
2361
2362 ;; This code should be moved to underline.el (from which it is stolen). 
2363
2364 ;;;###autoload
2365 (defun bold-region (start end)
2366   "Bold all nonblank characters in the region.
2367 Works by overstriking characters.
2368 Called from program, takes two arguments START and END
2369 which specify the range to operate on."
2370   (interactive "r")
2371   (save-excursion
2372    (let ((end1 (make-marker)))
2373      (move-marker end1 (max start end))
2374      (goto-char (min start end))
2375      (while (< (point) end1)
2376        (or (looking-at "[_\^@- ]")
2377            (insert (following-char) "\b"))
2378        (forward-char 1)))))
2379
2380 ;;;###autoload
2381 (defun unbold-region (start end)
2382   "Remove all boldness (overstruck characters) in the region.
2383 Called from program, takes two arguments START and END
2384 which specify the range to operate on."
2385   (interactive "r")
2386   (save-excursion
2387    (let ((end1 (make-marker)))
2388      (move-marker end1 (max start end))
2389      (goto-char (min start end)) 
2390      (while (re-search-forward "\b" end1 t)
2391        (if (eq (following-char) (char-after (- (point) 2)))
2392            (delete-char -2))))))
2393
2394 (provide 'message)
2395
2396 ;;; message.el ends here