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