*** 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 nil
71   "Controls what syntax checks should not be performed on outgoing posts.
72 To disable checking of long signatures, for instance, add
73  `(signature . disable)' to this list.
74
75 Don't touch this variable unless you really know what you're doing.
76
77 Checks include subject-cmsg multiple-headers sendsys message-id from
78 long-lines control-chars size new-text redirected-followup signature
79 approved sender empty empty-headers message-id from subject.")
80
81 ;;;###autoload
82 (defvar message-required-news-headers
83   '(From Newsgroups Subject Date Message-ID 
84          (optional . Organization) Lines 
85          (optional . X-Newsreader))
86   "*Headers to be generated or prompted for when posting an article.
87 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
88 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
89 X-Newsreader are optional.  If don't you want message to insert some
90 header, remove it from this list.")
91
92 ;;;###autoload
93 (defvar message-required-mail-headers 
94   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
95          (optional . X-Mailer))
96   "*Headers to be generated or prompted for when mailing a message.
97 RFC822 required that From, Date, To, Subject and Message-ID be
98 included.  Organization, Lines and X-Mailer are optional.")
99
100 ;;;###autoload
101 (defvar message-deletable-headers '(Message-ID Date)
102   "*Headers to be deleted if they already exist and were generated by message previously.")
103
104 ;;;###autoload
105 (defvar message-ignored-news-headers 
106   "^NNTP-Posting-Host:\\|^Xref:\\|^Bcc:\\|^Gcc:\\|^Fcc:"
107   "*Regexp of headers to be removed unconditionally before posting.")
108
109 ;;;###autoload
110 (defvar message-ignored-mail-headers "^Gcc:\\|^Fcc:"
111   "*Regexp of headers to be removed unconditionally before mailing.")
112
113 ;;;###autoload
114 (defvar message-ignored-supersedes-headers
115   "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|Return-Path:"
116   "*Header lines matching this regexp will be deleted before posting.
117 It's best to delete old Path and Date headers before posting to avoid
118 any confusion.")
119
120 ;;;###autoload
121 (defvar message-signature-separator "^-- *$"
122   "Regexp matching the signature separator.")
123
124 ;;;###autoload
125 (defvar message-interactive nil 
126   "Non-nil means when sending a message wait for and display errors.
127 nil means let mailer mail back a message to report errors.")
128
129 ;;;###autoload
130 (defvar message-generate-new-buffers nil
131   "*Non-nil means that a new message buffer will be created whenever `mail-setup' is called.")
132
133 ;;;###autoload
134 (defvar message-kill-buffer-on-exit nil
135   "*Non-nil means that the message buffer will be killed after sending a message.")
136
137 (defvar gnus-local-organization)
138 ;;;###autoload
139 (defvar message-user-organization 
140   (or (and (boundp 'gnus-local-organization)
141            gnus-local-organization)
142       (getenv "ORGANIZATION")
143       t)
144   "*String to be used as an Organization header.
145 If t, use `message-user-organization-file'.")
146
147 ;;;###autoload
148 (defvar message-user-organization-file "/usr/lib/news/organization"
149   "*Local news organization file.")
150
151 ;;;###autoload
152 (defvar message-autosave-directory "~/Mail/drafts/"
153   "*Directory where message autosaves buffers.
154 If nil, message won't autosave.")
155
156 (defvar message-forward-start-separator 
157   "------- Start of forwarded message -------\n"
158   "*Delimiter inserted before forwarded messages.")
159
160 (defvar message-forward-end-separator
161   "------- End of forwarded message -------\n"
162   "*Delimiter inserted after forwarded messages.")
163
164 ;;;###autoload
165 (defvar message-signature-before-forwarded-message t
166   "*If non-nil, put the signature before any included forwarded message.")
167
168 ;;;###autoload
169 (defvar message-included-forward-headers 
170   "^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:"
171   "*Regexp matching headers to be included in forwarded messages.")
172
173 ;;;###autoload
174 (defvar message-ignored-resent-headers "^Return-receipt"
175   "*All headers that match this regexp will be deleted when resending a message.")
176
177 ;;;###autoload
178 (defvar message-ignored-cited-headers "."
179   "Delete these headers from the messages you yank.")
180
181 ;; Useful to set in site-init.el
182 ;;;###autoload
183 (defvar message-send-mail-function 'message-send-mail 
184   "Function to call to send the current buffer as mail.
185 The headers should be delimited by a line whose contents match the
186 variable `mail-header-separator'.")
187
188 ;;;###autoload
189 (defvar message-send-news-function 'message-send-news
190   "Function to call to send the current buffer as news.
191 The headers should be delimited by a line whose contents match the
192 variable `message-header-separator'.")
193
194 ;;;###autoload
195 (defvar message-reply-to-function nil
196   "Function that should return a list of headers.")
197
198 ;;;###autoload
199 (defvar message-wide-reply-to-function nil
200   "Function that should return a list of headers.")
201
202 ;;;###autoload
203 (defvar message-followup-to-function nil
204   "Function that should return a list of headers.")
205
206 ;;;###autoload
207 (defvar message-use-followup-to 'ask
208   "*Specifies what to do with Followup-To header.
209 If nil, ignore the header. If it is t, use its value, but query before
210 using the \"poster\" value.  If it is the symbol `ask', query the user
211 whether to ignore the \"poster\" value.  If it is the symbol `use',
212 always use the value.")
213
214 (defvar gnus-post-method)
215 (defvar gnus-select-method)
216 ;;;###autoload
217 (defvar message-post-method 
218   (cond ((and (boundp 'gnus-post-method)
219               gnus-post-method)
220          gnus-post-method)
221         ((boundp 'gnus-select-method)
222          gnus-select-method)
223         (t '(nnspool "")))
224   "Method used to post news.")
225
226 ;;;###autoload
227 (defvar message-generate-headers-first nil
228   "*If non-nil, generate all possible headers before composing.")
229
230 ;;;###autoload
231 (defvar message-header-separator "--text follows this line--" 
232   "*Line used to separate headers from text in messages being composed.")
233
234 (defvar message-setup-hook nil
235   "Normal hook, run each time a new outgoing message is initialized.
236 The function `message-setup' runs this hook.")
237
238 (defvar message-header-setup-hook nil
239   "Hook called narrowed to the headers when setting up a message buffer.")
240
241 ;;;###autoload
242 (defvar message-citation-line-function 'message-insert-citation-line
243   "*Function called to insert the \"Whomever writes:\" line.")
244
245 ;;;###autoload
246 (defvar message-yank-prefix "> "
247   "*Prefix inserted on the lines of yanked messages.
248 nil means use indentation.")
249
250 (defvar message-indentation-spaces 3
251   "*Number of spaces to insert at the beginning of each cited line.
252 Used by `message-yank-original' via `message-yank-cite'.")
253
254 ;;;###autoload
255 (defvar message-cite-function 'message-cite-original
256   "*Function for citing an original message.")
257
258 ;;;###autoload
259 (defvar message-indent-citation-function 'message-indent-citation
260   "*Function for modifying a citation just inserted in the mail buffer.
261 This can also be a list of functions.  Each function can find the
262 citation between (point) and (mark t).  And each function should leave
263 point and mark around the citation text as modified.")
264
265 (defvar message-abbrevs-loaded nil)
266
267 ;;;###autoload
268 (defvar message-signature t
269   "*String to be inserted at the end of the message buffer.
270 If t, the `message-signature-file' file will be inserted instead.
271 If a function, the result from the function will be used instead.
272 If a form, the result from the form will be used instead.")
273
274 ;;;###autoload
275 (defvar message-signature-file "~/.signature"
276   "*File containing the text inserted at end of message. buffer.")
277
278 (defvar message-distribution-function nil
279   "*Function called to return a Distribution header.")
280
281 (defvar message-expires 14
282   "*Number of days before your article expires.")
283
284 (defvar message-user-path nil
285   "If nil, use the NNTP server name in the Path header.
286 If stringp, use this; if non-nil, use no host name (user name only).")
287
288 (defvar message-reply-buffer nil)
289 (defvar message-reply-headers nil)
290 (defvar message-newsreader nil)
291 (defvar message-mailer nil)
292 (defvar message-sent-message-via nil)
293 (defvar message-checksum nil)
294 (defvar message-send-actions nil
295   "A list of actions to be performed upon successful sending of a message.")
296
297 ;;;###autoload
298 (defvar message-default-headers nil
299   "*A string containing header lines to be inserted in outgoing messages.
300 It is inserted before you edit the message, so you can edit or delete
301 these lines.")
302
303 ;;;###autoload
304 (defvar message-default-mail-headers nil
305   "*A string of header lines to be inserted in outgoing mails.")
306
307 ;;;###autoload
308 (defvar message-default-news-headers nil
309   "*A string of header lines to be inserted in outgoing news articles.")
310
311 ;; Note: could use /usr/ucb/mail instead of sendmail;
312 ;; options -t, and -v if not interactive.
313 (defvar message-mailer-swallows-blank-line
314   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)" 
315                          system-configuration)
316            (file-readable-p "/etc/sendmail.cf")
317            (let ((buffer (get-buffer-create " *temp*")))
318              (unwind-protect
319                  (save-excursion
320                    (set-buffer buffer)
321                    (insert-file-contents "/etc/sendmail.cf")
322                    (goto-char (point-min))
323                    (let ((case-fold-search nil))
324                      (re-search-forward "^OR\\>" nil t)))
325                (kill-buffer buffer))))
326       ;; According to RFC822, "The field-name must be composed of printable
327       ;; ASCII characters (i.e. characters that have decimal values between
328       ;; 33 and 126, except colon)", i.e. any chars except ctl chars,
329       ;; space, or colon.
330       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
331   "Set this non-nil if the system's mailer runs the header and body together.
332 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
333 The value should be an expression to test whether the problem will
334 actually occur.")
335
336 (defvar message-mode-syntax-table 
337   (let ((table (copy-syntax-table text-mode-syntax-table)))
338     (modify-syntax-entry ?% ". " table)
339     table)
340   "Syntax table used while in Message mode.")
341
342 (defvar message-font-lock-keywords
343   (let* ((cite-prefix "A-Za-z") (cite-suffix (concat cite-prefix "0-9_.@-")))
344     (list '("^To:" . font-lock-function-name-face)
345           '("^B?CC:\\|^Reply-To:" . font-lock-keyword-face)
346           '("^\\(Subject:\\)[ \t]*\\(.+\\)?"
347             (1 font-lock-comment-face) (2 font-lock-type-face nil t))
348           (list (concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
349                 1 'font-lock-comment-face)
350           (cons (concat "^[ \t]*"
351                         "\\([" cite-prefix "]+[" cite-suffix "]*\\)?"
352                         "[>|}].*")
353                 'font-lock-reference-face)
354           '("^\\(X-[A-Za-z0-9-]+\\|In-reply-to\\):.*"
355             . font-lock-string-face)))
356   "Additional expressions to highlight in Message mode.")
357
358 (defvar message-face-alist
359   '((bold . bold-region)
360     (underline . underline-region)
361     (default . (lambda (b e) 
362                  (unbold-region b e)
363                  (ununderline-region b e))))
364   "Alist of mail and news faces for facemenu.
365 The cdr of ech entry is a function for applying the face to a region.")
366
367 (defvar message-send-hook nil
368   "Hook run before sending messages.")
369
370 (defvar message-sent-hook nil
371   "Hook run after sending messages.")
372
373 ;;; Internal variables.
374
375 (defvar message-header-format-alist 
376   `((Newsgroups)
377     (To . message-fill-header) 
378     (Cc . message-fill-header)
379     (Subject)
380     (In-Reply-To)
381     (Fcc)
382     (Bcc)
383     (Date)
384     (Organization)
385     (Distribution)
386     (Lines)
387     (Expires)
388     (Message-ID)
389     (References . message-fill-header)
390     (X-Mailer)
391     (X-Newsreader))
392   "Alist used for formatting headers.")
393
394 \f
395
396 ;;; 
397 ;;; Utility functions.
398 ;;;
399
400 (defun message-point-at-bol ()
401   "Return point at the beginning of the line."
402   (let ((p (point)))
403     (beginning-of-line)
404     (prog1
405         (point)
406       (goto-char p))))
407
408 (defun message-point-at-eol ()
409   "Return point at the end of the line."
410   (let ((p (point)))
411     (end-of-line)
412     (prog1
413         (point)
414       (goto-char p))))
415
416 ;; Delete the current line (and the next N lines.);
417 (defmacro message-delete-line (&optional n)
418   `(delete-region (progn (beginning-of-line) (point))
419                   (progn (forward-line ,(or n 1)) (point))))
420
421 (defun message-tokenize-header (header &optional separator)
422   "Split HEADER into a list of header elements.
423 \",\" is used as the separator."
424   (let* ((beg 0)
425          (separator (or separator ","))
426          (regexp
427           (format "[ \t]*\\([^%s]+\\)?\\([%s]+\\|\\'\\)" separator separator))
428          elems)
429     (while (and (string-match regexp header beg)
430                 (< beg (length header)))
431       (when (match-beginning 1)
432         (push (match-string 1 header) elems))
433       (setq beg (match-end 0)))
434     (nreverse elems)))
435
436 (defun message-fetch-reply-field (header)
437   "Fetch FIELD from the message we're replying to."
438   (when (and message-reply-buffer
439              (buffer-name message-reply-buffer))
440     (save-excursion
441       (set-buffer message-reply-buffer)
442       (mail-fetch-field header))))
443
444 (defun message-set-work-buffer ()
445   (if (get-buffer " *message work*")
446       (progn
447         (set-buffer " *message work*")
448         (erase-buffer))
449     (set-buffer (get-buffer-create " *message work*"))
450     (kill-all-local-variables)
451     (buffer-disable-undo (current-buffer))))
452
453 (defun message-functionp (form)
454   "Return non-nil if FORM is funcallable."
455   (or (and (symbolp form) (fboundp form))
456       (and (listp form) (eq (car form) 'lambda))))
457
458 (defun message-strip-subject-re (subject)
459   "Remove \"Re:\" from subject lines."
460   (if (string-match "^[Rr][Ee]: *" subject)
461       (substring subject (match-end 0))
462     subject))
463
464 (defun message-remove-header (header &optional is-regexp first reverse)
465   "Remove HEADER in the narrowed buffer.
466 If REGEXP, HEADER is a regular expression.
467 If FIRST, only remove the first instance of the header.
468 Return the number of headers removed."
469   (goto-char (point-min))
470   (let ((regexp (if is-regexp header (concat "^" header ":")))
471         (number 0)
472         (case-fold-search t)
473         last)
474     (while (and (not (eobp))
475                 (not last))
476       (if (if reverse
477               (not (looking-at regexp))
478             (looking-at regexp))
479           (progn
480             (incf number)
481             (when first
482               (setq last t))
483             (delete-region
484              (point)
485              ;; There might be a continuation header, so we have to search
486              ;; until we find a new non-continuation line.
487              (progn
488                (forward-line 1)
489                (if (re-search-forward "^[^ \t]" nil t)
490                    (goto-char (match-beginning 0))
491                  (point-max)))))
492         (forward-line 1)
493         (if (re-search-forward "^[^ \t]" nil t)
494             (goto-char (match-beginning 0))
495           (point-max))))
496     number))
497
498 (defun message-narrow-to-headers ()
499   "Narrow the buffer to the head of the message."
500   (widen)
501   (narrow-to-region
502    (goto-char (point-min))
503    (if (re-search-forward
504         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
505        (match-beginning 0)
506      (point-max)))
507   (goto-char (point-min)))
508
509 (defun message-narrow-to-head ()
510   "Narrow the buffer to the head of the message."
511   (widen)
512   (narrow-to-region
513    (goto-char (point-min))
514    (if (search-forward "\n\n" nil 1)
515        (1- (point))
516      (point-max)))
517   (goto-char (point-min)))
518
519 (defun message-news-p ()
520   "Say whether the current buffer contains a news message."
521   (save-excursion
522     (save-restriction
523       (message-narrow-to-headers)
524       (mail-fetch-field "newsgroups"))))
525
526 (defun message-mail-p ()
527   "Say whether the current buffer contains a mail message."
528   (save-excursion
529     (save-restriction
530       (message-narrow-to-headers)
531       (or (mail-fetch-field "to")
532           (mail-fetch-field "cc")
533           (mail-fetch-field "bcc")))))
534
535 (defun message-next-header ()
536   "Go to the beginning of the next header."
537   (beginning-of-line)
538   (or (eobp) (forward-char 1))
539   (not (if (re-search-forward "^[^ \t]" nil t)
540            (beginning-of-line)
541          (goto-char (point-max)))))
542     
543 (defun message-sort-headers-1 ()
544   "Sort the buffer as headers using `message-rank' text props."
545   (goto-char (point-min))
546   (sort-subr 
547    nil 'message-next-header 
548    (lambda ()
549      (message-next-header)
550      (unless (bobp)
551        (forward-char -1)))
552    (lambda ()
553      (or (get-text-property (point) 'message-rank)
554          0))))
555
556 (defun message-sort-headers ()
557   "Sort the headers of the current message according to `message-header-format-alist'."
558   (interactive)
559   (save-excursion
560     (save-restriction
561       (let ((max (1+ (length message-header-format-alist)))
562             rank)
563         (message-narrow-to-headers)
564         (while (re-search-forward "^[^ ]+:" nil t)
565           (put-text-property
566            (match-beginning 0) (1+ (match-beginning 0))
567            'message-rank
568            (if (setq rank (length (memq (assq (intern (buffer-substring
569                                                        (match-beginning 0)
570                                                        (1- (match-end 0))))
571                                               message-header-format-alist)
572                                         message-header-format-alist)))
573                (- max rank)
574              (1+ max)))))
575       (message-sort-headers-1))))
576
577 \f
578
579 ;;;
580 ;;; Message mode
581 ;;;
582
583 ;;; Set up keymap.
584
585 (defvar message-mode-map nil)
586
587 (unless message-mode-map
588   (setq message-mode-map (copy-keymap text-mode-map))
589   (define-key message-mode-map "\C-c?" 'describe-mode)
590
591   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
592   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
593   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
594   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
595   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
596   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
597   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
598   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
599   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
600   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
601   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
602   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
603   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
604
605   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
606   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
607   
608   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
609   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
610   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
611   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
612   (define-key message-mode-map "\C-c\C-h" 'message-sort-headers)
613
614   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
615   (define-key message-mode-map "\C-c\C-s" 'message-send)
616   (define-key message-mode-map "\C-c\C-k" 'message-dont-send))
617
618 (defun message-make-menu-bar ()
619   (unless (boundp 'message-menu)
620     (easy-menu-define
621      message-menu message-mode-map ""
622      '("Message"
623        ["Fill Citation" message-fill-yanked-message t]))))
624
625 ;;;###autoload
626 (defun message-mode ()
627   "Major mode for editing mail and news to be sent.
628 Like Text Mode but with these additional commands:
629 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
630 C-c C-f  move to a header field (and create it if there isn't):
631          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
632          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
633          C-c C-f C-f  move to Fcc       C-c C-f C-r  move to Reply-To
634          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
635          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
636          C-c C-f C-o  move to Followup-To
637 C-c C-t  message-insert-to (add a To header to a news followup)
638 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
639 C-c C-b  message-goto-body (move to beginning of message text).
640 C-c C-i  message-goto-signature (move to the beginning of the signature).
641 C-c C-w  message-insert-signature (insert `message-signature-file' file).
642 C-c C-y  message-yank-original (insert current message, if any).
643 C-c C-q  message-fill-yanked-message (fill what was yanked).
644 C-c C-r  message-ceasar-buffer-body (rot13 the message body)."
645   (interactive)
646   (kill-all-local-variables)
647   (make-local-variable 'message-reply-buffer)
648   (setq message-reply-buffer nil)
649   (make-local-variable 'message-send-actions)
650   (set-syntax-table message-mode-syntax-table)
651   (use-local-map message-mode-map)
652   (setq local-abbrev-table text-mode-abbrev-table)
653   (setq major-mode 'message-mode)
654   (setq mode-name "Message")
655   (setq buffer-offer-save t)
656   (make-local-variable 'font-lock-defaults)
657   (setq font-lock-defaults '(message-font-lock-keywords t))
658   (make-local-variable 'facemenu-add-face-function)
659   (make-local-variable 'facemenu-remove-face-function)
660   (setq facemenu-add-face-function
661         (lambda (face end)
662           (let ((face-fun (cdr (assq face message-face-alist))))
663             (if face-fun
664                 (funcall face-fun (point) end)
665               (error "Face %s not configured for %s mode" face mode-name)))
666           "")
667         facemenu-remove-face-function t)
668   (make-local-variable 'paragraph-separate)
669   (make-local-variable 'paragraph-start)
670   (setq paragraph-start (concat (regexp-quote mail-header-separator)
671                                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
672                                 paragraph-start))
673   (setq paragraph-separate (concat (regexp-quote mail-header-separator)
674                                    "$\\|[ \t]*[-_][-_][-_]+$\\|"
675                                    paragraph-separate))
676   (make-local-variable 'message-reply-headers)
677   (setq message-reply-headers nil)
678   (make-local-variable 'message-newsreader)
679   (make-local-variable 'message-mailer)
680   (make-local-variable 'message-post-method)
681   (make-local-variable 'message-sent-message-via)
682   (setq message-sent-message-via nil)
683   (make-local-variable 'message-checksum)
684   (setq message-checksum nil)
685   (when (fboundp 'mail-hist-define-keys)
686     (mail-hist-define-keys))
687   (run-hooks 'text-mode-hook 'message-mode-hook))
688
689 \f
690
691 ;;;
692 ;;; Message mode commands
693 ;;;
694
695 ;;; Movement commands
696
697 (defun message-goto-to ()
698   "Move point to the To header."
699   (interactive)
700   (message-position-on-field "To"))
701
702 (defun message-goto-subject ()
703   "Move point to the Subject header."
704   (interactive)
705   (message-position-on-field "Subject"))
706
707 (defun message-goto-cc ()
708   "Move point to the Cc header."
709   (interactive)
710   (message-position-on-field "Cc" "To"))
711
712 (defun message-goto-bcc ()
713   "Move point to the Bcc  header."
714   (interactive)
715   (message-position-on-field "Bcc" "Cc" "To"))
716
717 (defun message-goto-fcc ()
718   "Move point to the Fcc header."
719   (interactive)
720   (message-position-on-field "Fcc" "To" "Newsgroups"))
721
722 (defun message-goto-reply-to ()
723   "Move point to the Reply-To header."
724   (interactive)
725   (message-position-on-field "Reply-To" "Subject"))
726
727 (defun message-goto-newsgroups ()
728   "Move point to the Newsgroups header."
729   (interactive)
730   (message-position-on-field "Newsgroups"))
731
732 (defun message-goto-distribution ()
733   "Move point to the Distribution header."
734   (interactive)
735   (message-position-on-field "Distribution"))
736
737 (defun message-goto-followup-to ()
738   "Move point to the Followup-To header."
739   (interactive)
740   (message-position-on-field "Followup-To" "Newsgroups"))
741
742 (defun message-goto-keywords ()
743   "Move point to the Keywords header."
744   (interactive)
745   (message-position-on-field "Keywords" "Subject"))
746
747 (defun message-goto-summary ()
748   "Move point to the Summary header."
749   (interactive)
750   (message-position-on-field "Summary" "Subject"))
751
752 (defun message-goto-body ()
753   "Move point to the beginning of the message body."
754   (interactive)
755   (goto-char (point-min))
756   (search-forward (concat "\n" mail-header-separator "\n") nil t))
757
758 (defun message-goto-signature ()
759   "Move point to the beginning of the message signature."
760   (interactive)
761   (goto-char (point-min))
762   (or (re-search-forward message-signature-separator nil t)
763       (goto-char (point-max))))
764
765 \f
766
767 (defun message-insert-to ()
768   "Insert a To header that points to the author of the article being replied to."
769   (interactive)
770   (when (message-position-on-field "To")
771     (insert ", "))
772   (insert (or (message-fetch-reply-field "reply-to")
773               (message-fetch-reply-field "from") "")))
774
775 (defun message-insert-newsgroups ()
776   "Insert the Newsgroups header from the article being replied to."
777   (interactive)
778   (when (message-position-on-field "Newsgroups")
779     (insert ","))
780   (insert (or (message-fetch-reply-field "newsgroups") "")))
781
782 \f
783
784 ;;; Various commands
785
786 (defun message-insert-signature (&optional force)
787   "Insert a signature.  See documentation for the `message-signature' variable."
788   (interactive (list t))
789   (let* ((signature 
790           (cond ((and (null message-signature)
791                       force)
792                  t)
793                 ((message-functionp message-signature)
794                  (funcall message-signature))
795                 ((listp message-signature)
796                  (eval message-signature))
797                 (t message-signature)))
798          (signature
799           (cond ((stringp signature)
800                  signature)
801                 ((and (eq t signature)
802                       message-signature-file
803                       (file-exists-p message-signature-file))
804                  signature))))
805     (when signature
806       ;; Remove blank lines at the end of the message.
807       (goto-char (point-max))
808       (skip-chars-backward " \t\n")
809       (end-of-line)
810       (delete-region (point) (point-max))
811       ;; Insert the signature.
812       (insert "\n\n-- \n")
813       (if (eq signature t)
814           (insert-file-contents message-signature-file)
815         (insert signature))
816       (goto-char (point-max))
817       (or (bolp) (insert "\n")))))
818
819 (defvar message-caesar-translation-table nil)
820
821 (defun message-caesar-region (b e &optional n)
822   "Caesar rotation of region by N, default 13, for decrypting netnews."
823   (interactive
824    (list
825     (min (point) (or (mark t) (point)))
826     (max (point) (or (mark t) (point)))
827     (when current-prefix-arg
828       (prefix-numeric-value current-prefix-arg))))
829
830   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
831   (unless (or (zerop n)                 ; no action needed for a rot of 0
832               (= b e))                  ; no region to rotate
833     ;; We build the table, if necessary.
834     (when (or (not message-caesar-translation-table)
835               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
836       (let ((i -1) 
837             (table (make-string 256 0)))
838         (while (< (incf i) 256)
839           (aset table i i))
840         (setq table
841               (concat
842                (substring table 0 ?A)
843                (substring table (+ ?A n) (+ ?A n (- 26 n)))
844                (substring table ?A (+ ?A n))
845                (substring table (+ ?A 26) ?a)
846                (substring table (+ ?a n) (+ ?a n (- 26 n)))
847                (substring table ?a (+ ?a n))
848                (substring table (+ ?a 26) 255)))
849         (setq message-caesar-translation-table table)))
850     ;; Then we translate the region.  Do it this way to retain 
851     ;; text properties.
852     (while (< b e)
853       (subst-char-in-region 
854        b (1+ b) (char-after b)
855        (aref message-caesar-translation-table (char-after b)))
856       (incf b))))
857
858 (defun message-caesar-buffer-body (&optional rotnum)
859   "Caesar rotates all letters in the current buffer by 13 places.
860 Used to encode/decode possibly offensive messages (commonly in net.jokes).
861 With prefix arg, specifies the number of places to rotate each letter forward.
862 Mail and USENET news headers are not rotated."
863   (interactive (if current-prefix-arg
864                    (list (prefix-numeric-value current-prefix-arg))
865                  (list nil)))
866   (save-excursion
867     (save-restriction
868       (when (message-goto-body)
869         (narrow-to-region (point) (point-max)))
870       (message-caesar-region (point-min) (point-max) rotnum))))
871
872 (defun message-fill-yanked-message (&optional justifyp)
873   "Fill the paragraphs of a message yanked into this one.
874 Numeric argument means justify as well."
875   (interactive "P")
876   (save-excursion
877     (goto-char (point-min))
878     (search-forward (concat "\n" mail-header-separator "\n") nil t)
879     (let ((fill-prefix message-yank-prefix))
880       (fill-individual-paragraphs (point) (point-max) justifyp t))))
881
882 (defun message-indent-citation ()
883   "Modify text just inserted from a message to be cited.
884 The inserted text should be the region.
885 When this function returns, the region is again around the modified text.
886
887 Normally, indent each nonblank line `message-indentation-spaces' spaces.
888 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
889   (let ((start (point)))
890     ;; Remove unwanted headers.
891     (when message-ignored-cited-headers
892       (save-restriction
893         (narrow-to-region 
894          (goto-char start)
895          (if (search-forward "\n\n" nil t)
896              (1- (point))
897            (point)))
898         (message-remove-header message-ignored-cited-headers t)))
899     ;; Do the indentation.
900     (if (null message-yank-prefix)
901         (indent-rigidly start (mark t) message-indentation-spaces)
902       (save-excursion
903         (goto-char start)
904         (while (< (point) (mark t))
905           (insert message-yank-prefix)
906           (forward-line 1)))
907       (goto-char start))))
908
909 (defun message-yank-original (&optional arg)
910   "Insert the message being replied to, if any.
911 Puts point before the text and mark after.
912 Normally indents each nonblank line ARG spaces (default 3).  However,
913 if `message-yank-prefix' is non-nil, insert that prefix on each line.
914
915 Just \\[universal-argument] as argument means don't indent, insert no
916 prefix, and don't delete any headers."
917   (interactive "P")
918   (let ((modified (buffer-modified-p)))
919     (when (and message-reply-buffer
920                message-cite-function)
921       (delete-windows-on message-reply-buffer t)
922       (insert-buffer message-reply-buffer)
923       (funcall message-cite-function)
924       (exchange-point-and-mark)
925       (unless (bolp)
926         (insert ?\n))
927       (unless modified
928         (setq message-checksum (message-checksum))))))
929
930 (defun message-cite-original ()    
931   (let ((start (point))
932         (functions 
933          (when message-indent-citation-function
934            (if (listp message-indent-citation-function)
935                message-indent-citation-function
936              (list message-indent-citation-function)))))
937     (goto-char start)
938     (while functions
939       (funcall (pop functions)))
940     (when message-citation-line-function
941       (unless (bolp)
942         (insert "\n"))
943       (funcall message-citation-line-function))))
944
945 (defun message-insert-citation-line ()
946   "Function that inserts a simple citation line."
947   (when message-reply-headers
948     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
949
950 (defun message-position-on-field (header &rest afters)
951   (let ((case-fold-search t))
952     (save-restriction
953       (narrow-to-region
954        (goto-char (point-min))
955        (progn
956          (re-search-forward 
957           (concat "^" (regexp-quote mail-header-separator) "$"))
958          (match-beginning 0)))
959       (goto-char (point-min))
960       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
961           (progn
962             (re-search-forward "^[^ \t]" nil 'move)
963             (beginning-of-line)
964             (skip-chars-backward "\n")
965             t)
966         (while (and afters
967                     (not (re-search-forward 
968                           (concat "^" (regexp-quote (car afters)) ":")
969                           nil t)))
970           (pop afters))
971         (when afters
972           (re-search-forward "^[^ \t]" nil 'move)
973           (beginning-of-line))
974         (insert header ": \n")
975         (forward-char -1)
976         nil))))
977
978 (defun message-remove-signature ()
979   "Remove the signature from the text between point and mark.
980 The text will also be indented the normal way."
981   (save-excursion
982     (let ((start (point))
983           mark)
984     (if (not (re-search-forward message-signature-separator (mark t) t))
985         ;; No signature here, so we just indent the cited text.
986         (message-indent-citation)
987       ;; Find the last non-empty line.
988       (forward-line -1)
989       (while (looking-at "[ \t]*$")
990         (forward-line -1))
991       (forward-line 1)
992       (setq mark (set-marker (make-marker) (point)))
993       (goto-char start)
994       (message-indent-citation)
995       ;; Enable undoing the deletion.
996       (undo-boundary)
997       (delete-region mark (mark t))
998       (set-marker mark nil)))))
999
1000 \f
1001
1002 ;;;
1003 ;;; Sending messages
1004 ;;;
1005
1006 (defun message-send-and-exit (&optional arg)
1007   "Send message like `message-send', then, if no errors, exit from mail buffer."
1008   (interactive "P")
1009   (let ((buf (current-buffer)))
1010     (when (and (message-send arg)
1011                (buffer-name buf))
1012       (if message-kill-buffer-on-exit
1013           (kill-buffer buf)
1014         (bury-buffer buf)
1015         (when (eq buf (current-buffer))
1016           (message-bury buf))))))
1017
1018 (defun message-dont-send ()
1019   "Don't send the message you have been editing."
1020   (interactive)
1021   (message-bury (current-buffer)))
1022
1023 (defun message-bury (buffer)
1024   "Bury this mail buffer."
1025   (let ((newbuf (other-buffer buffer)))
1026     (bury-buffer buffer)
1027     (if (and (fboundp 'frame-parameters)
1028              (cdr (assq 'dedicated (frame-parameters)))
1029              (not (null (delq (selected-frame) (visible-frame-list)))))
1030         (delete-frame (selected-frame))
1031       (switch-to-buffer newbuf))))
1032
1033 (defun message-send (&optional arg)
1034   "Send the message in the current buffer.
1035 If `message-interactive' is non-nil, wait for success indication
1036 or error messages, and inform user.
1037 Otherwise any failure is reported in a message back to
1038 the user from the mailer."
1039   (interactive "P")
1040   (when (if buffer-file-name
1041             (y-or-n-p (format "Send buffer contents as %s message? "
1042                               (if (message-mail-p)
1043                                   (if (message-news-p) "mail and news" "mail")
1044                                 "news")))
1045           (or (buffer-modified-p)
1046               (y-or-n-p "No changes in the buffer; really send? ")))
1047     ;; Make it possible to undo the coming changes.
1048     (undo-boundary)
1049     (run-hooks 'message-send-hook)
1050     (message "Sending...")
1051     (when (and (or (not (message-news-p))
1052                    (and (or (not (memq 'news message-sent-message-via))
1053                             (y-or-n-p
1054                              "Already sent message via news; resend? "))
1055                         (funcall message-send-news-function arg)))
1056                (or (not (message-mail-p))
1057                    (and (or (not (memq 'mail message-sent-message-via))
1058                             (y-or-n-p
1059                              "Already sent message via mail; resend? "))
1060                         (funcall message-send-mail-function arg))))
1061       (message-do-fcc)
1062       (when (fboundp 'mail-hist-put-headers-into-history)
1063         (mail-hist-put-headers-into-history))
1064       (run-hooks 'message-sent-hook)
1065       (message "Sending...done")
1066       ;; If buffer has no file, mark it as unmodified and delete autosave.
1067       (unless buffer-file-name
1068         (set-buffer-modified-p nil)
1069         (delete-auto-save-file-if-necessary t))
1070       ;; Now perform actions on successful sending.
1071       (let ((actions message-send-actions))
1072         (while actions
1073           (condition-case nil
1074               (apply (caar actions) (cdar actions))
1075             (error))
1076           (pop actions)))
1077       ;; Return success.
1078       t)))
1079
1080 (defun message-send-mail (&optional arg)
1081   (require 'mail-utils)
1082   (let ((errbuf (if message-interactive
1083                     (generate-new-buffer " sendmail errors")
1084                   0))
1085         (tembuf (generate-new-buffer " message temp"))
1086         (case-fold-search nil)
1087         (news (message-news-p))
1088         resend-to-addresses delimline
1089         (mailbuf (current-buffer)))
1090     (save-restriction
1091       (message-narrow-to-headers)
1092       (setq resend-to-addresses (mail-fetch-field "resent-to"))
1093       ;; Insert some headers.
1094       (message-generate-headers message-required-mail-headers)
1095       ;; Let the user do all of the above.
1096       (run-hooks 'message-header-hook))
1097     (unwind-protect
1098         (save-excursion
1099           (set-buffer tembuf)
1100           (erase-buffer)
1101           (insert-buffer-substring mailbuf)
1102           ;; Remove some headers.
1103           (save-restriction
1104             (message-narrow-to-headers)
1105             ;; Remove some headers.
1106             (message-remove-header message-ignored-mail-headers t))
1107           (goto-char (point-max))
1108           ;; require one newline at the end.
1109           (or (= (preceding-char) ?\n)
1110               (insert ?\n))
1111           (when (and news
1112                      (or (mail-fetch-field "cc")
1113                          (mail-fetch-field "to")))
1114             (message-insert-courtesy-copy))
1115           (let ((case-fold-search t))
1116             ;; Change header-delimiter to be what sendmail expects.
1117             (goto-char (point-min))
1118             (re-search-forward
1119              (concat "^" (regexp-quote mail-header-separator) "\n"))
1120             (replace-match "\n")
1121             (backward-char 1)
1122             (setq delimline (point-marker))
1123             ;; Insert an extra newline if we need it to work around
1124             ;; Sun's bug that swallows newlines.
1125             (goto-char (1+ delimline))
1126             (when (eval message-mailer-swallows-blank-line)
1127               (newline))
1128             (when message-interactive
1129               (save-excursion
1130                 (set-buffer errbuf)
1131                 (erase-buffer))))
1132           (let ((default-directory "/"))
1133             (apply 'call-process-region
1134                    (append (list (point-min) (point-max)
1135                                  (if (boundp 'sendmail-program)
1136                                      sendmail-program
1137                                    "/usr/lib/sendmail")
1138                                  nil errbuf nil "-oi")
1139                            ;; Always specify who from,
1140                            ;; since some systems have broken sendmails.
1141                            (list "-f" (user-login-name))
1142                            ;; These mean "report errors by mail"
1143                            ;; and "deliver in background".
1144                            (if (null message-interactive) '("-oem" "-odb"))
1145                            ;; Get the addresses from the message
1146                            ;; unless this is a resend.
1147                            ;; We must not do that for a resend
1148                            ;; because we would find the original addresses.
1149                            ;; For a resend, include the specific addresses.
1150                            (if resend-to-addresses
1151                                (list resend-to-addresses)
1152                              '("-t")))))
1153           (when message-interactive
1154             (save-excursion
1155               (set-buffer errbuf)
1156               (goto-char (point-min))
1157               (while (re-search-forward "\n\n* *" nil t)
1158                 (replace-match "; "))
1159               (if (not (zerop (buffer-size)))
1160                   (error "Sending...failed to %s"
1161                          (buffer-substring (point-min) (point-max)))))))
1162       (kill-buffer tembuf)
1163       (when (bufferp errbuf)
1164         (kill-buffer errbuf)))
1165     (set-buffer mailbuf)
1166     (push 'mail message-sent-message-via)))
1167
1168 (defun message-send-news (&optional arg)
1169   (let ((tembuf (generate-new-buffer " *message temp*"))
1170         (case-fold-search nil)
1171         (method (if (message-functionp message-post-method)
1172                     (funcall message-post-method arg)
1173                   message-post-method))
1174         (messbuf (current-buffer)))
1175     (save-restriction
1176       (message-narrow-to-headers)
1177       ;; Insert some headers.
1178       (message-generate-headers message-required-news-headers)
1179       ;; Let the user do all of the above.
1180       (run-hooks 'message-header-hook))
1181     (when (message-check-news-syntax)
1182       (unwind-protect
1183           (save-excursion
1184             (set-buffer tembuf)
1185             (buffer-disable-undo (current-buffer))
1186             (erase-buffer) 
1187             (insert-buffer-substring messbuf)
1188             ;; Remove some headers.
1189             (save-restriction
1190               (message-narrow-to-headers)
1191               ;; Remove some headers.
1192               (message-remove-header message-ignored-news-headers t))
1193             (goto-char (point-max))
1194             ;; require one newline at the end.
1195             (or (= (preceding-char) ?\n)
1196                 (insert ?\n))
1197             (let ((case-fold-search t))
1198               ;; Remove the delimeter.
1199               (goto-char (point-min))
1200               (re-search-forward
1201                (concat "^" (regexp-quote mail-header-separator) "\n"))
1202               (replace-match "\n")
1203               (backward-char 1))
1204             (require (car method))
1205             (funcall (intern (format "%s-open-server" (car method)))
1206                      (cadr method) (cddr method))
1207             (funcall (intern (format "%s-request-post"
1208                                      (car method)))))
1209         (kill-buffer tembuf))
1210       (set-buffer messbuf)
1211       (push 'news message-sent-message-via))))
1212
1213 ;;;
1214 ;;; Header generation & syntax checking.
1215 ;;;
1216
1217 (defun message-check-news-syntax ()
1218   "Check the syntax of the message."
1219   (and 
1220    ;; We narrow to the headers and check them first.
1221    (save-excursion
1222      (save-restriction
1223        (message-narrow-to-headers)
1224        (and 
1225         ;; Check for commands in Subject.
1226         (or 
1227          (message-check-element 'subject-cmsg)
1228          (save-excursion
1229            (if (string-match "^cmsg " (mail-fetch-field "subject"))
1230                (y-or-n-p
1231                 "The control code \"cmsg \" is in the subject. Really post? ")
1232              t)))
1233         ;; Check for multiple identical headers.
1234         (or (message-check-element 'multiple-headers)
1235             (save-excursion
1236               (let (found)
1237                 (while (and (not found) 
1238                             (re-search-forward "^[^ \t:]+: " nil t))
1239                   (save-excursion
1240                     (or (re-search-forward 
1241                          (concat "^" (setq found
1242                                            (buffer-substring 
1243                                             (match-beginning 0) 
1244                                             (- (match-end 0) 2))))
1245                          nil t)
1246                         (setq found nil))))
1247                 (if found
1248                     (y-or-n-p 
1249                      (format "Multiple %s headers. Really post? " found))
1250                   t))))
1251         ;; Check for Version and Sendsys.
1252         (or (message-check-element 'sendsys)
1253             (save-excursion
1254               (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1255                   (y-or-n-p
1256                    (format "The article contains a %s command. Really post? "
1257                            (buffer-substring (match-beginning 0) 
1258                                              (1- (match-end 0)))))
1259                 t)))
1260         ;; See whether we can shorten Followup-To.
1261         (or (message-check-element 'shorten-followup-to)
1262             (let ((newsgroups (mail-fetch-field "newsgroups"))
1263                   (followup-to (mail-fetch-field "followup-to"))
1264                   to)
1265               (when (and newsgroups (string-match "," newsgroups)
1266                          (not followup-to)
1267                          (not
1268                           (zerop
1269                            (length
1270                             (setq to (completing-read 
1271                                       "Followups to: (default all groups) " 
1272                                       (mapcar (lambda (g) (list g))
1273                                               (cons "poster" 
1274                                                     (message-tokenize-header 
1275                                                      newsgroups)))))))))
1276                 (goto-char (point-min))
1277                 (insert "Followup-To: " to "\n"))
1278               t))
1279
1280         ;; Check for Approved.
1281         (or (message-check-element 'approved)
1282             (save-excursion
1283               (if (re-search-forward "^Approved:" nil t)
1284                   (y-or-n-p
1285                    "The article contains an Approved header. Really post? ")
1286                 t)))
1287         ;; Check the Message-Id header.
1288         (or (message-check-element 'message-id)
1289             (save-excursion
1290               (let* ((case-fold-search t)
1291                      (message-id (mail-fetch-field "message-id")))
1292                 (or (not message-id)
1293                     (and (string-match "@" message-id)
1294                          (string-match "@[^\\.]*\\." message-id))
1295                     (y-or-n-p
1296                      (format 
1297                       "The Message-ID looks strange: \"%s\". Really post? "
1298                       message-id))))))
1299         ;; Check the Subject header.
1300         (or 
1301          (message-check-element 'subject)
1302          (save-excursion
1303            (let* ((case-fold-search t)
1304                   (subject (mail-fetch-field "subject")))
1305              (or
1306               (and subject
1307                    (not (string-match "\\`[ \t]*\\'" subject)))
1308               (progn
1309                 (message 
1310                  "The subject field is empty or missing.  Posting is denied.")
1311                 nil)))))
1312         ;; Check the From header.
1313         (or (message-check-element 'from)
1314             (save-excursion
1315               (let* ((case-fold-search t)
1316                      (from (mail-fetch-field "from")))
1317                 (cond
1318                  ((not from)
1319                   (message "There is no From line.  Posting is denied.")
1320                   nil)
1321                  ((not (string-match "@[^\\.]*\\." from))
1322                   (message
1323                    "Denied posting -- the From looks strange: \"%s\"." from)
1324                   nil)
1325                  ((string-match "@[^@]*@" from)
1326                   (message 
1327                    "Denied posting -- two \"@\"'s in the From header: %s."
1328                    from)
1329                   nil)
1330                  ((string-match "(.*).*(.*)" from)
1331                   (message
1332                    "Denied posting -- the From header looks strange: \"%s\"." 
1333                    from)
1334                   nil)
1335                  (t t))))))))
1336    ;; Check for long lines.
1337    (or (message-check-element 'long-lines)
1338        (save-excursion
1339          (goto-char (point-min))
1340          (re-search-forward
1341           (concat "^" (regexp-quote mail-header-separator) "$"))
1342          (while (and
1343                  (progn
1344                    (end-of-line)
1345                    (< (current-column) 80))
1346                  (zerop (forward-line 1))))
1347          (or (bolp)
1348              (eobp)
1349              (y-or-n-p
1350               "You have lines longer than 79 characters.  Really post? "))))
1351    ;; Check whether the article is empty.
1352    (or (message-check-element 'empty)
1353        (save-excursion
1354          (goto-char (point-min))
1355          (re-search-forward
1356           (concat "^" (regexp-quote mail-header-separator) "$"))
1357          (forward-line 1)
1358          (or (re-search-forward "[^ \n\t]" nil t)
1359              (y-or-n-p "Empty article.  Really post?"))))
1360    ;; Check for control characters.
1361    (or (message-check-element 'control-chars)
1362        (save-excursion
1363          (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1364              (y-or-n-p 
1365               "The article contains control characters. Really post? ")
1366            t)))
1367    ;; Check excessive size.
1368    (or (message-check-element 'size)
1369        (if (> (buffer-size) 60000)
1370            (y-or-n-p
1371             (format "The article is %d octets long. Really post? "
1372                     (buffer-size)))
1373          t))
1374    ;; Check whether any new text has been added.
1375    (or (message-check-element 'new-text)
1376        (not message-checksum)
1377        (not (eq (message-checksum) message-checksum))
1378        (y-or-n-p
1379         "It looks like no new text has been added.  Really post? "))
1380    ;; Check the length of the signature.
1381    (or (message-check-element 'signature)
1382        (progn
1383          (goto-char (point-max))
1384          (if (not (re-search-backward "^-- $" nil t))
1385              t
1386            (if (> (count-lines (point) (point-max)) 5)
1387                (y-or-n-p
1388                 (format
1389                  "Your .sig is %d lines; it should be max 4.  Really post? "
1390                  (count-lines (point) (point-max))))
1391              t))))))
1392
1393 (defun message-check-element (type)
1394   "Returns non-nil if this type is not to be checked."
1395   (let ((able (assq type message-syntax-checks)))
1396     (and (consp able)
1397          (eq (cdr able) 'disabled))))
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