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