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