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