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