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