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