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