*** empty log message ***
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages
2 ;; Copyright (C) 1996 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
5 ;; Keywords: mail, news
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This mode provides mail-sending facilities from within Emacs.  It
27 ;; consists mainly of large chunks of code from the sendmail.el,
28 ;; gnus-msg.el and rnewspost.el files.
29
30 ;;; Code:
31
32 (eval-when-compile 
33   (require 'cl))
34 (require 'mail-header)
35 (require 'nnheader)
36
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 'angles 
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
65 ;;;###autoload
66 (defvar message-syntax-checks
67   '(subject-cmsg multiple-headers sendsys message-id from
68                  long-lines control-chars size new-text
69                  redirected-followup signature approved sender 
70                  empty empty-headers message-id from subject)
71   "In non-nil, message will attempt to run some checks on outgoing posts.
72 If this variable is t, message will check everything it can.  If it is
73 a list, then those elements in that list will be checked.")
74
75 ;;;###autoload
76 (defvar message-required-news-headers
77   '(From Date Newsgroups Subject Message-ID 
78          (optional . Organization) Lines 
79          (optional . X-Newsreader))
80   "*Headers to be generated or prompted for when posting an article.
81 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
82 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
83 X-Newsreader are optional.  If don't you want message to insert some
84 header, remove it from this list.")
85
86 ;;;###autoload
87 (defvar message-required-mail-headers 
88   '(From Date To Subject (optional . In-Reply-To) Message-ID Lines
89          (optional . X-Mailer))
90   "*Headers to be generated or prompted for when mailing a message.
91 RFC822 required that From, Date, To, Subject and Message-ID be
92 included.  Organization, Lines and X-Mailer are optional.")
93
94 ;;;###autoload
95 (defvar message-deletable-headers '(Message-ID Date)
96   "*Headers to be deleted if they already exist and were generated by message previously.")
97
98 ;;;###autoload
99 (defvar message-ignored-news-headers 
100   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:"
101   "*Regexp of headers to be removed unconditionally before posting.")
102
103 ;;;###autoload
104 (defvar message-ignored-mail-headers "^Gcc:"
105   "*Regexp of headers to be removed unconditionally before mailing.")
106
107 ;;;###autoload
108 (defvar message-ignored-supersedes-headers
109   "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:"
110   "*Header lines matching this regexp will be deleted before posting.
111 It's best to delete old Path and Date headers before posting to avoid
112 any confusion.")
113
114 ;;;###autoload
115 (defvar message-signature-separator "^-- *$"
116   "Regexp matching signature separator.")
117
118 ;;;###autoload
119 (defvar message-interactive nil 
120   "Non-nil means when sending a message wait for and display errors.
121 nil means let mailer mail back a message to report errors.")
122
123 (defvar gnus-local-organization)
124 ;;;###autoload
125 (defvar message-user-organization 
126   (if (boundp 'gnus-local-organization)
127       gnus-local-organization t)
128   "*String to be used as an Organization header.
129 If t, use `message-user-organization-file'.")
130
131 ;;;###autoload
132 (defvar message-user-organization-file "/usr/lib/news/organization"
133   "*Local news organization file.")
134
135 ;;;###autoload
136 (defvar message-autosave-directory "~/Mail/drafts/"
137   "*Directory where message autosaves buffers.
138 If nil, message won't autosave.")
139
140 (defvar message-forward-start-separator 
141   "------- Start of forwarded message -------\n"
142   "*Delimiter inserted before forwarded messages.")
143
144 (defvar message-forward-end-separator
145   "------- End of forwarded message -------\n"
146   "*Delimiter inserted after forwarded messages.")
147
148 ;;;###autoload
149 (defvar message-signature-before-forwarded-message t
150   "*If non-nil, put the signature before any included forwarded message.")
151
152 ;;;###autoload
153 (defvar message-included-forward-headers 
154   "^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:"
155   "*Regexp matching headers to be included in forwarded messages.")
156
157 ;;;###autoload
158 (defvar message-ignored-resent-headers "^Return-receipt"
159   "*All headers that match this regexp will be deleted when resending a message.")
160
161 ;;;###autoload
162 (defvar message-ignored-cited-headers "."
163   "Delete these headers from the messages you yank.")
164
165 ;; Useful to set in site-init.el
166 ;;;###autoload
167 (defvar message-send-mail-function 'message-send-mail 
168   "Function to call to send the current buffer as mail.
169 The headers should be delimited by a line whose contents match the
170 variable `message-header-separator'.")
171
172 ;;;###autoload
173 (defvar message-send-news-function 'message-send-news
174   "Function to call to send the current buffer as news.
175 The headers should be delimited by a line whose contents match the
176 variable `message-header-separator'.")
177
178 ;;;###autoload
179 (defvar message-reply-to-function nil
180   "Function that should return a list of headers.")
181
182 ;;;###autoload
183 (defvar message-wide-reply-to-function nil
184   "Function that should return a list of headers.")
185
186 ;;;###autoload
187 (defvar message-followup-to-function nil
188   "Function that should return a list of headers.")
189
190 ;;;###autoload
191 (defvar message-use-followup-to 'ask
192   "*Specifies what to do with Followup-To header.
193 If nil, ignore the header. If it is t, use its value, but ignore
194 \"poster\".  If it is the symbol `ask', query the user whether to
195 ignore the \"poster\" value.  If it is the symbol `use', always use
196 the value.")
197
198 ;;;###autoload
199 (defvar message-post-method 
200   (cond ((boundp 'gnus-post-method)
201          gnus-post-method)
202         ((boundp 'gnus-select-method)
203          gnus-select-method)
204         (t '(nnspool "")))
205   "Method used to post news.")
206
207 ;;;###autoload
208 (defvar message-generate-headers-first nil
209   "*If non-nil, generate all possible headers before composing.")
210
211 ;;;###autoload
212 (defvar message-header-separator "--text follows this line--" 
213   "*Line used to separate headers from text in messages being composed.")
214
215 ;;;###autoload
216 (defvar message-alias-file nil
217   "*If non-nil, the name of a file to use instead of `/usr/lib/aliases'.
218 This file defines aliases to be expanded by the mailer; this is a different
219 feature from that of defining aliases in `.mailrc' to be expanded in Emacs.
220 This variable has no effect unless your system uses sendmail as its mailer.")
221
222 ;;;###autoload
223 (defvar message-personal-alias-file "~/.mailrc"
224   "*If non-nil, the name of the user's personal mail alias file.
225 This file typically should be in same format as the `.mailrc' file used by
226 the `Mail' or `mailx' program.
227 This file need not actually exist.")
228
229 (defvar message-setup-hook nil
230   "Normal hook, run each time a new outgoing message is initialized.
231 The function `message-setup' runs this hook.")
232
233 (defvar message-header-setup-hook nil
234   "Hook called narrowed to the headers when setting up a message buffer.")
235
236 ;;;###autoload
237 (defvar message-citation-line-function 'message-insert-citation-line
238   "*Function called to insert the \"Whomever writes:\" line.")
239
240 (defvar message-aliases t
241   "Alist of mail address aliases.
242 If t, initialized from your mail aliases file.
243 \(The file's name is normally `~/.mailrc', but your MAILRC environment
244 variable can override that name.)
245 The alias definitions in the file have this form:
246     alias ALIAS MEANING")
247
248 (defvar message-alias-modtime nil
249   "The modification time of your mail alias file when it was last examined.")
250
251 ;;;###autoload
252 (defvar message-yank-prefix "> "
253   "*Prefix inserted on the lines of yanked messages.
254 nil means use indentation.")
255
256 (defvar message-indentation-spaces 3
257   "*Number of spaces to insert at the beginning of each cited line.
258 Used by `message-yank-original' via `message-yank-cite'.")
259
260 ;;;###autoload
261 (defvar message-cite-function 'message-cite-original
262   "*Function for citing an original message.")
263
264 ;;;###autoload
265 (defvar message-indent-citation-function 'message-indent-citation
266   "*Function for modifying a citation just inserted in the mail buffer.
267 This can also be a list of functions.  Each function can find the
268 citation between (point) and (mark t).  And each function should leave
269 point and mark around the citation text as modified.")
270
271 (defvar message-abbrevs-loaded nil)
272
273 (autoload 'build-mail-aliases "mailalias"
274   "Read mail aliases from user's personal aliases file and set `mail-aliases'."
275   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 message-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 message-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-s" '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-s  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 message-header-separator)
623                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
624                                 paragraph-start))
625   (setq paragraph-separate (concat (regexp-quote message-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 Followup-To 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" message-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" message-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       ;; This is like exchange-point-and-mark, but doesn't activate the mark.
875       ;; It is cleaner to avoid activation, even though the command
876       ;; loop would deactivate the mark because we inserted text.
877       (goto-char (prog1 (mark t)
878                    (set-marker (mark-marker) (point) (current-buffer))))
879       (unless (bolp)
880         (insert ?\n))
881       (unless modified
882         (setq message-checksum (message-checksum))))))
883
884 (defun message-cite-original ()    
885   (let ((start (point))
886         (functions 
887          (when message-indent-citation-function
888            (if (listp message-indent-citation-function)
889                message-indent-citation-function
890              (list message-indent-citation-function)))))
891     (unless (consp arg)
892       (goto-char start)
893       (let ((message-indentation-spaces
894              (if arg (prefix-numeric-value arg)
895                message-indentation-spaces)))
896         (while functions
897           (funcall (pop functions)))))
898     (when message-citation-line-function
899       (unless (bolp)
900         (insert "\n"))
901       (funcall message-citation-line-function))))
902
903 (defun message-insert-citation-line ()
904   "Function that inserts a simple citation line."
905   (when message-reply-headers
906     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
907
908 (defun message-position-on-field (header &rest afters)
909   (let ((case-fold-search t))
910     (save-restriction
911       (narrow-to-region
912        (goto-char (point-min))
913        (progn
914          (re-search-forward 
915           (concat "^" (regexp-quote message-header-separator) "$"))
916          (match-beginning 0)))
917       (goto-char (point-min))
918       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
919           (progn
920             (re-search-forward "^[^ \t]" nil 'move)
921             (beginning-of-line)
922             (skip-chars-backward "\n")
923             t)
924         (while (and afters
925                     (not (re-search-forward 
926                           (concat "^" (regexp-quote (car afters)) ":")
927                           nil t)))
928           (pop afters))
929         (when afters
930           (re-search-forward "^[^ \t]" nil 'move)
931           (beginning-of-line))
932         (insert header ": \n")
933         (forward-char -1)
934         nil))))
935
936 (defun message-remove-signature ()
937   "Remove the signature from the text between point and mark.
938 The text will also be indented the normal way.
939 This function can be used in `message-citation-hook', for instance."
940   (save-excursion
941     (let ((start (point))
942           mark)
943     (if (not (re-search-forward message-signature-separator (mark t) t))
944         ;; No signature here, so we just indent the cited text.
945         (message-indent-citation)
946       ;; Find the last non-empty line.
947       (forward-line -1)
948       (while (looking-at "[ \t]*$")
949         (forward-line -1))
950       (forward-line 1)
951       (setq mark (set-marker (make-marker) (point)))
952       (goto-char start)
953       (message-indent-citation)
954       ;; Enable undoing the deletion.
955       (undo-boundary)
956       (delete-region mark (mark t))
957       (set-marker mark nil)))))
958
959 \f
960
961 ;;;
962 ;;; Sending messages
963 ;;;
964
965 (defun message-send-and-exit (&optional arg)
966   "Send message like `message-send', then, if no errors, exit from mail buffer.
967 Prefix arg means don't delete this window."
968   (interactive "P")
969   (message-send)
970   ;(message-bury arg)
971   )
972
973 (defun message-dont-send (&optional arg)
974   "Don't send the message you have been editing.
975 Prefix arg means don't delete this window."
976   (interactive "P")
977   (message-bury arg))
978
979 (defun message-bury (arg)
980   "Bury this mail buffer."
981   (let ((newbuf (other-buffer (current-buffer))))
982     (bury-buffer (current-buffer))
983     (if (and (fboundp 'frame-parameters)
984              (cdr (assq 'dedicated (frame-parameters)))
985              (not (null (delq (selected-frame) (visible-frame-list)))))
986         (delete-frame (selected-frame))
987       (switch-to-buffer newbuf))))
988
989 (defun message-send (&optional arg)
990   "Send the message in the current buffer.
991 If `message-interactive' is non-nil, wait for success indication
992 or error messages, and inform user.
993 Otherwise any failure is reported in a message back to
994 the user from the mailer."
995   (interactive "P")
996   (when (if buffer-file-name
997             (y-or-n-p (format "Send buffer contents as %s message? "
998                               (if (message-mail-p)
999                                   (if (message-news-p) "mail and news" "mail")
1000                                 "news")))
1001           (or (buffer-modified-p)
1002               (y-or-n-p "No changes in the buffer; really send? ")))
1003     ;; Make it possible to undo the coming changes.
1004     (undo-boundary)
1005     (run-hooks 'message-send-hook)
1006     (message "Sending...")
1007     (when (and (or (not (message-news-p))
1008                    (and (or (not (memq 'news message-sent-message-via))
1009                             (y-or-n-p
1010                              "Already sent message via news; resend? "))
1011                         (funcall message-send-news-function arg)))
1012                (or (not (message-mail-p))
1013                    (and (or (not (memq 'mail message-sent-message-via))
1014                             (y-or-n-p
1015                              "Already sent message via mail; resend? "))
1016                         (funcall message-send-mail-function arg))))
1017       (message-do-fcc)
1018       (run-hooks 'message-sent-hook)
1019       (message "Sending...done")
1020       ;; If buffer has no file, mark it as unmodified and delete autosave.
1021       (unless buffer-file-name
1022         (set-buffer-modified-p nil)
1023         (delete-auto-save-file-if-necessary t))
1024       ;; Now perform actions on successful sending.
1025       (let ((actions message-send-actions))
1026         (while actions
1027           (condition-case nil
1028               (apply (caar actions) (cdar actions))
1029             (error))
1030           (pop actions))))))
1031
1032 (defun message-send-mail (&optional arg)
1033   (require 'mail-utils)
1034   (let ((errbuf (if message-interactive
1035                     (generate-new-buffer " sendmail errors")
1036                   0))
1037         (tembuf (generate-new-buffer " message temp"))
1038         (case-fold-search nil)
1039         (news (message-news-p))
1040         (resend-to-addresses (mail-fetch-field "resent-to"))
1041         delimline
1042         (mailbuf (current-buffer)))
1043     (save-restriction
1044       (message-narrow-to-headers)
1045       ;; Insert some headers.
1046       (message-generate-headers message-required-mail-headers)
1047       ;; Let the user do all of the above.
1048       (run-hooks 'message-header-hook))
1049     (unwind-protect
1050         (save-excursion
1051           (set-buffer tembuf)
1052           (erase-buffer)
1053           (insert-buffer-substring mailbuf)
1054           ;; Remove some headers.
1055           (save-restriction
1056             (message-narrow-to-headers)
1057             ;; Remove some headers.
1058             (message-remove-header message-ignored-mail-headers t))
1059           (goto-char (point-max))
1060           ;; require one newline at the end.
1061           (or (= (preceding-char) ?\n)
1062               (insert ?\n))
1063           (when (and news
1064                      (or (mail-fetch-field "cc")
1065                          (mail-fetch-field "to")))
1066             (message-insert-courtesy-copy))
1067           (let ((case-fold-search t))
1068             ;; Change header-delimiter to be what sendmail expects.
1069             (goto-char (point-min))
1070             (re-search-forward
1071              (concat "^" (regexp-quote message-header-separator) "\n"))
1072             (replace-match "\n")
1073             (backward-char 1)
1074             (setq delimline (point-marker))
1075             (sendmail-synch-aliases)
1076             (when message-aliases
1077               (expand-mail-aliases (point-min) delimline))
1078             ;; Insert an extra newline if we need it to work around
1079             ;; Sun's bug that swallows newlines.
1080             (goto-char (1+ delimline))
1081             (when (eval message-mailer-swallows-blank-line)
1082               (newline))
1083             (when message-interactive
1084               (save-excursion
1085                 (set-buffer errbuf)
1086                 (erase-buffer))))
1087           (let ((default-directory "/"))
1088             (apply 'call-process-region
1089                    (append (list (point-min) (point-max)
1090                                  (if (boundp 'sendmail-program)
1091                                      sendmail-program
1092                                    "/usr/lib/sendmail")
1093                                  nil errbuf nil "-oi")
1094                            ;; Always specify who from,
1095                            ;; since some systems have broken sendmails.
1096                            (list "-f" (user-login-name))
1097                            (and message-alias-file
1098                                 (list (concat "-oA" message-alias-file)))
1099                            ;; These mean "report errors by mail"
1100                            ;; and "deliver in background".
1101                            (if (null message-interactive) '("-oem" "-odb"))
1102                            ;; Get the addresses from the message
1103                            ;; unless this is a resend.
1104                            ;; We must not do that for a resend
1105                            ;; because we would find the original addresses.
1106                            ;; For a resend, include the specific addresses.
1107                            (or resend-to-addresses
1108                                '("-t")))))
1109           (when message-interactive
1110             (save-excursion
1111               (set-buffer errbuf)
1112               (goto-char (point-min))
1113               (while (re-search-forward "\n\n* *" nil t)
1114                 (replace-match "; "))
1115               (if (not (zerop (buffer-size)))
1116                   (error "Sending...failed to %s"
1117                          (buffer-substring (point-min) (point-max)))))))
1118       (kill-buffer tembuf)
1119       (when (bufferp errbuf)
1120         (kill-buffer errbuf)))
1121     (set-buffer mailbuf)
1122     (push 'mail message-sent-message-via)))
1123
1124 (defun message-send-news (&optional arg)
1125   (let ((tembuf (generate-new-buffer " *message temp*"))
1126         (case-fold-search nil)
1127         (method (if (message-functionp message-post-method)
1128                     (funcall message-post-method arg)
1129                   message-post-method))
1130         (messbuf (current-buffer)))
1131     (save-restriction
1132       (message-narrow-to-headers)
1133       ;; Insert some headers.
1134       (message-generate-headers message-required-news-headers)
1135       ;; Let the user do all of the above.
1136       (run-hooks 'message-header-hook))
1137     (when (message-check-news-syntax)
1138       (unwind-protect
1139           (save-excursion
1140             (set-buffer tembuf)
1141             (buffer-disable-undo (current-buffer))
1142             (erase-buffer) 
1143             (insert-buffer-substring messbuf)
1144             ;; Remove some headers.
1145             (save-restriction
1146               (message-narrow-to-headers)
1147               ;; Remove some headers.
1148               (message-remove-header message-ignored-news-headers t))
1149             (goto-char (point-max))
1150             ;; require one newline at the end.
1151             (or (= (preceding-char) ?\n)
1152                 (insert ?\n))
1153             (let ((case-fold-search t))
1154               ;; Remove the delimeter.
1155               (goto-char (point-min))
1156               (re-search-forward
1157                (concat "^" (regexp-quote message-header-separator) "\n"))
1158               (replace-match "\n")
1159               (backward-char 1))
1160             (require (car method))
1161             (funcall (intern (format "%s-open-server" (car method)))
1162                      (cadr method) (cddr method))
1163             (funcall (intern (format "%s-request-post"
1164                                      (car method)))))
1165         (kill-buffer tembuf))
1166       (set-buffer messbuf)
1167       (push 'news message-sent-message-via))))
1168
1169 ;;;
1170 ;;; Header generation & syntax checking.
1171 ;;;
1172
1173 (defun message-check-news-syntax ()
1174   "Check the syntax of the message."
1175   (or
1176    (not message-syntax-checks)
1177    (and 
1178     ;; We narrow to the headers and check them first.
1179     (save-excursion
1180       (save-restriction
1181         (message-narrow-to-headers)
1182         (and 
1183          ;; Check for commands in Subject.
1184          (or 
1185           (message-check-element 'subject-cmsg)
1186           (save-excursion
1187             (if (string-match "^cmsg " (mail-fetch-field "subject"))
1188                 (y-or-n-p
1189                  "The control code \"cmsg \" is in the subject. Really post? ")
1190               t)))
1191          ;; Check for multiple identical headers.
1192          (or (message-check-element 'multiple-headers)
1193              (save-excursion
1194                (let (found)
1195                  (while (and (not found) 
1196                              (re-search-forward "^[^ \t:]+: " nil t))
1197                    (save-excursion
1198                      (or (re-search-forward 
1199                           (concat "^" (setq found
1200                                             (buffer-substring 
1201                                              (match-beginning 0) 
1202                                              (- (match-end 0) 2))))
1203                           nil t)
1204                          (setq found nil))))
1205                  (if found
1206                      (y-or-n-p 
1207                       (format "Multiple %s headers. Really post? " found))
1208                    t))))
1209          ;; Check for Version and Sendsys.
1210          (or (message-check-element 'sendsys)
1211              (save-excursion
1212                (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1213                    (y-or-n-p
1214                     (format "The article contains a %s command. Really post? "
1215                             (buffer-substring (match-beginning 0) 
1216                                               (1- (match-end 0)))))
1217                  t)))
1218          ;; See whether we can shorten Followup-To.
1219          (or (message-check-element 'shorten-followup-to)
1220              (let ((newsgroups (mail-fetch-field "newsgroups"))
1221                    (followup-to (mail-fetch-field "followup-to"))
1222                    to)
1223                (when (and newsgroups (string-match "," newsgroups)
1224                           (not followup-to)
1225                           (not
1226                            (zerop
1227                             (length
1228                              (setq to (completing-read 
1229                                        "Followups to: (default all groups) " 
1230                                        (mapcar (lambda (g) (list g))
1231                                                (cons "poster" 
1232                                                      (message-tokenize-header 
1233                                                       newsgroups)))))))))
1234                  (goto-char (point-min))
1235                  (insert "Followup-To: " to "\n"))))
1236
1237          ;; Check for Approved.
1238          (or (message-check-element 'approved)
1239              (save-excursion
1240                (if (re-search-forward "^Approved:" nil t)
1241                    (y-or-n-p
1242                     "The article contains an Approved header. Really post? ")
1243                  t)))
1244          ;; Check the Message-Id header.
1245          (or (message-check-element 'message-id)
1246              (save-excursion
1247                (let* ((case-fold-search t)
1248                       (message-id (mail-fetch-field "message-id")))
1249                  (or (not message-id)
1250                      (and (string-match "@" message-id)
1251                           (string-match "@[^\\.]*\\." message-id))
1252                      (y-or-n-p
1253                       (format 
1254                        "The Message-ID looks strange: \"%s\". Really post? "
1255                        message-id))))))
1256          ;; Check the Subject header.
1257          (or 
1258           (message-check-element 'subject)
1259           (save-excursion
1260             (let* ((case-fold-search t)
1261                    (subject (mail-fetch-field "subject")))
1262               (or
1263                (and subject
1264                     (not (string-match "\\`[ \t]*\\'" subject)))
1265                (progn
1266                  (message 
1267                   "The subject field is empty or missing.  Posting is denied.")
1268                  nil)))))
1269          ;; Check the From header.
1270          (or (message-check-element 'from)
1271              (save-excursion
1272                (let* ((case-fold-search t)
1273                       (from (mail-fetch-field "from")))
1274                  (cond
1275                   ((not from)
1276                    (message "There is no From line.  Posting is denied.")
1277                    nil)
1278                   ((not (string-match "@[^\\.]*\\." from))
1279                    (message
1280                     "Denied posting -- the From looks strange: \"%s\"." from)
1281                    nil)
1282                   ((string-match "(.*).*(.*)" from)
1283                    (message
1284                     "Denied posting -- the From header looks strange: \"%s\"." 
1285                     from)
1286                    nil)
1287                   (t t))))))))
1288     ;; Check for long lines.
1289     (or (message-check-element 'long-lines)
1290         (save-excursion
1291           (goto-char (point-min))
1292           (re-search-forward
1293            (concat "^" (regexp-quote mail-header-separator) "$"))
1294           (while (and
1295                   (progn
1296                     (end-of-line)
1297                     (< (current-column) 80))
1298                   (zerop (forward-line 1))))
1299           (or (bolp)
1300               (eobp)
1301               (y-or-n-p
1302                "You have lines longer than 79 characters.  Really post? "))))
1303     ;; Check whether the article is empty.
1304     (or (message-check-element 'empty)
1305         (save-excursion
1306           (goto-char (point-min))
1307           (re-search-forward
1308            (concat "^" (regexp-quote mail-header-separator) "$"))
1309           (forward-line 1)
1310           (or (re-search-forward "[^ \n\t]" nil t)
1311               (y-or-n-p "Empty article.  Really post?"))))
1312     ;; Check for control characters.
1313     (or (message-check-element 'control-chars)
1314         (save-excursion
1315           (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1316               (y-or-n-p 
1317                "The article contains control characters. Really post? ")
1318             t)))
1319     ;; Check excessive size.
1320     (or (message-check-element 'size)
1321         (if (> (buffer-size) 60000)
1322             (y-or-n-p
1323              (format "The article is %d octets long. Really post? "
1324                      (buffer-size)))
1325           t))
1326     ;; Check whether any new text has been added.
1327     (or (message-check-element 'new-text)
1328         (not message-checksum)
1329         (not (eq (message-checksum) message-checksum))
1330         (y-or-n-p
1331          "It looks like no new text has been added.  Really post? "))
1332     ;; Check the length of the signature.
1333     (or (message-check-element 'signature)
1334         (progn
1335           (goto-char (point-max))
1336           (if (not (re-search-backward "^-- $" nil t))
1337               t
1338             (if (> (count-lines (point) (point-max)) 5)
1339                 (y-or-n-p
1340                  (format
1341                   "Your .sig is %d lines; it should be max 4.  Really post? "
1342                   (count-lines (point) (point-max))))
1343               t)))))))
1344
1345 ;; Returns non-nil if this type is not to be checked.
1346 (defun message-check-element (type)
1347   (not 
1348    (or (not message-syntax-checks)
1349        (if (listp message-syntax-checks)
1350            (memq type message-syntax-checks)
1351          t))))
1352
1353 (defun message-checksum ()
1354   "Return a \"checksum\" for the current buffer."
1355   (let ((sum 0))
1356     (save-excursion
1357       (while (not (eobp))
1358         (setq sum (logxor sum (following-char)))
1359         (forward-char 1)))
1360     sum))
1361
1362 (defun message-do-fcc ()
1363   "Process Fcc headers in the current buffer."
1364   (let ((case-fold-search t)
1365         list file)
1366     (save-excursion
1367       (save-restriction
1368         (message-narrow-to-headers)
1369         (while (setq file (mail-fetch-field "fcc"))
1370           (push file list)
1371           (message-remove-header "fcc" nil t))
1372         ;; Process FCC operations.
1373         (widen)
1374         (while list
1375           (setq file (pop list))
1376           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
1377               ;; Pipe the article to the program in question.
1378               (call-process-region (point-min) (point-max) shell-file-name
1379                                    nil nil nil "-c" (match-string 1 file))
1380             ;; Save the article.
1381             (setq file (expand-file-name file))
1382             (unless (file-exists-p (file-name-directory file))
1383               (make-directory (file-name-directory file) t))
1384             (if (and message-fcc-handler-function
1385                      (not (eq message-fcc-handler-function 'rmail-output)))
1386                 (funcall message-fcc-handler-function file)
1387               (if (and (file-readable-p file) (mail-file-babyl-p file))
1388                   (rmail-output file 1)
1389                 (let ((mail-use-rfc822 t))
1390                   (rmail-output file 1 t t))))))))))
1391
1392 (defun message-cleanup-headers ()
1393   "Do various automatic cleanups of the headers."
1394   ;; Remove empty lines in the header.
1395   (save-restriction
1396     (message-narrow-to-headers)
1397     (while (re-search-forward "^[ \t]*\n" nil t)
1398       (replace-match "" t t)))
1399
1400   ;; Correct Newsgroups and Followup-To headers: change sequence of
1401   ;; spaces to comma and eliminate spaces around commas.  Eliminate
1402   ;; embedded line breaks.
1403   (goto-char (point-min))
1404   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
1405     (save-restriction
1406       (narrow-to-region
1407        (point)
1408        (if (re-search-forward "^[^ \t]" nil t)
1409            (match-beginning 0)
1410          (forward-line 1)
1411          (point)))
1412       (goto-char (point-min))
1413       (while (re-search-forward "\n[ \t]+" nil t)
1414         (replace-match " " t t))        ;No line breaks (too confusing)
1415       (goto-char (point-min))
1416       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
1417         (replace-match "," t t))
1418       (goto-char (point-min))
1419       ;; Remove trailing commas.
1420       (when (re-search-forward ",+$" nil t)
1421         (replace-match "" t t)))))
1422
1423 (defun message-make-date ()
1424   "Make a valid data header."
1425   (let ((now (current-time)))
1426     (timezone-make-date-arpa-standard 
1427      (current-time-string now) (current-time-zone now))))
1428
1429 (defun message-make-message-id ()
1430   "Make a unique Message-ID."
1431   (concat "<" (message-unique-id) 
1432           (let ((psubject (save-excursion (mail-fetch-field "subject"))))
1433             (if (and message-reply-headers
1434                      (mail-header-references message-reply-headers)
1435                      (mail-header-subject message-reply-headers)
1436                      psubject
1437                      (mail-header-subject message-reply-headers)
1438                      (not (string= 
1439                            (message-strip-subject-re
1440                             (mail-header-subject message-reply-headers))
1441                            (message-strip-subject-re psubject))))
1442                 "_-_" ""))
1443           "@" (message-make-fqdm) ">"))
1444
1445 (defvar message-unique-id-char nil)
1446
1447 ;; If you ever change this function, make sure the new version
1448 ;; cannot generate IDs that the old version could.
1449 ;; You might for example insert a "." somewhere (not next to another dot
1450 ;; or string boundary), or modify the "fsf" string.
1451 (defun message-unique-id ()
1452   ;; Don't use microseconds from (current-time), they may be unsupported.
1453   ;; Instead we use this randomly inited counter.
1454   (setq message-unique-id-char
1455         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
1456            ;; (current-time) returns 16-bit ints,
1457            ;; and 2^16*25 just fits into 4 digits i base 36.
1458            (* 25 25)))
1459   (let ((tm (current-time)))
1460     (concat
1461      (if (memq system-type '(ms-dos emx vax-vms))
1462          (let ((user (downcase (user-login-name))))
1463            (while (string-match "[^a-z0-9_]" user)
1464              (aset user (match-beginning 0) ?_))
1465            user)
1466        (message-number-base36 (user-uid) -1))
1467      (message-number-base36 (+ (car   tm) 
1468                                (lsh (% message-unique-id-char 25) 16)) 4)
1469      (message-number-base36 (+ (nth 1 tm)
1470                                (lsh (/ message-unique-id-char 25) 16)) 4)
1471      ;; Append the newsreader name, because while the generated
1472      ;; ID is unique to this newsreader, other newsreaders might
1473      ;; otherwise generate the same ID via another algorithm.
1474      ".fsf")))
1475
1476 (defun message-number-base36 (num len)
1477   (if (if (< len 0) (<= num 0) (= len 0))
1478       ""
1479     (concat (message-number-base36 (/ num 36) (1- len))
1480             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
1481                                   (% num 36))))))
1482
1483 (defun message-make-organization ()
1484   "Make an Organization header."
1485   (let* ((organization 
1486           (or (getenv "ORGANIZATION")
1487               (when message-user-organization
1488                 (if (message-functionp message-user-organization)
1489                     (funcall message-user-organization)
1490                   message-user-organization)))))
1491     (save-excursion
1492       (message-set-work-buffer)
1493       (cond ((stringp message-user-organization)
1494              (insert message-user-organization))
1495             ((and (eq t message-user-organization)
1496                   message-user-organization-file
1497                   (file-exists-p message-user-organization-file))
1498              (insert-file-contents message-user-organization-file)))
1499       (goto-char (point-min))
1500       (when (re-search-forward "[ \t\n]*" nil t)
1501         (replace-match "" t t))
1502       (unless (zerop (buffer-size))
1503         (buffer-string)))))
1504
1505 (defun message-make-lines ()
1506   "Count the number of lines and return numeric string."
1507   (save-excursion
1508     (save-restriction
1509       (widen)
1510       (goto-char (point-min))
1511       (re-search-forward 
1512        (concat "^" (regexp-quote message-header-separator) "$"))
1513       (forward-line 1)
1514       (int-to-string (count-lines (point) (point-max))))))
1515
1516 (defun message-make-in-reply-to ()
1517   "Return the In-Reply-To header for this message."
1518   (when message-reply-headers
1519     (let ((from (mail-header-from message-reply-headers))
1520           (date (mail-header-date message-reply-headers)))
1521       (when from
1522         (let ((stop-pos 
1523                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
1524           (concat (if stop-pos (substring from 0 stop-pos) from)
1525                   "'s message of " 
1526                   (if (or (not date) (string= date ""))
1527                       "(unknown date)" date)))))))
1528
1529 (defun message-make-distribution ()
1530   "Make a Distribution header."
1531   (let ((orig-distribution (message-fetch-reply-field "distribution")))
1532     (cond ((message-functionp message-distribution-function)
1533            (funcall message-distribution-function))
1534           (t orig-distribution))))
1535
1536 (defun message-make-expires ()
1537   "Return an Expires header based on `message-expires'."
1538   (let ((current (current-time))
1539         (future (* 1.0 message-expires 60 60 24)))
1540     ;; Add the future to current.
1541     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
1542     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
1543     ;; Return the date in the future in UT.
1544     (timezone-make-date-arpa-standard 
1545      (current-time-string current) (current-time-zone current) '(0 "UT"))))
1546
1547 (defun message-make-path ()
1548   "Return uucp path."
1549   (let ((login-name (user-login-name)))
1550     (cond ((null message-user-path)
1551            (concat (system-name) "!" login-name))
1552           ((stringp message-user-path)
1553            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
1554            (concat message-user-path "!" login-name))
1555           (t login-name))))
1556
1557 (defun message-make-from ()
1558   "Make a From header."
1559   (let* ((login (message-make-address))
1560          (fullname (user-full-name)))
1561     (when (string= fullname "&")
1562       (setq fullname (user-login-name)))
1563     (save-excursion
1564       (message-set-work-buffer)
1565       (cond 
1566        ((eq message-from-style 'angles)
1567         (insert fullname)
1568         (goto-char (point-min))
1569         ;; Look for a character that cannot appear unquoted
1570         ;; according to RFC 822.
1571         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
1572           ;; Quote fullname, escaping specials.
1573           (goto-char (point-min))
1574           (insert "\"")
1575           (while (re-search-forward "[\"\\]" nil 1)
1576             (replace-match "\\\\\\&" t))
1577           (insert "\""))
1578         (insert " <" login ">"))
1579        ((eq message-from-style 'parens)
1580         (insert login " (")
1581         (let ((fullname-start (point)))
1582           (insert fullname)
1583           (goto-char fullname-start)
1584           ;; RFC 822 says \ and nonmatching parentheses
1585           ;; must be escaped in comments.
1586           ;; Escape every instance of ()\ ...
1587           (while (re-search-forward "[()\\]" nil 1)
1588             (replace-match "\\\\\\&" t))
1589           ;; ... then undo escaping of matching parentheses,
1590           ;; including matching nested parentheses.
1591           (goto-char fullname-start)
1592           (while (re-search-forward 
1593                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
1594                     nil 1)
1595             (replace-match "\\1(\\3)" t)
1596             (goto-char fullname-start)))
1597         (insert ")"))
1598        ((null message-from-style)
1599         (insert login "\n")))
1600       (buffer-string))))
1601
1602 (defun message-make-sender ()
1603   "Return the \"real\" user address.
1604 This function tries to ignore all user modifications, and 
1605 give as trustworthy answer as possible."
1606   (concat (user-login-name) "@" (system-name)))
1607
1608 (defun message-make-address ()
1609   "Make the address of the user."
1610   (or user-mail-address
1611       (concat (user-login-name) "@" (message-make-domain))))
1612
1613 (defun message-make-fqdm ()
1614   "Return user's fully qualified domain name."
1615   (let ((system-name (system-name)))
1616     (cond 
1617      ((string-match "[^.]\\.[^.]" system-name)
1618       ;; `system-name' returned the right result.
1619       system-name)
1620      ;; We try `user-mail-address' as a backup.
1621      ((string-match "@\\(\\W+\\)\\(\\'\\|\\W\\)" user-mail-address)
1622       (match-string 1 user-mail-address))
1623      (t
1624       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
1625
1626 (defun message-make-host-name ()
1627   "Return the name of the host."
1628   (let ((fqdm (message-make-fqdm)))
1629     (string-match "^[^.]+\\." fqdm)
1630     (substring fqdm 0 (1- (match-end 0)))))
1631
1632 (defun message-make-domain ()
1633   "Return the domain name."
1634   (or mail-host-address
1635       (message-make-fqdm)))
1636
1637 (defun message-generate-headers (headers)
1638   "Prepare article HEADERS.
1639 Headers already prepared in the buffer are not modified."
1640   (save-restriction
1641     (message-narrow-to-headers)
1642     (let* ((Date (message-make-date))
1643            (Message-ID (message-make-message-id))
1644            (Organization (message-make-organization))
1645            (From (message-make-from))
1646            (Path (message-make-path))
1647            (Subject nil)
1648            (Newsgroups nil)
1649            (In-Reply-To (message-make-in-reply-to))
1650            (To nil)
1651            (Distribution (message-make-distribution))
1652            (Lines (message-make-lines))
1653            (X-Newsreader message-newsreader)
1654            (X-Mailer message-mailer)
1655            (Expires (message-make-expires))
1656            (case-fold-search t)
1657            header value elem)
1658       ;; First we remove any old generated headers.
1659       (let ((headers message-deletable-headers))
1660         (while headers
1661           (goto-char (point-min))
1662           (and (re-search-forward 
1663                 (concat "^" (symbol-name (car headers)) ": *") nil t)
1664                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
1665                (message-delete-line))
1666           (pop headers)))
1667       ;; Go through all the required headers and see if they are in the
1668       ;; articles already. If they are not, or are empty, they are
1669       ;; inserted automatically - except for Subject, Newsgroups and
1670       ;; Distribution. 
1671       (while headers
1672         (goto-char (point-min))
1673         (setq elem (pop headers))
1674         (if (consp elem)
1675             (if (eq (car elem) 'optional)
1676                 (setq header (cdr elem))
1677               (setq header (car elem)))
1678           (setq header elem))
1679         (when (or (not (re-search-forward 
1680                         (concat "^" (downcase (symbol-name header)) ":") 
1681                         nil t))
1682                   (progn
1683                     ;; The header was found. We insert a space after the
1684                     ;; colon, if there is none.
1685                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
1686                     ;; Find out whether the header is empty...
1687                     (looking-at "[ \t]*$")))
1688           ;; So we find out what value we should insert.
1689           (setq value
1690                 (cond 
1691                  ((and (consp elem) (eq (car elem) 'optional))
1692                   ;; This is an optional header.  If the cdr of this
1693                   ;; is something that is nil, then we do not insert
1694                   ;; this header.
1695                   (setq header (cdr elem))
1696                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
1697                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
1698                  ((consp elem)
1699                   ;; The element is a cons.  Either the cdr is a
1700                   ;; string to be inserted verbatim, or it is a
1701                   ;; function, and we insert the value returned from
1702                   ;; this function.
1703                   (or (and (stringp (cdr elem)) (cdr elem))
1704                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
1705                  ((and (boundp header) (symbol-value header))
1706                   ;; The element is a symbol.  We insert the value
1707                   ;; of this symbol, if any.
1708                   (symbol-value header))
1709                  (t
1710                   ;; We couldn't generate a value for this header,
1711                   ;; so we just ask the user.
1712                   (read-from-minibuffer
1713                    (format "Empty header for %s; enter value: " header)))))
1714           ;; Finally insert the header.
1715           (when (and value 
1716                      (not (equal value "")))
1717             (save-excursion
1718               (if (bolp)
1719                   (progn
1720                     ;; This header didn't exist, so we insert it.
1721                     (goto-char (point-max))
1722                     (insert (symbol-name header) ": " value "\n")
1723                     (forward-line -1))
1724                 ;; The value of this header was empty, so we clear
1725                 ;; totally and insert the new value.
1726                 (delete-region (point) (message-point-at-eol))
1727                 (insert value))
1728               ;; Add the deletable property to the headers that require it.
1729               (and (memq header message-deletable-headers)
1730                    (progn (beginning-of-line) (looking-at "[^:]+: "))
1731                    (add-text-properties 
1732                     (point) (match-end 0)
1733                     '(message-deletable t face italic) (current-buffer)))))))
1734       ;; Insert new Sender if the From is strange. 
1735       (let ((from (mail-fetch-field "from"))
1736             (sender (mail-fetch-field "sender"))
1737             (secure-sender (message-make-sender)))
1738         (when (and from 
1739                    (not (message-check-element 'sender))
1740                    (not (string=
1741                          (downcase
1742                           (cadr (mail-extract-address-components from)))
1743                          (downcase secure-sender)))
1744                    (or (null sender)
1745                        (not 
1746                         (string=
1747                          (downcase
1748                           (cadr (mail-extract-address-components sender)))
1749                          (downcase secure-sender)))))
1750           (goto-char (point-min))    
1751           ;; Rename any old Sender headers to Original-Sender.
1752           (when (re-search-forward "^Sender:" nil t)
1753             (beginning-of-line)
1754             (insert "Original-")
1755             (beginning-of-line))
1756           (insert "Sender: " secure-sender "\n"))))))
1757
1758 (defun message-insert-courtesy-copy ()
1759   "Insert a courtesy message in mail copies of combined messages."
1760   (save-excursion
1761     (save-restriction
1762       (message-narrow-to-headers)
1763       (let ((newsgroups (mail-fetch-field "newsgroups")))
1764         (when newsgroups
1765           (goto-char (point-max))
1766           (insert "Posted-To: " newsgroups "\n"))))
1767     (forward-line 1)
1768     (insert message-courtesy-message)))
1769     
1770 ;;;
1771 ;;; Setting up a message buffer
1772 ;;;
1773
1774 (defun message-fill-header (header value)
1775   (let ((begin (point))
1776         (fill-column 78)
1777         (fill-prefix "\t"))
1778     (insert (capitalize (symbol-name header))
1779             ": "
1780             (if (consp value) (car value) value)
1781             "\n")
1782     (fill-region-as-paragraph begin (point))))
1783
1784 (defun sendmail-synch-aliases ()
1785   (let ((modtime (nth 5 (file-attributes message-personal-alias-file))))
1786     (or (equal message-alias-modtime modtime)
1787         (setq message-alias-modtime modtime
1788               message-aliases t))))
1789
1790 (defun message-position-point ()
1791   "Move point to where the user probably wants to find it."
1792   (message-narrow-to-headers)
1793   (cond 
1794    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
1795     (search-backward ":" )
1796     (widen)
1797     (forward-char 1)
1798     (if (= (following-char) ? )
1799         (forward-char 1)
1800       (insert " ")))
1801    (t
1802     (goto-char (point-max))
1803     (widen)
1804     (forward-line 1)
1805     (unless (looking-at "$")
1806       (forward-line 2)))
1807    (sit-for 0)))
1808
1809 (defun message-pop-to-buffer (name)
1810   "Pop to buffer NAME, and warn if it already exists and is modified."
1811   (let ((buffer (get-buffer name)))
1812     (if (and buffer
1813              (buffer-name buffer))
1814         (progn
1815           (set-buffer (pop-to-buffer buffer))
1816           (when (and (buffer-modified-p)
1817                      (not (y-or-n-p
1818                            "Message already being composed; erase? ")))
1819             (error "Message being composed")))
1820       (set-buffer (pop-to-buffer name)))
1821     (erase-buffer)
1822     (message-mode)))
1823
1824 (defun message-setup (headers &optional replybuffer actions)
1825   (sendmail-synch-aliases)
1826   (when (eq message-aliases t)
1827     (setq message-aliases nil)
1828     (when (file-exists-p message-personal-alias-file)
1829       (build-mail-aliases)))
1830   (setq message-send-actions actions)
1831   (setq message-reply-buffer replybuffer)
1832   (goto-char (point-min))
1833   ;; Insert all the headers.
1834   (mail-header-format 
1835    (let ((h headers)
1836          (alist message-header-format-alist))
1837      (while h
1838        (unless (assq (caar h) message-header-format-alist)
1839          (push (list (caar h)) alist))
1840        (pop h))
1841      alist)
1842    headers)
1843   (forward-line -1)
1844   (when message-default-headers
1845     (insert message-default-headers))
1846   (when (and (message-news-p)
1847              message-default-news-headers)
1848     (when message-generate-headers-first
1849       (message-generate-headers message-required-news-headers))
1850     (insert message-default-news-headers))
1851   (when (and (message-mail-p)
1852              message-default-mail-headers)
1853     (when message-generate-headers-first
1854       (message-generate-headers message-required-mail-headers))
1855     (insert message-default-mail-headers))
1856   (insert message-header-separator "\n")
1857   (message-insert-signature)
1858   (message-set-auto-save-file-name)
1859   (save-restriction
1860     (message-narrow-to-headers)
1861     (run-hooks 'message-header-setup-hook))
1862   (set-buffer-modified-p nil)
1863   (run-hooks 'message-setup-hook)
1864   (message-position-point)
1865   (undo-boundary))
1866
1867 (defun message-set-auto-save-file-name ()
1868   "Associate the message buffer with a file in the drafts directory."
1869   (when message-autosave-directory
1870     (unless (file-exists-p message-autosave-directory)
1871       (make-directory message-autosave-directory t))
1872     (let ((name (make-temp-name
1873                  (concat (file-name-as-directory message-autosave-directory)
1874                          "msg."))))
1875       (setq buffer-auto-save-file-name
1876             (save-excursion
1877               (prog1
1878                   (progn
1879                     (set-buffer (get-buffer-create " *draft tmp*"))
1880                     (setq buffer-file-name name)
1881                     (make-auto-save-file-name))
1882                 (kill-buffer (current-buffer)))))
1883       (clear-visited-file-modtime))))
1884
1885 \f
1886
1887 ;;;
1888 ;;; Commands for interfacing with message
1889 ;;;
1890
1891 ;;;###autoload
1892 (defun message-mail (&optional to subject)
1893   "Start editing a mail message to be sent."
1894   (interactive)
1895   (message-pop-to-buffer "*mail message*")
1896   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
1897
1898 ;;;###autoload
1899 (defun message-news (&optional newsgroups subject)
1900   "Start editing a news article to be sent."
1901   (interactive)
1902   (message-pop-to-buffer "*news message*")
1903   (message-setup `((Newsgroups . ,(or newsgroups "")) 
1904                    (Subject . ,(or subject "")))))
1905
1906 ;;;###autoload
1907 (defun message-reply (&optional to-address wide)
1908   "Start editing a reply to the article in the current buffer."
1909   (interactive)
1910   (let ((cur (current-buffer))
1911         from subject date reply-to message-of to cc
1912         references message-id sender follow-to sendto elt new-cc new-to
1913         mct never-mct gnus-warning)
1914     (save-restriction
1915       (narrow-to-region
1916        (goto-char (point-min))
1917        (if (search-forward "\n\n" nil t)
1918            (1- (point))
1919          (point-max)))
1920       ;; Allow customizations to have their say.
1921       (if (not wide)
1922           ;; This is a regular reply.
1923           (if (message-functionp message-reply-to-function)
1924               (setq follow-to (funcall message-reply-to-function)))
1925         ;; This is a followup.
1926         (if (message-functionp message-wide-reply-to-function)
1927             (save-excursion
1928               (setq follow-to
1929                     (funcall message-wide-reply-to-function)))))
1930       ;; Find all relevant headers we need.
1931       (setq from (mail-fetch-field "from")
1932             date (mail-fetch-field "date") 
1933             sender (mail-fetch-field "sender")
1934             subject (or (mail-fetch-field "subject") "none")
1935             to (mail-fetch-field "to")
1936             cc (mail-fetch-field "cc")
1937             mct (mail-fetch-field "mail-copies-to")
1938             reply-to (mail-fetch-field "reply-to")
1939             references (mail-fetch-field "references")
1940             message-id (mail-fetch-field "message-id"))
1941       ;; Remove any (buggy) Re:'s that are present and make a
1942       ;; proper one.
1943       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
1944         (setq subject (substring subject (match-end 0))))
1945       (setq subject (concat "Re: " subject))
1946
1947       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
1948                  (string-match "<[^>]+>" gnus-warning))
1949         (setq message-id (match-string 0 gnus-warning)))
1950             
1951       ;; Handle special values of Mail-Copies-To.
1952       (when mct
1953         (cond ((equal (downcase mct) "never")
1954                (setq never-mct t)
1955                (setq mct nil))
1956               ((equal (downcase mct) "always")
1957                (setq mct (or reply-to from)))))
1958
1959       (unless follow-to
1960         (if (or (not wide)
1961                 to-address)
1962             (setq follow-to (list (cons 'To (or to-address reply-to from))))
1963           (let (ccalist)
1964             (save-excursion
1965               (message-set-work-buffer)
1966               (unless never-mct
1967                 (insert (or reply-to from "")))
1968               (insert 
1969                (if (bolp) "" ", ") (or to "")
1970                (if mct (concat (if (bolp) "" ", ") mct) "")
1971                (if cc (concat (if (bolp) "" ", ") cc) ""))
1972               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
1973               (insert (prog1 (rmail-dont-reply-to (buffer-string))
1974                         (erase-buffer)))
1975               (goto-char (point-min))
1976               (setq ccalist
1977                     (mapcar
1978                      (lambda (addr)
1979                        (cons (mail-strip-quoted-names addr) addr))
1980                      (nreverse (mail-parse-comma-list))))
1981               (let ((s ccalist))
1982                 (while s
1983                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
1984             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
1985             (when ccalist
1986               (push (cons 'Cc
1987                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
1988                     follow-to)))))
1989       (widen))
1990
1991     (message-pop-to-buffer "*mail message*")
1992
1993     (setq message-reply-headers
1994           (vector 0 subject from date message-id references 0 0 ""))
1995
1996     (message-setup
1997      `((Subject . ,subject)
1998        ,@follow-to 
1999        (References . ,(concat (or references "") (and references " ")
2000                               (or message-id ""))))
2001      cur)))
2002
2003 ;;;###autoload
2004 (defun message-wide-reply (&optional to-address)
2005   (interactive)
2006   (message-reply to-address t))
2007
2008 ;;;###autoload
2009 (defun message-followup ()
2010   (interactive)
2011   (let ((cur (current-buffer))
2012         from subject date message-of reply-to mct
2013         references message-id follow-to sendto elt 
2014         followup-to distribution newsgroups gnus-warning)
2015     (save-restriction
2016       (narrow-to-region
2017        (goto-char (point-min))
2018        (if (search-forward "\n\n" nil t)
2019            (1- (point))
2020          (point-max)))
2021       (when (message-functionp message-followup-to-function)
2022         (setq follow-to
2023               (funcall message-followup-to-function)))
2024       (setq from (mail-fetch-field "from")
2025             date (mail-fetch-field "date") 
2026             subject (or (mail-fetch-field "subject") "none")
2027             references (mail-fetch-field "references")
2028             message-id (mail-fetch-field "message-id")
2029             followup-to (mail-fetch-field "followup-to")
2030             newsgroups (mail-fetch-field "newsgroups")
2031             reply-to (mail-fetch-field "reply-to")
2032             distribution (mail-fetch-field "distribution")
2033             mct (mail-fetch-field "mail-copies-to"))
2034       (when (and (setq gnus-warning (mail-fetch-field "gnus-warning"))
2035                  (string-match "<[^>]+>" gnus-warning))
2036         (setq message-id (match-string 0 gnus-warning)))
2037       ;; Remove bogus distribution.
2038       (and (stringp distribution)
2039            (string-match "world" distribution)
2040            (setq distribution nil))
2041       ;; Remove any (buggy) Re:'s that are present and make a
2042       ;; proper one.
2043       (when (string-match "^[ \t]*[Re][Ee]:[ \t]*" subject)
2044         (setq subject (substring subject (match-end 0))))
2045       (setq subject (concat "Re: " subject))
2046       (widen))
2047
2048     (message-pop-to-buffer "*news message*")
2049
2050     (message-setup
2051      `((Subject . ,subject)
2052        ,@(cond 
2053           (follow-to follow-to)
2054           ((and followup-to message-use-followup-to)
2055            (list
2056             (cond 
2057              ((equal (downcase followup-to) "poster")
2058               (if (or (eq message-use-followup-to 'use)
2059                       (y-or-n-p "Use Followup-To \"poster\"? "))
2060                   (cons 'To (or reply-to from ""))
2061                 (cons 'Newsgroups newsgroups)))
2062              (t
2063               (if (or (equal followup-to newsgroups)
2064                       (not (eq message-use-followup-to 'ask))
2065                       (y-or-n-p (format "Use Followup-To %s? " followup-to)))
2066                   (cons 'Newsgroups followup-to)
2067                 (cons 'Newsgroups newsgroups))))))
2068           (t
2069            `((Newsgroups . ,newsgroups))))
2070        ,@(and distribution (list (cons 'Distribution distribution)))
2071        (References . ,(concat (or references "") (and references " ")
2072                               (or message-id "")))
2073        ,@(when (and mct
2074                     (not (equal (downcase mct) "never")))
2075            (list (cons 'Cc (if (equal (downcase mct) "always")
2076                                (or reply-to from "")
2077                              mct)))))
2078      cur)))
2079
2080 ;;;###autoload
2081 (defun message-cancel-news ()
2082   "Cancel an article you posted."
2083   (interactive)
2084   (unless (message-news-p)
2085     (error "This is not a news article; canceling is impossible"))
2086   (when (yes-or-no-p "Do you really want to cancel this article? "))
2087   (let (from newsgroups message-id distribution buf)
2088     (save-excursion
2089       ;; Get header info. from original article.
2090       (save-restriction
2091         (message-narrow-to-head)
2092         (setq from (mail-fetch-field "from")
2093               newsgroups (mail-fetch-field "newsgroups")
2094               message-id (mail-fetch-field "message-id")
2095               distribution (mail-fetch-field "distribution")))
2096       ;; Make sure that this article was written by the user.
2097       (unless (string-equal
2098                (downcase (mail-strip-quoted-names from))
2099                (downcase (message-make-address)))
2100         (error "This article is not yours"))
2101       ;; Make control message.
2102       (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2103       (buffer-disable-undo (current-buffer))
2104       (erase-buffer)
2105       (insert "Newsgroups: " newsgroups "\n"
2106               "From: " (message-make-from) "\n"
2107               "Subject: cmsg cancel " message-id "\n"
2108               "Control: cancel " message-id "\n"
2109               (if distribution
2110                   (concat "Distribution: " distribution "\n")
2111                 "")
2112               message-header-separator "\n"
2113               "This is a cancel message from " from ".\n")
2114       (message "Canceling your article...")
2115       (funcall message-send-news-function)
2116       (message "Canceling your article...done")
2117       (kill-buffer buf))))
2118
2119 ;;;###autoload
2120 (defun message-supersede ()
2121   "Start composing a message to supersede the current message.
2122 This is done simply by taking the old article and adding a Supersedes
2123 header line with the old Message-ID."
2124   (interactive)
2125   (let ((cur (current-buffer)))
2126     ;; Check whether the user owns the article that is to be superseded. 
2127     (unless (string-equal
2128              (downcase (mail-strip-quoted-names (mail-fetch-field "from")))
2129              (downcase (mail-strip-quoted-names (message-make-address))))
2130       (error "This article is not yours"))
2131     ;; Get a normal message buffer.
2132     (message-pop-to-buffer "*supersede message*")
2133     (insert-buffer-substring cur)
2134     (message-narrow-to-head)
2135     ;; Remove unwanted headers.
2136     (when message-ignored-supersedes-headers
2137       (message-remove-header message-ignored-supersedes-headers t))
2138     (goto-char (point-min))
2139     (if (not (re-search-forward "^Message-ID: " nil t))
2140         (error "No Message-ID in this article")
2141       (replace-match "Supersedes: " t t))
2142     (goto-char (point-max))
2143     (insert message-header-separator)
2144     (widen)
2145     (forward-line 1)))
2146
2147 ;;;###autoload
2148 (defun message-recover ()
2149   "Reread contents of current buffer from its last auto-save file."
2150   (interactive)
2151   (let ((file-name (make-auto-save-file-name)))
2152     (cond ((save-window-excursion
2153              (if (not (eq system-type 'vax-vms))
2154                  (with-output-to-temp-buffer "*Directory*"
2155                    (buffer-disable-undo standard-output)
2156                    (let ((default-directory "/"))
2157                      (call-process
2158                       "ls" nil standard-output nil "-l" file-name))))
2159              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2160            (let ((buffer-read-only nil))
2161              (erase-buffer)
2162              (insert-file-contents file-name nil)))
2163           (t (error "message-recover cancelled")))))
2164
2165 ;;; Forwarding messages.
2166
2167 (defun message-make-forward-subject ()
2168   "Return a Subject header suitable for the message in the current buffer."
2169   (concat "[" (mail-fetch-field (if (message-news-p) "newsgroups" "from"))
2170           "] " (or (mail-fetch-field "Subject") "")))
2171
2172 ;;;###autoload
2173 (defun message-forward (&optional news)
2174   "Forward the current message via mail.  
2175 Optional NEWS will use news to forward instead of mail."
2176   (interactive "P")
2177   (let ((cur (current-buffer))
2178         (subject (message-make-forward-subject)))
2179     (if news (message-news nil subject) (message-mail nil subject))
2180     ;; Put point where we want it before inserting the forwarded
2181     ;; message. 
2182     (if message-signature-before-forwarded-message
2183         (goto-char (point-max))
2184       (message-goto-body))
2185     ;; Narrow to the area we are to insert.
2186     (narrow-to-region (point) (point))
2187     ;; Insert the separators and the forwarded buffer.
2188     (insert message-forward-start-separator)
2189     (insert-buffer-substring cur)
2190     (goto-char (point-max))
2191     (insert message-forward-end-separator)
2192     (set-text-properties (point-min) (point-max) nil)
2193     ;; Remove all unwanted headers.
2194     (goto-char (point-min))
2195     (forward-line 1)
2196     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2197                                   (1- (point))
2198                                 (point)))
2199     (goto-char (point-min))
2200     (message-remove-header message-included-forward-headers t nil t)
2201     (widen)
2202     (message-position-point)))
2203
2204 ;;;###autoload
2205 (defun message-resend (address)
2206   "Resend the current article to ADDRESS."
2207   (interactive "sResend message to: ")
2208   (save-excursion
2209     (let ((cur (current-buffer))
2210           beg)
2211       ;; We first set up a normal mail buffer.
2212       (message-set-work-buffer)
2213       (message-setup `((To . ,address)))
2214       ;; Insert our usual headers.
2215       (message-narrow-to-headers)
2216       (message-generate-headers '(From Date To))
2217       (goto-char (point-min))
2218       ;; Rename them all to "Resent-*".
2219       (while (re-search-forward "^[A-Za-z]" nil t)
2220         (forward-char -1)
2221         (insert "Resent-"))
2222       (widen)
2223       (forward-line)
2224       (delete-region (point) (point-max))
2225       (setq beg (point))
2226       ;; Insert the message to be resent.
2227       (insert-buffer-substring cur)
2228       (goto-char (point-min))
2229       (search-forward "\n\n")
2230       (forward-char -1)
2231       (save-restriction
2232         (narrow-to-region beg (point))
2233         (message-remove-header message-ignored-resent-headers t)
2234         (goto-char (point-max)))
2235       (insert mail-header-separator)
2236       ;; Rename all old ("Also-")Resent headers.
2237       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2238         (beginning-of-line)
2239         (insert "Also-"))
2240       ;; Send it.
2241       (funcall message-send-mail-function))))
2242
2243 ;;;###autoload
2244 (defun message-bounce ()
2245   "Re-mail the current message.
2246 This only makes sense if the current message is a bounce message than
2247 contains some mail you have written which has been bounced back to
2248 you."
2249   (interactive "P")
2250   (let ((cur (current-buffer)))
2251     (message-pop-to-buffer "*mail message*")
2252     (insert-buffer-substring cur)
2253     (goto-char (point-min))
2254     (or (and (re-search-forward mail-unsent-separator nil t)
2255              (forward-line 1))
2256         (and (search-forward "\n\n" nil t)
2257              (re-search-forward "^Return-Path:.*\n" nil t)))
2258     ;; We remove everything before the bounced mail.
2259     (delete-region 
2260      (point-min)
2261      (if (re-search-forward "[^ \t]*:" nil t)
2262          (match-beginning 0)
2263        (point)))
2264     (save-restriction
2265       (message-narrow-to-head)
2266       (message-remove-header message-ignored-bounced-headers t)
2267       (goto-char (point-max))
2268       (insert mail-header-separator))
2269     (message-position-point)))
2270
2271 ;;;
2272 ;;; Interactive entry points for new message buffers.
2273 ;;;
2274
2275 ;;;###autoload
2276 (defun message-mail-other-window (&optional to subject)
2277   "Like `message-mail' command, but display mail buffer in another window."
2278   (interactive)
2279   (let ((pop-up-windows t)
2280         (special-display-buffer-names nil)
2281         (special-display-regexps nil)
2282         (same-window-buffer-names nil)
2283         (same-window-regexps nil))
2284     (message-pop-to-buffer "*mail message*"))
2285   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2286
2287 ;;;###autoload
2288 (defun message-mail-other-frame (&optional to subject)
2289   "Like `message-mail' command, but display mail buffer in another frame."
2290   (interactive)
2291   (let ((pop-up-frames t)
2292         (special-display-buffer-names nil)
2293         (special-display-regexps nil)
2294         (same-window-buffer-names nil)
2295         (same-window-regexps nil))
2296     (message-pop-to-buffer "*mail message*"))
2297   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2298
2299 ;;;###autoload
2300 (defun message-news-other-window (&optional newsgroups subject)
2301   "Start editing a news article to be sent."
2302   (interactive)
2303   (let ((pop-up-windows t)
2304         (special-display-buffer-names nil)
2305         (special-display-regexps nil)
2306         (same-window-buffer-names nil)
2307         (same-window-regexps nil))
2308     (message-pop-to-buffer "*news message*"))
2309   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2310                    (Subject . ,(or subject "")))))
2311
2312 ;;;###autoload
2313 (defun message-news-other-frame (&optional newsgroups subject)
2314   "Start editing a news article to be sent."
2315   (interactive)
2316   (let ((pop-up-frames t)
2317         (special-display-buffer-names nil)
2318         (special-display-regexps nil)
2319         (same-window-buffer-names nil)
2320         (same-window-regexps nil))
2321     (message-pop-to-buffer "*news message*"))
2322   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2323                    (Subject . ,(or subject "")))))
2324
2325 (provide 'message)
2326
2327 ;;; message.el ends here