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