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