b0cc714acc943d45b48b51fb08205c76e17b6278
[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   (goto-char (point-min))
887   (search-forward (concat "\n" mail-header-separator "\n") nil t))
888
889 (defun message-goto-signature ()
890   "Move point to the beginning of the message signature."
891   (interactive)
892   (goto-char (point-min))
893   (or (re-search-forward message-signature-separator nil t)
894       (goto-char (point-max))))
895
896 \f
897
898 (defun message-insert-to ()
899   "Insert a To header that points to the author of the article being replied to."
900   (interactive)
901   (when (message-position-on-field "To")
902     (insert ", "))
903   (insert (or (message-fetch-reply-field "reply-to")
904               (message-fetch-reply-field "from") "")))
905
906 (defun message-insert-newsgroups ()
907   "Insert the Newsgroups header from the article being replied to."
908   (interactive)
909   (when (message-position-on-field "Newsgroups")
910     (insert ","))
911   (insert (or (message-fetch-reply-field "newsgroups") "")))
912
913 \f
914
915 ;;; Various commands
916
917 (defun message-insert-signature (&optional force)
918   "Insert a signature.  See documentation for the `message-signature' variable."
919   (interactive (list t))
920   (let* ((signature 
921           (cond ((and (null message-signature)
922                       force)
923                  t)
924                 ((message-functionp message-signature)
925                  (funcall message-signature))
926                 ((listp message-signature)
927                  (eval message-signature))
928                 (t message-signature)))
929          (signature
930           (cond ((stringp signature)
931                  signature)
932                 ((and (eq t signature)
933                       message-signature-file
934                       (file-exists-p message-signature-file))
935                  signature))))
936     (when signature
937       ;; Remove blank lines at the end of the message.
938       (goto-char (point-max))
939       (skip-chars-backward " \t\n")
940       (end-of-line)
941       (delete-region (point) (point-max))
942       ;; Insert the signature.
943       (insert "\n\n-- \n")
944       (if (eq signature t)
945           (insert-file-contents message-signature-file)
946         (insert signature))
947       (goto-char (point-max))
948       (or (bolp) (insert "\n")))))
949
950 (defvar message-caesar-translation-table nil)
951
952 (defun message-caesar-region (b e &optional n)
953   "Caesar rotation of region by N, default 13, for decrypting netnews."
954   (interactive
955    (list
956     (min (point) (or (mark t) (point)))
957     (max (point) (or (mark t) (point)))
958     (when current-prefix-arg
959       (prefix-numeric-value current-prefix-arg))))
960
961   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
962   (unless (or (zerop n)                 ; no action needed for a rot of 0
963               (= b e))                  ; no region to rotate
964     ;; We build the table, if necessary.
965     (when (or (not message-caesar-translation-table)
966               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
967       (let ((i -1) 
968             (table (make-string 256 0)))
969         (while (< (incf i) 256)
970           (aset table i i))
971         (setq table
972               (concat
973                (substring table 0 ?A)
974                (substring table (+ ?A n) (+ ?A n (- 26 n)))
975                (substring table ?A (+ ?A n))
976                (substring table (+ ?A 26) ?a)
977                (substring table (+ ?a n) (+ ?a n (- 26 n)))
978                (substring table ?a (+ ?a n))
979                (substring table (+ ?a 26) 255)))
980         (setq message-caesar-translation-table table)))
981     ;; Then we translate the region.  Do it this way to retain 
982     ;; text properties.
983     (while (< b e)
984       (subst-char-in-region 
985        b (1+ b) (char-after b)
986        (aref message-caesar-translation-table (char-after b)))
987       (incf b))))
988
989 (defun message-caesar-buffer-body (&optional rotnum)
990   "Caesar rotates all letters in the current buffer by 13 places.
991 Used to encode/decode possibly offensive messages (commonly in net.jokes).
992 With prefix arg, specifies the number of places to rotate each letter forward.
993 Mail and USENET news headers are not rotated."
994   (interactive (if current-prefix-arg
995                    (list (prefix-numeric-value current-prefix-arg))
996                  (list nil)))
997   (save-excursion
998     (save-restriction
999       (when (message-goto-body)
1000         (narrow-to-region (point) (point-max)))
1001       (message-caesar-region (point-min) (point-max) rotnum))))
1002
1003 (defun message-rename-buffer (&optional enter-string)
1004   "Rename the *message* buffer to \"*message* RECIPIENT\".  
1005 If the function is run with a prefix, it will ask for a new buffer
1006 name, rather than giving an automatic name."
1007   (interactive "Pbuffer name: ")
1008   (save-excursion
1009     (save-restriction
1010       (goto-char (point-min))
1011       (narrow-to-region (point) 
1012                         (search-forward mail-header-separator nil 'end))
1013       (let* ((mail-to (if (message-news-p) (message-fetch-field "Newsgroups")
1014                         (message-fetch-field "To")))
1015              (mail-trimmed-to
1016               (if (string-match "," mail-to)
1017                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1018                 mail-to))
1019              (name-default (concat "*message* " mail-trimmed-to))
1020              (name (if enter-string
1021                        (read-string "New buffer name: " name-default)
1022                      name-default)))
1023         (rename-buffer name t)))))
1024
1025 (defun message-fill-yanked-message (&optional justifyp)
1026   "Fill the paragraphs of a message yanked into this one.
1027 Numeric argument means justify as well."
1028   (interactive "P")
1029   (save-excursion
1030     (goto-char (point-min))
1031     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1032     (let ((fill-prefix message-yank-prefix))
1033       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1034
1035 (defun message-indent-citation ()
1036   "Modify text just inserted from a message to be cited.
1037 The inserted text should be the region.
1038 When this function returns, the region is again around the modified text.
1039
1040 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1041 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1042   (let ((start (point)))
1043     ;; Remove unwanted headers.
1044     (when message-ignored-cited-headers
1045       (save-restriction
1046         (narrow-to-region 
1047          (goto-char start)
1048          (if (search-forward "\n\n" nil t)
1049              (1- (point))
1050            (point)))
1051         (message-remove-header message-ignored-cited-headers t)))
1052     ;; Do the indentation.
1053     (if (null message-yank-prefix)
1054         (indent-rigidly start (mark t) message-indentation-spaces)
1055       (save-excursion
1056         (goto-char start)
1057         (while (< (point) (mark t))
1058           (insert message-yank-prefix)
1059           (forward-line 1)))
1060       (goto-char start))))
1061
1062 (defun message-yank-original (&optional arg)
1063   "Insert the message being replied to, if any.
1064 Puts point before the text and mark after.
1065 Normally indents each nonblank line ARG spaces (default 3).  However,
1066 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1067
1068 Just \\[universal-argument] as argument means don't indent, insert no
1069 prefix, and don't delete any headers."
1070   (interactive "P")
1071   (let ((modified (buffer-modified-p)))
1072     (when (and message-reply-buffer
1073                message-cite-function)
1074       (delete-windows-on message-reply-buffer t)
1075       (insert-buffer message-reply-buffer)
1076       (funcall message-cite-function)
1077       (exchange-point-and-mark)
1078       (unless (bolp)
1079         (insert ?\n))
1080       (unless modified
1081         (setq message-checksum (message-checksum))))))
1082
1083 (defun message-cite-original ()    
1084   (let ((start (point))
1085         (functions 
1086          (when message-indent-citation-function
1087            (if (listp message-indent-citation-function)
1088                message-indent-citation-function
1089              (list message-indent-citation-function)))))
1090     (goto-char start)
1091     (while functions
1092       (funcall (pop functions)))
1093     (when message-citation-line-function
1094       (unless (bolp)
1095         (insert "\n"))
1096       (funcall message-citation-line-function))))
1097
1098 (defun message-insert-citation-line ()
1099   "Function that inserts a simple citation line."
1100   (when message-reply-headers
1101     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1102
1103 (defun message-position-on-field (header &rest afters)
1104   (let ((case-fold-search t))
1105     (save-restriction
1106       (narrow-to-region
1107        (goto-char (point-min))
1108        (progn
1109          (re-search-forward 
1110           (concat "^" (regexp-quote mail-header-separator) "$"))
1111          (match-beginning 0)))
1112       (goto-char (point-min))
1113       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1114           (progn
1115             (re-search-forward "^[^ \t]" nil 'move)
1116             (beginning-of-line)
1117             (skip-chars-backward "\n")
1118             t)
1119         (while (and afters
1120                     (not (re-search-forward 
1121                           (concat "^" (regexp-quote (car afters)) ":")
1122                           nil t)))
1123           (pop afters))
1124         (when afters
1125           (re-search-forward "^[^ \t]" nil 'move)
1126           (beginning-of-line))
1127         (insert header ": \n")
1128         (forward-char -1)
1129         nil))))
1130
1131 (defun message-remove-signature ()
1132   "Remove the signature from the text between point and mark.
1133 The text will also be indented the normal way."
1134   (save-excursion
1135     (let ((start (point))
1136           mark)
1137     (if (not (re-search-forward message-signature-separator (mark t) t))
1138         ;; No signature here, so we just indent the cited text.
1139         (message-indent-citation)
1140       ;; Find the last non-empty line.
1141       (forward-line -1)
1142       (while (looking-at "[ \t]*$")
1143         (forward-line -1))
1144       (forward-line 1)
1145       (setq mark (set-marker (make-marker) (point)))
1146       (goto-char start)
1147       (message-indent-citation)
1148       ;; Enable undoing the deletion.
1149       (undo-boundary)
1150       (delete-region mark (mark t))
1151       (set-marker mark nil)))))
1152
1153 \f
1154
1155 ;;;
1156 ;;; Sending messages
1157 ;;;
1158
1159 (defun message-send-and-exit (&optional arg)
1160   "Send message like `message-send', then, if no errors, exit from mail buffer."
1161   (interactive "P")
1162   (let ((buf (current-buffer))
1163         (actions message-exit-actions))
1164     (when (and (message-send arg)
1165                (buffer-name buf))
1166       (if message-kill-buffer-on-exit
1167           (kill-buffer buf)
1168         (bury-buffer buf)
1169         (when (eq buf (current-buffer))
1170           (message-bury buf)))
1171       (message-do-actions actions))))
1172
1173 (defun message-dont-send ()
1174   "Don't send the message you have been editing."
1175   (interactive)
1176   (message-bury (current-buffer))
1177   (message-do-actions message-postpone-actions))
1178
1179 (defun message-kill-buffer ()
1180   "Kill the current buffer."
1181   (interactive)
1182   (let ((actions message-kill-actions))
1183     (kill-buffer (current-buffer))
1184     (message-do-actions actions)))
1185
1186 (defun message-bury (buffer)
1187   "Bury this mail buffer."
1188   (let ((newbuf (other-buffer buffer)))
1189     (bury-buffer buffer)
1190     (if (and (fboundp 'frame-parameters)
1191              (cdr (assq 'dedicated (frame-parameters)))
1192              (not (null (delq (selected-frame) (visible-frame-list)))))
1193         (delete-frame (selected-frame))
1194       (switch-to-buffer newbuf))))
1195
1196 (defun message-send (&optional arg)
1197   "Send the message in the current buffer.
1198 If `message-interactive' is non-nil, wait for success indication
1199 or error messages, and inform user.
1200 Otherwise any failure is reported in a message back to
1201 the user from the mailer."
1202   (interactive "P")
1203   (when (if buffer-file-name
1204             (y-or-n-p (format "Send buffer contents as %s message? "
1205                               (if (message-mail-p)
1206                                   (if (message-news-p) "mail and news" "mail")
1207                                 "news")))
1208           (or (buffer-modified-p)
1209               (y-or-n-p "No changes in the buffer; really send? ")))
1210     ;; Make it possible to undo the coming changes.
1211     (undo-boundary)
1212     (message-fix-before-sending)
1213     (run-hooks 'message-send-hook)
1214     (message "Sending...")
1215     (when (and (or (not (message-news-p))
1216                    (and (or (not (memq 'news message-sent-message-via))
1217                             (y-or-n-p
1218                              "Already sent message via news; resend? "))
1219                         (funcall message-send-news-function arg)))
1220                (or (not (message-mail-p))
1221                    (and (or (not (memq 'mail message-sent-message-via))
1222                             (y-or-n-p
1223                              "Already sent message via mail; resend? "))
1224                         (message-send-mail arg))))
1225       (message-do-fcc)
1226       (when (fboundp 'mail-hist-put-headers-into-history)
1227         (mail-hist-put-headers-into-history))
1228       (run-hooks 'message-sent-hook)
1229       (message "Sending...done")
1230       ;; If buffer has no file, mark it as unmodified and delete autosave.
1231       (unless buffer-file-name
1232         (set-buffer-modified-p nil)
1233         (delete-auto-save-file-if-necessary t))
1234       ;; Delete other mail buffers and stuff.
1235       (message-do-send-housekeeping)
1236       (message-do-actions message-send-actions)
1237       ;; Return success.
1238       t)))
1239
1240 (defun message-fix-before-sending ()
1241   "Do various things to make the message nice before sending it."
1242   ;; Make sure there's a newline at the end of the message.
1243   (goto-char (point-max))
1244   (unless (bolp)
1245     (insert "\n")))
1246
1247 (defun message-add-action (action &rest types)
1248   "Add ACTION to be performed when doing an exit of type TYPES."
1249   (let (var)
1250     (while types
1251       (set (setq var (intern (format "message-%s-actions" (pop types))))
1252            (nconc (symbol-value var) (list action))))))
1253
1254 (defun message-do-actions (actions)
1255   "Perform all actions in ACTIONS."
1256   ;; Now perform actions on successful sending.
1257   (while actions
1258     (condition-case nil
1259         (cond 
1260          ;; A simple function.
1261          ((message-functionp (car actions))
1262           (funcall (car actions)))
1263          ;; Something to be evaled.
1264          (t
1265           (eval (car actions))))
1266       (error))
1267     (pop actions)))
1268
1269 (defun message-send-mail (&optional arg)
1270   (require 'mail-utils)
1271   (let ((tembuf (generate-new-buffer " message temp"))
1272         (case-fold-search nil)
1273         (news (message-news-p))
1274         (mailbuf (current-buffer)))
1275     (save-restriction
1276       (message-narrow-to-headers)
1277       ;; Insert some headers.
1278       (let ((message-deletable-headers
1279              (if news nil message-deletable-headers)))
1280         (message-generate-headers message-required-mail-headers))
1281       ;; Let the user do all of the above.
1282       (run-hooks 'message-header-hook))
1283     (unwind-protect
1284         (save-excursion
1285           (set-buffer tembuf)
1286           (erase-buffer)
1287           (insert-buffer-substring mailbuf)
1288           ;; Remove some headers.
1289           (save-restriction
1290             (message-narrow-to-headers)
1291             ;; Remove some headers.
1292             (message-remove-header message-ignored-mail-headers t))
1293           (goto-char (point-max))
1294           ;; require one newline at the end.
1295           (or (= (preceding-char) ?\n)
1296               (insert ?\n))
1297           (when (and news
1298                      (or (message-fetch-field "cc")
1299                          (message-fetch-field "to")))
1300             (message-insert-courtesy-copy))
1301           (funcall message-send-mail-function))
1302       (kill-buffer tembuf))
1303     (set-buffer mailbuf)
1304     (push 'mail message-sent-message-via)))
1305
1306 (defun message-send-mail-with-sendmail ()
1307   "Send off the prepared buffer with sendmail."
1308   (let ((errbuf (if message-interactive
1309                     (generate-new-buffer " sendmail errors")
1310                   0))
1311         resend-to-addresses delimline)
1312     (let ((case-fold-search t))
1313       (save-restriction
1314         (message-narrow-to-headers)
1315         (setq resend-to-addresses (message-fetch-field "resent-to")))
1316       ;; Change header-delimiter to be what sendmail expects.
1317       (goto-char (point-min))
1318       (re-search-forward
1319        (concat "^" (regexp-quote mail-header-separator) "\n"))
1320       (replace-match "\n")
1321       (backward-char 1)
1322       (setq delimline (point-marker))
1323       ;; Insert an extra newline if we need it to work around
1324       ;; Sun's bug that swallows newlines.
1325       (goto-char (1+ delimline))
1326       (when (eval message-mailer-swallows-blank-line)
1327         (newline))
1328       (when message-interactive
1329         (save-excursion
1330           (set-buffer errbuf)
1331           (erase-buffer))))
1332     (let ((default-directory "/"))
1333       (apply 'call-process-region
1334              (append (list (point-min) (point-max)
1335                            (if (boundp 'sendmail-program)
1336                                sendmail-program
1337                              "/usr/lib/sendmail")
1338                            nil errbuf nil "-oi")
1339                      ;; Always specify who from,
1340                      ;; since some systems have broken sendmails.
1341                      (list "-f" (user-login-name))
1342                      ;; These mean "report errors by mail"
1343                      ;; and "deliver in background".
1344                      (if (null message-interactive) '("-oem" "-odb"))
1345                      ;; Get the addresses from the message
1346                      ;; unless this is a resend.
1347                      ;; We must not do that for a resend
1348                      ;; because we would find the original addresses.
1349                      ;; For a resend, include the specific addresses.
1350                      (if resend-to-addresses
1351                          (list resend-to-addresses)
1352                        '("-t")))))
1353     (when message-interactive
1354       (save-excursion
1355         (set-buffer errbuf)
1356         (goto-char (point-min))
1357         (while (re-search-forward "\n\n* *" nil t)
1358           (replace-match "; "))
1359         (if (not (zerop (buffer-size)))
1360             (error "Sending...failed to %s"
1361                    (buffer-substring (point-min) (point-max)))))
1362       (when (bufferp errbuf)
1363         (kill-buffer errbuf)))))
1364
1365 (defun message-send-mail-with-mh ()
1366   "Send the prepared message buffer with mh."
1367   (let ((mh-previous-window-config nil)
1368         (name (make-temp-name
1369                (concat (file-name-as-directory message-autosave-directory)
1370                        "msg."))))
1371     (setq buffer-file-name name)
1372     (mh-send-letter)
1373     (condition-case ()
1374         (delete-file name)
1375       (error nil))))
1376
1377 (defun message-send-news (&optional arg)
1378   (let ((tembuf (generate-new-buffer " *message temp*"))
1379         (case-fold-search nil)
1380         (method (if (message-functionp message-post-method)
1381                     (funcall message-post-method arg)
1382                   message-post-method))
1383         (messbuf (current-buffer))
1384         result)
1385     (save-restriction
1386       (message-narrow-to-headers)
1387       ;; Insert some headers.
1388       (message-generate-headers message-required-news-headers)
1389       ;; Let the user do all of the above.
1390       (run-hooks 'message-header-hook))
1391     (when (message-check-news-syntax)
1392       (unwind-protect
1393           (save-excursion
1394             (set-buffer tembuf)
1395             (buffer-disable-undo (current-buffer))
1396             (erase-buffer) 
1397             (insert-buffer-substring messbuf)
1398             ;; Remove some headers.
1399             (save-restriction
1400               (message-narrow-to-headers)
1401               ;; Remove some headers.
1402               (message-remove-header message-ignored-news-headers t))
1403             (goto-char (point-max))
1404             ;; require one newline at the end.
1405             (or (= (preceding-char) ?\n)
1406                 (insert ?\n))
1407             (let ((case-fold-search t))
1408               ;; Remove the delimeter.
1409               (goto-char (point-min))
1410               (re-search-forward
1411                (concat "^" (regexp-quote mail-header-separator) "\n"))
1412               (replace-match "\n")
1413               (backward-char 1))
1414             (require (car method))
1415             (funcall (intern (format "%s-open-server" (car method)))
1416                      (cadr method) (cddr method))
1417             (setq result
1418                   (funcall (intern (format "%s-request-post" (car method))))))
1419         (kill-buffer tembuf))
1420       (set-buffer messbuf)
1421       (if result
1422           (push 'news message-sent-message-via)
1423         (message "Couldn't send message via news: %s"
1424                  (nnheader-get-report (car method)))
1425         nil))))
1426
1427 ;;;
1428 ;;; Header generation & syntax checking.
1429 ;;;
1430
1431 (defun message-check-news-syntax ()
1432   "Check the syntax of the message."
1433   (and 
1434    ;; We narrow to the headers and check them first.
1435    (save-excursion
1436      (save-restriction
1437        (message-narrow-to-headers)
1438        (and 
1439         ;; Check for commands in Subject.
1440         (or 
1441          (message-check-element 'subject-cmsg)
1442          (save-excursion
1443            (if (string-match "^cmsg " (message-fetch-field "subject"))
1444                (y-or-n-p
1445                 "The control code \"cmsg \" is in the subject. Really post? ")
1446              t)))
1447         ;; Check for multiple identical headers.
1448         (or (message-check-element 'multiple-headers)
1449             (save-excursion
1450               (let (found)
1451                 (while (and (not found) 
1452                             (re-search-forward "^[^ \t:]+: " nil t))
1453                   (save-excursion
1454                     (or (re-search-forward 
1455                          (concat "^" (setq found
1456                                            (buffer-substring 
1457                                             (match-beginning 0) 
1458                                             (- (match-end 0) 2))))
1459                          nil t)
1460                         (setq found nil))))
1461                 (if found
1462                     (y-or-n-p 
1463                      (format "Multiple %s headers. Really post? " found))
1464                   t))))
1465         ;; Check for Version and Sendsys.
1466         (or (message-check-element 'sendsys)
1467             (save-excursion
1468               (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1469                   (y-or-n-p
1470                    (format "The article contains a %s command. Really post? "
1471                            (buffer-substring (match-beginning 0) 
1472                                              (1- (match-end 0)))))
1473                 t)))
1474         ;; See whether we can shorten Followup-To.
1475         (or (message-check-element 'shorten-followup-to)
1476             (let ((newsgroups (message-fetch-field "newsgroups"))
1477                   (followup-to (message-fetch-field "followup-to"))
1478                   to)
1479               (when (and newsgroups (string-match "," newsgroups)
1480                          (not followup-to)
1481                          (not
1482                           (zerop
1483                            (length
1484                             (setq to (completing-read 
1485                                       "Followups to: (default all groups) " 
1486                                       (mapcar (lambda (g) (list g))
1487                                               (cons "poster" 
1488                                                     (message-tokenize-header 
1489                                                      newsgroups)))))))))
1490                 (goto-char (point-min))
1491                 (insert "Followup-To: " to "\n"))
1492               t))
1493
1494         ;; Check for Approved.
1495         (or (message-check-element 'approved)
1496             (save-excursion
1497               (if (re-search-forward "^Approved:" nil t)
1498                   (y-or-n-p
1499                    "The article contains an Approved header. Really post? ")
1500                 t)))
1501         ;; Check the Message-Id header.
1502         (or (message-check-element 'message-id)
1503             (save-excursion
1504               (let* ((case-fold-search t)
1505                      (message-id (message-fetch-field "message-id")))
1506                 (or (not message-id)
1507                     (and (string-match "@" message-id)
1508                          (string-match "@[^\\.]*\\." message-id))
1509                     (y-or-n-p
1510                      (format 
1511                       "The Message-ID looks strange: \"%s\". Really post? "
1512                       message-id))))))
1513         ;; Check the Subject header.
1514         (or 
1515          (message-check-element 'subject)
1516          (save-excursion
1517            (let* ((case-fold-search t)
1518                   (subject (message-fetch-field "subject")))
1519              (or
1520               (and subject
1521                    (not (string-match "\\`[ \t]*\\'" subject)))
1522               (progn
1523                 (message 
1524                  "The subject field is empty or missing.  Posting is denied.")
1525                 nil)))))
1526         ;; Check the Newsgroups & Followup-To headers.
1527         (or
1528          (message-check-element 'existing-newsgroups)
1529          (let* ((case-fold-search t)
1530                 (newsgroups (message-fetch-field "newsgroups"))
1531                 (followup-to (message-fetch-field "followup-to"))
1532                 (groups (message-tokenize-header
1533                          (if followup-to
1534                              (concat newsgroups "," followup-to)
1535                            newsgroups)))
1536                 (hashtb (and (boundp 'gnus-active-hashtb)
1537                              gnus-active-hashtb))
1538                 errors)
1539            (if (not hashtb)
1540                t
1541              (while groups
1542                (unless (boundp (intern (car groups) hashtb))
1543                  (push (car groups) errors))
1544                (pop groups))
1545              (if (not errors)
1546                  t
1547                (y-or-n-p
1548                 (format
1549                  "Really post to %s unknown group%s: %s "
1550                  (if (= (length errors) 1) "this" "these")
1551                  (if (= (length errors) 1) "" "s")
1552                  (mapconcat 'identity errors ", ")))))))
1553         ;; Check the Newsgroups & Followup-To headers for syntax errors.
1554         (or
1555          (message-check-element 'valid-newsgroups)
1556          (let ((case-fold-search t)
1557                (headers '("Newsgroups" "Followup-To"))
1558                header error)
1559            (while (and headers (not error))
1560              (when (setq header (mail-fetch-field (car headers)))
1561                (if (or
1562                     (not (string-match
1563                           "\\`\\([-.a-zA-Z0-9]+\\)?\\(,[-.a-zA-Z0-9]+\\)*\\'"
1564                           header))
1565                     (memq 
1566                      nil (mapcar 
1567                           (lambda (g)
1568                             (not (string-match "\\.\\'\\|\\.\\." g)))
1569                           (message-tokenize-header header ","))))
1570                    (setq error t)))
1571              (unless error
1572                (pop headers)))
1573            (if (not error)
1574                t
1575              (y-or-n-p
1576               (format "The %s header looks odd: \"%s\".  Really post? "
1577                       (car headers) header)))))
1578         ;; Check the From header.
1579         (or 
1580          (message-check-element 'from)
1581          (save-excursion
1582            (let* ((case-fold-search t)
1583                   (from (message-fetch-field "from")))
1584              (cond
1585               ((not from)
1586                (message "There is no From line.  Posting is denied.")
1587                nil)
1588               ((not (string-match "@[^\\.]*\\." from))
1589                (message
1590                 "Denied posting -- the From looks strange: \"%s\"." from)
1591                nil)
1592               ((string-match "@[^@]*@" from)
1593                (message 
1594                 "Denied posting -- two \"@\"'s in the From header: %s." from)
1595                nil)
1596               ((string-match "(.*).*(.*)" from)
1597                (message
1598                 "Denied posting -- the From header looks strange: \"%s\"." 
1599                 from)
1600                nil)
1601               (t t))))))))
1602    ;; Check for long lines.
1603    (or (message-check-element 'long-lines)
1604        (save-excursion
1605          (goto-char (point-min))
1606          (re-search-forward
1607           (concat "^" (regexp-quote mail-header-separator) "$"))
1608          (while (and
1609                  (progn
1610                    (end-of-line)
1611                    (< (current-column) 80))
1612                  (zerop (forward-line 1))))
1613          (or (bolp)
1614              (eobp)
1615              (y-or-n-p
1616               "You have lines longer than 79 characters.  Really post? "))))
1617    ;; Check whether the article is empty.
1618    (or (message-check-element 'empty)
1619        (save-excursion
1620          (goto-char (point-min))
1621          (re-search-forward
1622           (concat "^" (regexp-quote mail-header-separator) "$"))
1623          (forward-line 1)
1624          (let ((b (point)))
1625            (or (re-search-forward message-signature-separator nil t)
1626                (goto-char (point-max)))
1627            (beginning-of-line)
1628            (or (re-search-backward "[^ \n\t]" b t)
1629                (y-or-n-p "Empty article.  Really post? ")))))
1630    ;; Check for control characters.
1631    (or (message-check-element 'control-chars)
1632        (save-excursion
1633          (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1634              (y-or-n-p 
1635               "The article contains control characters. Really post? ")
1636            t)))
1637    ;; Check excessive size.
1638    (or (message-check-element 'size)
1639        (if (> (buffer-size) 60000)
1640            (y-or-n-p
1641             (format "The article is %d octets long. Really post? "
1642                     (buffer-size)))
1643          t))
1644    ;; Check whether any new text has been added.
1645    (or (message-check-element 'new-text)
1646        (not message-checksum)
1647        (not (eq (message-checksum) message-checksum))
1648        (y-or-n-p
1649         "It looks like no new text has been added.  Really post? "))
1650    ;; Check the length of the signature.
1651    (or
1652     (message-check-element 'signature)
1653     (progn
1654       (goto-char (point-max))
1655       (if (or (not (re-search-backward "^-- $" nil t))
1656               (search-forward message-forward-end-separator nil t))
1657           t
1658         (if (> (count-lines (point) (point-max)) 5)
1659             (y-or-n-p
1660              (format
1661               "Your .sig is %d lines; it should be max 4.  Really post? "
1662               (count-lines (point) (point-max))))
1663           t))))))
1664
1665 (defun message-check-element (type)
1666   "Returns non-nil if this type is not to be checked."
1667   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1668       t
1669     (let ((able (assq type message-syntax-checks)))
1670       (and (consp able)
1671            (eq (cdr able) 'disabled)))))
1672
1673 (defun message-checksum ()
1674   "Return a \"checksum\" for the current buffer."
1675   (let ((sum 0))
1676     (save-excursion
1677       (goto-char (point-min))
1678       (re-search-forward
1679        (concat "^" (regexp-quote mail-header-separator) "$"))
1680       (while (not (eobp))
1681         (setq sum (logxor sum (following-char)))
1682         (forward-char 1)))
1683     sum))
1684
1685 (defun message-do-fcc ()
1686   "Process Fcc headers in the current buffer."
1687   (let ((case-fold-search t)
1688         (buf (current-buffer))
1689         list file)
1690     (save-excursion
1691       (set-buffer (get-buffer-create " *message temp*"))
1692       (buffer-disable-undo (current-buffer))
1693       (erase-buffer)
1694       (insert-buffer-substring buf)
1695       (save-restriction
1696         (message-narrow-to-headers)
1697         (while (setq file (message-fetch-field "fcc"))
1698           (push file list)
1699           (message-remove-header "fcc" nil t)))
1700       (goto-char (point-min))
1701       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
1702       (replace-match "" t t)
1703       ;; Process FCC operations.
1704       (while list
1705         (setq file (pop list))
1706         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
1707             ;; Pipe the article to the program in question.
1708             (call-process-region (point-min) (point-max) shell-file-name
1709                                  nil nil nil "-c" (match-string 1 file))
1710           ;; Save the article.
1711           (setq file (expand-file-name file))
1712           (unless (file-exists-p (file-name-directory file))
1713             (make-directory (file-name-directory file) t))
1714           (if (and message-fcc-handler-function
1715                    (not (eq message-fcc-handler-function 'rmail-output)))
1716               (funcall message-fcc-handler-function file)
1717             (if (and (file-readable-p file) (mail-file-babyl-p file))
1718                 (rmail-output file 1)
1719               (let ((mail-use-rfc822 t))
1720                 (rmail-output file 1 t t))))))
1721       (kill-buffer (current-buffer)))))
1722
1723 (defun message-cleanup-headers ()
1724   "Do various automatic cleanups of the headers."
1725   ;; Remove empty lines in the header.
1726   (save-restriction
1727     (message-narrow-to-headers)
1728     (while (re-search-forward "^[ \t]*\n" nil t)
1729       (replace-match "" t t)))
1730
1731   ;; Correct Newsgroups and Followup-To headers: change sequence of
1732   ;; spaces to comma and eliminate spaces around commas.  Eliminate
1733   ;; embedded line breaks.
1734   (goto-char (point-min))
1735   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
1736     (save-restriction
1737       (narrow-to-region
1738        (point)
1739        (if (re-search-forward "^[^ \t]" nil t)
1740            (match-beginning 0)
1741          (forward-line 1)
1742          (point)))
1743       (goto-char (point-min))
1744       (while (re-search-forward "\n[ \t]+" nil t)
1745         (replace-match " " t t))        ;No line breaks (too confusing)
1746       (goto-char (point-min))
1747       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
1748         (replace-match "," t t))
1749       (goto-char (point-min))
1750       ;; Remove trailing commas.
1751       (when (re-search-forward ",+$" nil t)
1752         (replace-match "" t t)))))
1753
1754 (defun message-make-date ()
1755   "Make a valid data header."
1756   (let ((now (current-time)))
1757     (timezone-make-date-arpa-standard 
1758      (current-time-string now) (current-time-zone now))))
1759
1760 (defun message-make-message-id ()
1761   "Make a unique Message-ID."
1762   (concat "<" (message-unique-id) 
1763           (let ((psubject (save-excursion (message-fetch-field "subject"))))
1764             (if (and message-reply-headers
1765                      (mail-header-references message-reply-headers)
1766                      (mail-header-subject message-reply-headers)
1767                      psubject
1768                      (mail-header-subject message-reply-headers)
1769                      (not (string= 
1770                            (message-strip-subject-re
1771                             (mail-header-subject message-reply-headers))
1772                            (message-strip-subject-re psubject))))
1773                 "_-_" ""))
1774           "@" (message-make-fqdm) ">"))
1775
1776 (defvar message-unique-id-char nil)
1777
1778 ;; If you ever change this function, make sure the new version
1779 ;; cannot generate IDs that the old version could.
1780 ;; You might for example insert a "." somewhere (not next to another dot
1781 ;; or string boundary), or modify the "fsf" string.
1782 (defun message-unique-id ()
1783   ;; Don't use microseconds from (current-time), they may be unsupported.
1784   ;; Instead we use this randomly inited counter.
1785   (setq message-unique-id-char
1786         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
1787            ;; (current-time) returns 16-bit ints,
1788            ;; and 2^16*25 just fits into 4 digits i base 36.
1789            (* 25 25)))
1790   (let ((tm (current-time)))
1791     (concat
1792      (if (memq system-type '(ms-dos emx vax-vms))
1793          (let ((user (downcase (user-login-name))))
1794            (while (string-match "[^a-z0-9_]" user)
1795              (aset user (match-beginning 0) ?_))
1796            user)
1797        (message-number-base36 (user-uid) -1))
1798      (message-number-base36 (+ (car   tm) 
1799                                (lsh (% message-unique-id-char 25) 16)) 4)
1800      (message-number-base36 (+ (nth 1 tm)
1801                                (lsh (/ message-unique-id-char 25) 16)) 4)
1802      ;; Append the newsreader name, because while the generated
1803      ;; ID is unique to this newsreader, other newsreaders might
1804      ;; otherwise generate the same ID via another algorithm.
1805      ".fsf")))
1806
1807 (defun message-number-base36 (num len)
1808   (if (if (< len 0) (<= num 0) (= len 0))
1809       ""
1810     (concat (message-number-base36 (/ num 36) (1- len))
1811             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
1812                                   (% num 36))))))
1813
1814 (defun message-make-organization ()
1815   "Make an Organization header."
1816   (let* ((organization 
1817           (or (getenv "ORGANIZATION")
1818               (when message-user-organization
1819                 (if (message-functionp message-user-organization)
1820                     (funcall message-user-organization)
1821                   message-user-organization)))))
1822     (save-excursion
1823       (message-set-work-buffer)
1824       (cond ((stringp organization)
1825              (insert organization))
1826             ((and (eq t organization)
1827                   message-user-organization-file
1828                   (file-exists-p message-user-organization-file))
1829              (insert-file-contents message-user-organization-file)))
1830       (goto-char (point-min))
1831       (while (re-search-forward "[\t\n]+" nil t)
1832         (replace-match "" t t))
1833       (unless (zerop (buffer-size))
1834         (buffer-string)))))
1835
1836 (defun message-make-lines ()
1837   "Count the number of lines and return numeric string."
1838   (save-excursion
1839     (save-restriction
1840       (widen)
1841       (goto-char (point-min))
1842       (re-search-forward 
1843        (concat "^" (regexp-quote mail-header-separator) "$"))
1844       (forward-line 1)
1845       (int-to-string (count-lines (point) (point-max))))))
1846
1847 (defun message-make-in-reply-to ()
1848   "Return the In-Reply-To header for this message."
1849   (when message-reply-headers
1850     (let ((from (mail-header-from message-reply-headers))
1851           (date (mail-header-date message-reply-headers)))
1852       (when from
1853         (let ((stop-pos 
1854                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
1855           (concat (if stop-pos (substring from 0 stop-pos) from)
1856                   "'s message of " 
1857                   (if (or (not date) (string= date ""))
1858                       "(unknown date)" date)))))))
1859
1860 (defun message-make-distribution ()
1861   "Make a Distribution header."
1862   (let ((orig-distribution (message-fetch-reply-field "distribution")))
1863     (cond ((message-functionp message-distribution-function)
1864            (funcall message-distribution-function))
1865           (t orig-distribution))))
1866
1867 (defun message-make-expires ()
1868   "Return an Expires header based on `message-expires'."
1869   (let ((current (current-time))
1870         (future (* 1.0 message-expires 60 60 24)))
1871     ;; Add the future to current.
1872     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
1873     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
1874     ;; Return the date in the future in UT.
1875     (timezone-make-date-arpa-standard 
1876      (current-time-string current) (current-time-zone current) '(0 "UT"))))
1877
1878 (defun message-make-path ()
1879   "Return uucp path."
1880   (let ((login-name (user-login-name)))
1881     (cond ((null message-user-path)
1882            (concat (system-name) "!" login-name))
1883           ((stringp message-user-path)
1884            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
1885            (concat message-user-path "!" login-name))
1886           (t login-name))))
1887
1888 (defun message-make-from ()
1889   "Make a From header."
1890   (let* ((login (message-make-address))
1891          (fullname 
1892           (or (and (boundp 'user-full-name)
1893                    user-full-name)
1894               (user-full-name))))
1895     (when (string= fullname "&")
1896       (setq fullname (user-login-name)))
1897     (save-excursion
1898       (message-set-work-buffer)
1899       (cond 
1900        ((or (null message-from-style)
1901             (equal fullname ""))
1902         (insert login))
1903        ((or (eq message-from-style 'angles)
1904             (and (not (eq message-from-style 'parens))
1905                  ;; Use angles if no quoting is needed, or if parens would
1906                  ;; need quoting too.
1907                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
1908                      (let ((tmp (concat fullname nil)))
1909                        (while (string-match "([^()]*)" tmp)
1910                          (aset tmp (match-beginning 0) ?-)
1911                          (aset tmp (1- (match-end 0)) ?-))
1912                        (string-match "[\\()]" tmp)))))
1913         (insert fullname)
1914         (goto-char (point-min))
1915         ;; Look for a character that cannot appear unquoted
1916         ;; according to RFC 822.
1917         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
1918           ;; Quote fullname, escaping specials.
1919           (goto-char (point-min))
1920           (insert "\"")
1921           (while (re-search-forward "[\"\\]" nil 1)
1922             (replace-match "\\\\\\&" t))
1923           (insert "\""))
1924         (insert " <" login ">"))
1925        (t                               ; 'parens or default
1926         (insert login " (")
1927         (let ((fullname-start (point)))
1928           (insert fullname)
1929           (goto-char fullname-start)
1930           ;; RFC 822 says \ and nonmatching parentheses
1931           ;; must be escaped in comments.
1932           ;; Escape every instance of ()\ ...
1933           (while (re-search-forward "[()\\]" nil 1)
1934             (replace-match "\\\\\\&" t))
1935           ;; ... then undo escaping of matching parentheses,
1936           ;; including matching nested parentheses.
1937           (goto-char fullname-start)
1938           (while (re-search-forward 
1939                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
1940                     nil 1)
1941             (replace-match "\\1(\\3)" t)
1942             (goto-char fullname-start)))
1943         (insert ")")))
1944       (buffer-string))))
1945
1946 (defun message-make-sender ()
1947   "Return the \"real\" user address.
1948 This function tries to ignore all user modifications, and 
1949 give as trustworthy answer as possible."
1950   (concat (user-login-name) "@" (system-name)))
1951
1952 (defun message-make-address ()
1953   "Make the address of the user."
1954   (or (message-user-mail-address)
1955       (concat (user-login-name) "@" (message-make-domain))))
1956
1957 (defun message-user-mail-address ()
1958   "Return the pertinent part of `user-mail-address'."
1959   (when user-mail-address
1960     (nth 1 (mail-extract-address-components user-mail-address))))
1961
1962 (defun message-make-fqdm ()
1963   "Return user's fully qualified domain name."
1964   (let ((system-name (system-name)))
1965     (cond 
1966      ((string-match "[^.]\\.[^.]" system-name)
1967       ;; `system-name' returned the right result.
1968       system-name)
1969      ;; We try `user-mail-address' as a backup.
1970      ((string-match "@\\(.*\\)\\'" (message-user-mail-address))
1971       (match-string 1 user-mail-address))
1972      ;; Try `mail-host-address'.
1973      ((and (boundp 'mail-host-address)
1974            mail-host-address)
1975       mail-host-address)
1976      ;; Default to this bogus thing.
1977      (t
1978       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
1979
1980 (defun message-make-host-name ()
1981   "Return the name of the host."
1982   (let ((fqdm (message-make-fqdm)))
1983     (string-match "^[^.]+\\." fqdm)
1984     (substring fqdm 0 (1- (match-end 0)))))
1985
1986 (defun message-make-domain ()
1987   "Return the domain name."
1988   (or mail-host-address
1989       (message-make-fqdm)))
1990
1991 (defun message-generate-headers (headers)
1992   "Prepare article HEADERS.
1993 Headers already prepared in the buffer are not modified."
1994   (save-restriction
1995     (message-narrow-to-headers)
1996     (let* ((Date (message-make-date))
1997            (Message-ID (message-make-message-id))
1998            (Organization (message-make-organization))
1999            (From (message-make-from))
2000            (Path (message-make-path))
2001            (Subject nil)
2002            (Newsgroups nil)
2003            (In-Reply-To (message-make-in-reply-to))
2004            (To nil)
2005            (Distribution (message-make-distribution))
2006            (Lines (message-make-lines))
2007            (X-Newsreader message-newsreader)
2008            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2009                           message-mailer))
2010            (Expires (message-make-expires))
2011            (case-fold-search t)
2012            header value elem)
2013       ;; First we remove any old generated headers.
2014       (let ((headers message-deletable-headers))
2015         (while headers
2016           (goto-char (point-min))
2017           (and (re-search-forward 
2018                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2019                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2020                (message-delete-line))
2021           (pop headers)))
2022       ;; Go through all the required headers and see if they are in the
2023       ;; articles already. If they are not, or are empty, they are
2024       ;; inserted automatically - except for Subject, Newsgroups and
2025       ;; Distribution. 
2026       (while headers
2027         (goto-char (point-min))
2028         (setq elem (pop headers))
2029         (if (consp elem)
2030             (if (eq (car elem) 'optional)
2031                 (setq header (cdr elem))
2032               (setq header (car elem)))
2033           (setq header elem))
2034         (when (or (not (re-search-forward 
2035                         (concat "^" (downcase (symbol-name header)) ":") 
2036                         nil t))
2037                   (progn
2038                     ;; The header was found. We insert a space after the
2039                     ;; colon, if there is none.
2040                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2041                     ;; Find out whether the header is empty...
2042                     (looking-at "[ \t]*$")))
2043           ;; So we find out what value we should insert.
2044           (setq value
2045                 (cond 
2046                  ((and (consp elem) (eq (car elem) 'optional))
2047                   ;; This is an optional header.  If the cdr of this
2048                   ;; is something that is nil, then we do not insert
2049                   ;; this header.
2050                   (setq header (cdr elem))
2051                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2052                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2053                  ((consp elem)
2054                   ;; The element is a cons.  Either the cdr is a
2055                   ;; string to be inserted verbatim, or it is a
2056                   ;; function, and we insert the value returned from
2057                   ;; this function.
2058                   (or (and (stringp (cdr elem)) (cdr elem))
2059                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2060                  ((and (boundp header) (symbol-value header))
2061                   ;; The element is a symbol.  We insert the value
2062                   ;; of this symbol, if any.
2063                   (symbol-value header))
2064                  (t
2065                   ;; We couldn't generate a value for this header,
2066                   ;; so we just ask the user.
2067                   (read-from-minibuffer
2068                    (format "Empty header for %s; enter value: " header)))))
2069           ;; Finally insert the header.
2070           (when (and value 
2071                      (not (equal value "")))
2072             (save-excursion
2073               (if (bolp)
2074                   (progn
2075                     ;; This header didn't exist, so we insert it.
2076                     (goto-char (point-max))
2077                     (insert (symbol-name header) ": " value "\n")
2078                     (forward-line -1))
2079                 ;; The value of this header was empty, so we clear
2080                 ;; totally and insert the new value.
2081                 (delete-region (point) (message-point-at-eol))
2082                 (insert value))
2083               ;; Add the deletable property to the headers that require it.
2084               (and (memq header message-deletable-headers)
2085                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2086                    (add-text-properties 
2087                     (point) (match-end 0)
2088                     '(message-deletable t face italic) (current-buffer)))))))
2089       ;; Insert new Sender if the From is strange. 
2090       (let ((from (message-fetch-field "from"))
2091             (sender (message-fetch-field "sender"))
2092             (secure-sender (message-make-sender)))
2093         (when (and from 
2094                    (not (message-check-element 'sender))
2095                    (not (string=
2096                          (downcase
2097                           (cadr (mail-extract-address-components from)))
2098                          (downcase secure-sender)))
2099                    (or (null sender)
2100                        (not 
2101                         (string=
2102                          (downcase
2103                           (cadr (mail-extract-address-components sender)))
2104                          (downcase secure-sender)))))
2105           (goto-char (point-min))    
2106           ;; Rename any old Sender headers to Original-Sender.
2107           (when (re-search-forward "^Sender:" nil t)
2108             (beginning-of-line)
2109             (insert "Original-")
2110             (beginning-of-line))
2111           (insert "Sender: " secure-sender "\n"))))))
2112
2113 (defun message-insert-courtesy-copy ()
2114   "Insert a courtesy message in mail copies of combined messages."
2115   (save-excursion
2116     (save-restriction
2117       (message-narrow-to-headers)
2118       (let ((newsgroups (message-fetch-field "newsgroups")))
2119         (when newsgroups
2120           (goto-char (point-max))
2121           (insert "Posted-To: " newsgroups "\n"))))
2122     (forward-line 1)
2123     (insert message-courtesy-message)))
2124     
2125 ;;;
2126 ;;; Setting up a message buffer
2127 ;;;
2128
2129 (defun message-fill-header (header value)
2130   (let ((begin (point))
2131         (fill-column 78)
2132         (fill-prefix "\t"))
2133     (insert (capitalize (symbol-name header))
2134             ": "
2135             (if (consp value) (car value) value)
2136             "\n")
2137     (save-restriction
2138       (narrow-to-region begin (point))
2139       (fill-region-as-paragraph begin (point))
2140       ;; Tapdance around looong Message-IDs.
2141       (forward-line -1)
2142       (when (looking-at "[ \t]*$")
2143         (message-delete-line))
2144       (goto-char begin)
2145       (re-search-forward ":" nil t)
2146       (when (looking-at "\n[ \t]+")
2147         (replace-match " " t t))
2148       (goto-char (point-max)))))
2149
2150 (defun message-position-point ()
2151   "Move point to where the user probably wants to find it."
2152   (message-narrow-to-headers)
2153   (cond 
2154    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2155     (search-backward ":" )
2156     (widen)
2157     (forward-char 1)
2158     (if (= (following-char) ? )
2159         (forward-char 1)
2160       (insert " ")))
2161    (t
2162     (goto-char (point-max))
2163     (widen)
2164     (forward-line 1)
2165     (unless (looking-at "$")
2166       (forward-line 2)))
2167    (sit-for 0)))
2168
2169 (defun message-buffer-name (type &optional to group)
2170   "Return a new (unique) buffer name based on TYPE and TO."
2171   (if message-generate-new-buffers
2172       (generate-new-buffer-name
2173        (concat "*" type
2174                (if to
2175                    (concat " to "
2176                            (or (car (mail-extract-address-components to))
2177                                to) "")
2178                  "")
2179                (if group (concat " on " group) "")
2180                "*"))
2181     (format "*%s message*" type)))
2182
2183 (defun message-pop-to-buffer (name)
2184   "Pop to buffer NAME, and warn if it already exists and is modified."
2185   (let ((buffer (get-buffer name)))
2186     (if (and buffer
2187              (buffer-name buffer))
2188         (progn
2189           (set-buffer (pop-to-buffer buffer))
2190           (when (and (buffer-modified-p)
2191                      (not (y-or-n-p
2192                            "Message already being composed; erase? ")))
2193             (error "Message being composed")))
2194       (set-buffer (pop-to-buffer name))))
2195   (erase-buffer)
2196   (message-mode))
2197
2198 (defun message-do-send-housekeeping ()
2199   "Kill old message buffers."
2200   ;; We might have sent this buffer already.  Delete it from the
2201   ;; list of buffers.
2202   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2203   (when (and message-max-buffers
2204              (>= (length message-buffer-list) message-max-buffers))
2205     ;; Kill the oldest buffer -- unless it has been changed.
2206     (let ((buffer (pop message-buffer-list)))
2207       (when (and (buffer-name buffer)
2208                  (not (buffer-modified-p buffer)))
2209         (kill-buffer buffer))))
2210   ;; Rename the buffer.
2211   (when (string-match "\\`\\*" (buffer-name))
2212     (rename-buffer 
2213      (concat "*sent " (substring (buffer-name) (match-end 0))) t))
2214   ;; Push the current buffer onto the list.
2215   (when message-max-buffers
2216     (setq message-buffer-list 
2217           (nconc message-buffer-list (list (current-buffer))))))
2218
2219 (defun message-setup (headers &optional replybuffer actions)
2220   (when actions
2221     (setq message-send-actions actions))
2222   (setq message-reply-buffer replybuffer)
2223   (goto-char (point-min))
2224   ;; Insert all the headers.
2225   (mail-header-format 
2226    (let ((h headers)
2227          (alist message-header-format-alist))
2228      (while h
2229        (unless (assq (caar h) message-header-format-alist)
2230          (push (list (caar h)) alist))
2231        (pop h))
2232      alist)
2233    headers)
2234   (forward-line -1)
2235   (when message-default-headers
2236     (insert message-default-headers))
2237   (put-text-property
2238    (point)
2239    (progn
2240      (insert mail-header-separator "\n")
2241      (point))
2242    'read-only nil)
2243   (forward-line -1)
2244   (when (message-news-p)
2245     (when message-default-news-headers
2246       (insert message-default-news-headers))
2247     (when message-generate-headers-first
2248       (message-generate-headers
2249        (delq 'Lines
2250              (delq 'Subject
2251                    (copy-sequence message-required-news-headers))))))
2252   (when (message-mail-p)
2253     (when message-default-mail-headers
2254       (insert message-default-mail-headers))
2255     (when message-generate-headers-first
2256       (message-generate-headers
2257        (delq 'Lines
2258              (delq 'Subject
2259                    (copy-sequence message-required-mail-headers))))))
2260   (message-insert-signature)
2261   (message-set-auto-save-file-name)
2262   (save-restriction
2263     (message-narrow-to-headers)
2264     (run-hooks 'message-header-setup-hook))
2265   (set-buffer-modified-p nil)
2266   (run-hooks 'message-setup-hook)
2267   (message-position-point)
2268   (undo-boundary))
2269
2270 (defun message-set-auto-save-file-name ()
2271   "Associate the message buffer with a file in the drafts directory."
2272   (when message-autosave-directory
2273     (unless (file-exists-p message-autosave-directory)
2274       (make-directory message-autosave-directory t))
2275     (let ((name (make-temp-name
2276                  (concat (file-name-as-directory message-autosave-directory)
2277                          "msg."))))
2278       (setq buffer-auto-save-file-name
2279             (save-excursion
2280               (prog1
2281                   (progn
2282                     (set-buffer (get-buffer-create " *draft tmp*"))
2283                     (setq buffer-file-name name)
2284                     (make-auto-save-file-name))
2285                 (kill-buffer (current-buffer)))))
2286       (clear-visited-file-modtime))))
2287
2288 \f
2289
2290 ;;;
2291 ;;; Commands for interfacing with message
2292 ;;;
2293
2294 ;;;###autoload
2295 (defun message-mail (&optional to subject)
2296   "Start editing a mail message to be sent."
2297   (interactive)
2298   (message-pop-to-buffer (message-buffer-name "mail" to))
2299   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2300
2301 ;;;###autoload
2302 (defun message-news (&optional newsgroups subject)
2303   "Start editing a news article to be sent."
2304   (interactive)
2305   (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2306   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2307                    (Subject . ,(or subject "")))))
2308
2309 ;;;###autoload
2310 (defun message-reply (&optional to-address wide ignore-reply-to)
2311   "Start editing a reply to the article in the current buffer."
2312   (interactive)
2313   (let ((cur (current-buffer))
2314         from subject date reply-to to cc
2315         references message-id follow-to 
2316         mct never-mct gnus-warning)
2317     (save-restriction
2318       (narrow-to-region
2319        (goto-char (point-min))
2320        (if (search-forward "\n\n" nil t)
2321            (1- (point))
2322          (point-max)))
2323       ;; Allow customizations to have their say.
2324       (if (not wide)
2325           ;; This is a regular reply.
2326           (if (message-functionp message-reply-to-function)
2327               (setq follow-to (funcall message-reply-to-function)))
2328         ;; This is a followup.
2329         (if (message-functionp message-wide-reply-to-function)
2330             (save-excursion
2331               (setq follow-to
2332                     (funcall message-wide-reply-to-function)))))
2333       ;; Find all relevant headers we need.
2334       (setq from (message-fetch-field "from")
2335             date (message-fetch-field "date") 
2336             subject (or (message-fetch-field "subject") "none")
2337             to (message-fetch-field "to")
2338             cc (message-fetch-field "cc")
2339             mct (message-fetch-field "mail-copies-to")
2340             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2341             references (message-fetch-field "references")
2342             message-id (message-fetch-field "message-id"))
2343       ;; Remove any (buggy) Re:'s that are present and make a
2344       ;; proper one.
2345       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2346         (setq subject (substring subject (match-end 0))))
2347       (setq subject (concat "Re: " subject))
2348
2349       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2350                  (string-match "<[^>]+>" gnus-warning))
2351         (setq message-id (match-string 0 gnus-warning)))
2352             
2353       ;; Handle special values of Mail-Copies-To.
2354       (when mct
2355         (cond ((equal (downcase mct) "never")
2356                (setq never-mct t)
2357                (setq mct nil))
2358               ((equal (downcase mct) "always")
2359                (setq mct (or reply-to from)))))
2360
2361       (unless follow-to
2362         (if (or (not wide)
2363                 to-address)
2364             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2365           (let (ccalist)
2366             (save-excursion
2367               (message-set-work-buffer)
2368               (unless never-mct
2369                 (insert (or reply-to from "")))
2370               (insert 
2371                (if (bolp) "" ", ") (or to "")
2372                (if mct (concat (if (bolp) "" ", ") mct) "")
2373                (if cc (concat (if (bolp) "" ", ") cc) ""))
2374               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2375               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2376                         (erase-buffer)))
2377               (goto-char (point-min))
2378               (setq ccalist
2379                     (mapcar
2380                      (lambda (addr)
2381                        (cons (mail-strip-quoted-names addr) addr))
2382                      (nreverse (mail-parse-comma-list))))
2383               (let ((s ccalist))
2384                 (while s
2385                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2386             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2387             (when ccalist
2388               (push (cons 'Cc
2389                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2390                     follow-to)))))
2391       (widen))
2392
2393     (message-pop-to-buffer (message-buffer-name "reply" from))
2394
2395     (setq message-reply-headers
2396           (vector 0 subject from date message-id references 0 0 ""))
2397
2398     (message-setup
2399      `((Subject . ,subject)
2400        ,@follow-to 
2401        ,@(if (or references message-id)
2402              `((References . ,(concat (or references "") (and references " ")
2403                                       (or message-id ""))))
2404            nil))
2405      cur)))
2406
2407 ;;;###autoload
2408 (defun message-wide-reply (&optional to-address)
2409   (interactive)
2410   (message-reply to-address t))
2411
2412 ;;;###autoload
2413 (defun message-followup ()
2414   (interactive)
2415   (let ((cur (current-buffer))
2416         from subject date reply-to mct
2417         references message-id follow-to 
2418         followup-to distribution newsgroups gnus-warning)
2419     (save-restriction
2420       (narrow-to-region
2421        (goto-char (point-min))
2422        (if (search-forward "\n\n" nil t)
2423            (1- (point))
2424          (point-max)))
2425       (when (message-functionp message-followup-to-function)
2426         (setq follow-to
2427               (funcall message-followup-to-function)))
2428       (setq from (message-fetch-field "from")
2429             date (message-fetch-field "date") 
2430             subject (or (message-fetch-field "subject") "none")
2431             references (message-fetch-field "references")
2432             message-id (message-fetch-field "message-id")
2433             followup-to (message-fetch-field "followup-to")
2434             newsgroups (message-fetch-field "newsgroups")
2435             reply-to (message-fetch-field "reply-to")
2436             distribution (message-fetch-field "distribution")
2437             mct (message-fetch-field "mail-copies-to"))
2438       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2439                  (string-match "<[^>]+>" gnus-warning))
2440         (setq message-id (match-string 0 gnus-warning)))
2441       ;; Remove bogus distribution.
2442       (and (stringp distribution)
2443            (string-match "world" distribution)
2444            (setq distribution nil))
2445       ;; Remove any (buggy) Re:'s that are present and make a
2446       ;; proper one.
2447       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2448         (setq subject (substring subject (match-end 0))))
2449       (setq subject (concat "Re: " subject))
2450       (widen))
2451
2452     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2453
2454     (message-setup
2455      `((Subject . ,subject)
2456        ,@(cond 
2457           (follow-to follow-to)
2458           ((and followup-to message-use-followup-to)
2459            (list
2460             (cond 
2461              ((equal (downcase followup-to) "poster")
2462               (if (or (eq message-use-followup-to 'use)
2463                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2464 You should normally obey the Followup-To: header.
2465
2466 `Followup-To: poster' sends your response via e-mail instead of news.
2467
2468 A typical situation where `Followup-To: poster' is used is when the poster
2469 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2470                   (cons 'To (or reply-to from ""))
2471                 (cons 'Newsgroups newsgroups)))
2472              (t
2473               (if (or (equal followup-to newsgroups)
2474                       (not (eq message-use-followup-to 'ask))
2475                       (message-y-or-n-p
2476                        (concat "Obey Followup-To: " followup-to "? ") t "\
2477 You should normally obey the Followup-To: header.
2478
2479         `Followup-To: " followup-to "'
2480 directs your response to " (if (string-match "," followup-to)
2481                                "the specified newsgroups"
2482                              "that newsgroup only") ".
2483
2484 If a message is posted to several newsgroups, Followup-To is often
2485 used to direct the following discussion to one newsgroup only,
2486 because discussions that are spread over several newsgroup tend to
2487 be fragmented and very difficult to follow.
2488
2489 Also, some source/announcment newsgroups are not indented for discussion;
2490 responses here are directed to other newsgroups."))
2491                   (cons 'Newsgroups followup-to)
2492                 (cons 'Newsgroups newsgroups))))))
2493           (t
2494            `((Newsgroups . ,newsgroups))))
2495        ,@(and distribution (list (cons 'Distribution distribution)))
2496        (References . ,(concat (or references "") (and references " ")
2497                               (or message-id "")))
2498        ,@(when (and mct
2499                     (not (equal (downcase mct) "never")))
2500            (list (cons 'Cc (if (equal (downcase mct) "always")
2501                                (or reply-to from "")
2502                              mct)))))
2503
2504      cur)
2505
2506     (setq message-reply-headers
2507           (vector 0 subject from date message-id references 0 0 ""))))
2508
2509
2510 ;;;###autoload
2511 (defun message-cancel-news ()
2512   "Cancel an article you posted."
2513   (interactive)
2514   (unless (message-news-p)
2515     (error "This is not a news article; canceling is impossible"))
2516   (when (yes-or-no-p "Do you really want to cancel this article? ")
2517     (let (from newsgroups message-id distribution buf)
2518       (save-excursion
2519         ;; Get header info. from original article.
2520         (save-restriction
2521           (message-narrow-to-head)
2522           (setq from (message-fetch-field "from")
2523                 newsgroups (message-fetch-field "newsgroups")
2524                 message-id (message-fetch-field "message-id")
2525                 distribution (message-fetch-field "distribution")))
2526         ;; Make sure that this article was written by the user.
2527         (unless (string-equal
2528                  (downcase (cadr (mail-extract-address-components from)))
2529                  (downcase (message-make-address)))
2530           (error "This article is not yours"))
2531         ;; Make control message.
2532         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2533         (buffer-disable-undo (current-buffer))
2534         (erase-buffer)
2535         (insert "Newsgroups: " newsgroups "\n"
2536                 "From: " (message-make-from) "\n"
2537                 "Subject: cmsg cancel " message-id "\n"
2538                 "Control: cancel " message-id "\n"
2539                 (if distribution
2540                     (concat "Distribution: " distribution "\n")
2541                   "")
2542                 mail-header-separator "\n"
2543                 "This is a cancel message from " from ".\n")
2544         (message "Canceling your article...")
2545         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
2546           (funcall message-send-news-function))
2547         (message "Canceling your article...done")
2548         (kill-buffer buf)))))
2549
2550 ;;;###autoload
2551 (defun message-supersede ()
2552   "Start composing a message to supersede the current message.
2553 This is done simply by taking the old article and adding a Supersedes
2554 header line with the old Message-ID."
2555   (interactive)
2556   (let ((cur (current-buffer)))
2557     ;; Check whether the user owns the article that is to be superseded. 
2558     (unless (string-equal
2559              (downcase (cadr (mail-extract-address-components
2560                               (message-fetch-field "from"))))
2561              (downcase (message-make-address)))
2562       (error "This article is not yours"))
2563     ;; Get a normal message buffer.
2564     (message-pop-to-buffer (message-buffer-name "supersede"))
2565     (insert-buffer-substring cur)
2566     (message-narrow-to-head)
2567     ;; Remove unwanted headers.
2568     (when message-ignored-supersedes-headers
2569       (message-remove-header message-ignored-supersedes-headers t))
2570     (goto-char (point-min))
2571     (if (not (re-search-forward "^Message-ID: " nil t))
2572         (error "No Message-ID in this article")
2573       (replace-match "Supersedes: " t t))
2574     (goto-char (point-max))
2575     (insert mail-header-separator)
2576     (widen)
2577     (forward-line 1)))
2578
2579 ;;;###autoload
2580 (defun message-recover ()
2581   "Reread contents of current buffer from its last auto-save file."
2582   (interactive)
2583   (let ((file-name (make-auto-save-file-name)))
2584     (cond ((save-window-excursion
2585              (if (not (eq system-type 'vax-vms))
2586                  (with-output-to-temp-buffer "*Directory*"
2587                    (buffer-disable-undo standard-output)
2588                    (let ((default-directory "/"))
2589                      (call-process
2590                       "ls" nil standard-output nil "-l" file-name))))
2591              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2592            (let ((buffer-read-only nil))
2593              (erase-buffer)
2594              (insert-file-contents file-name nil)))
2595           (t (error "message-recover cancelled")))))
2596
2597 ;;; Forwarding messages.
2598
2599 (defun message-make-forward-subject ()
2600   "Return a Subject header suitable for the message in the current buffer."
2601   (concat "[" (or (message-fetch-field (if (message-news-p) "newsgroups" "from"))
2602                   "(nowhere)")
2603           "] " (or (message-fetch-field "Subject") "")))
2604
2605 ;;;###autoload
2606 (defun message-forward (&optional news)
2607   "Forward the current message via mail.  
2608 Optional NEWS will use news to forward instead of mail."
2609   (interactive "P")
2610   (let ((cur (current-buffer))
2611         (subject (message-make-forward-subject)))
2612     (if news (message-news nil subject) (message-mail nil subject))
2613     ;; Put point where we want it before inserting the forwarded
2614     ;; message. 
2615     (if message-signature-before-forwarded-message
2616         (goto-char (point-max))
2617       (message-goto-body))
2618     ;; Make sure we're at the start of the line.
2619     (unless (eolp)
2620       (insert "\n"))
2621     ;; Narrow to the area we are to insert.
2622     (narrow-to-region (point) (point))
2623     ;; Insert the separators and the forwarded buffer.
2624     (insert message-forward-start-separator)
2625     (insert-buffer-substring cur)
2626     (goto-char (point-max))
2627     (insert message-forward-end-separator)
2628     (set-text-properties (point-min) (point-max) nil)
2629     ;; Remove all unwanted headers.
2630     (goto-char (point-min))
2631     (forward-line 1)
2632     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2633                                   (1- (point))
2634                                 (point)))
2635     (goto-char (point-min))
2636     (message-remove-header message-included-forward-headers t nil t)
2637     (widen)
2638     (message-position-point)))
2639
2640 ;;;###autoload
2641 (defun message-resend (address)
2642   "Resend the current article to ADDRESS."
2643   (interactive "sResend message to: ")
2644   (save-excursion
2645     (let ((cur (current-buffer))
2646           beg)
2647       ;; We first set up a normal mail buffer.
2648       (set-buffer (get-buffer-create " *message resend*"))
2649       (buffer-disable-undo (current-buffer))
2650       (erase-buffer)
2651       (message-setup `((To . ,address)))
2652       ;; Insert our usual headers.
2653       (message-generate-headers '(From Date To))
2654       (message-narrow-to-headers)
2655       ;; Rename them all to "Resent-*".
2656       (while (re-search-forward "^[A-Za-z]" nil t)
2657         (forward-char -1)
2658         (insert "Resent-"))
2659       (widen)
2660       (forward-line)
2661       (delete-region (point) (point-max))
2662       (setq beg (point))
2663       ;; Insert the message to be resent.
2664       (insert-buffer-substring cur)
2665       (goto-char (point-min))
2666       (search-forward "\n\n")
2667       (forward-char -1)
2668       (save-restriction
2669         (narrow-to-region beg (point))
2670         (message-remove-header message-ignored-resent-headers t)
2671         (goto-char (point-max)))
2672       (insert mail-header-separator)
2673       ;; Rename all old ("Also-")Resent headers.
2674       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2675         (beginning-of-line)
2676         (insert "Also-"))
2677       ;; Send it.
2678       (message-send-mail)
2679       (kill-buffer (current-buffer)))))
2680
2681 ;;;###autoload
2682 (defun message-bounce ()
2683   "Re-mail the current message.
2684 This only makes sense if the current message is a bounce message than
2685 contains some mail you have written which has been bounced back to
2686 you."
2687   (interactive)
2688   (let ((cur (current-buffer))
2689         boundary)
2690     (message-pop-to-buffer (message-buffer-name "bounce"))
2691     (insert-buffer-substring cur)
2692     (undo-boundary)
2693     (message-narrow-to-head)
2694     (if (and (message-fetch-field "Mime-Version")
2695              (setq boundary (message-fetch-field "Content-Type")))
2696         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
2697             (setq boundary (concat (match-string 1 boundary) " *\n"
2698                                    "Content-Type: message/rfc822"))
2699           (setq boundary nil)))
2700     (widen)
2701     (goto-char (point-min))
2702     (search-forward "\n\n" nil t)
2703     (or (and boundary
2704              (re-search-forward boundary nil t)
2705              (forward-line 2))
2706         (and (re-search-forward message-unsent-separator nil t)
2707              (forward-line 1))
2708         (and (search-forward "\n\n" nil t)
2709              (re-search-forward "^Return-Path:.*\n" nil t)))
2710     ;; We remove everything before the bounced mail.
2711     (delete-region 
2712      (point-min)
2713      (if (re-search-forward "[^ \t]*:" nil t)
2714          (match-beginning 0)
2715        (point)))
2716     (save-restriction
2717       (message-narrow-to-head)
2718       (message-remove-header message-ignored-bounced-headers t)
2719       (goto-char (point-max))
2720       (insert mail-header-separator))
2721     (message-position-point)))
2722
2723 ;;;
2724 ;;; Interactive entry points for new message buffers.
2725 ;;;
2726
2727 ;;;###autoload
2728 (defun message-mail-other-window (&optional to subject)
2729   "Like `message-mail' command, but display mail buffer in another window."
2730   (interactive)
2731   (let ((pop-up-windows t)
2732         (special-display-buffer-names nil)
2733         (special-display-regexps nil)
2734         (same-window-buffer-names nil)
2735         (same-window-regexps nil))
2736     (message-pop-to-buffer (message-buffer-name "mail" to)))
2737   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2738
2739 ;;;###autoload
2740 (defun message-mail-other-frame (&optional to subject)
2741   "Like `message-mail' command, but display mail buffer in another frame."
2742   (interactive)
2743   (let ((pop-up-frames t)
2744         (special-display-buffer-names nil)
2745         (special-display-regexps nil)
2746         (same-window-buffer-names nil)
2747         (same-window-regexps nil))
2748     (message-pop-to-buffer (message-buffer-name "mail" to)))
2749   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2750
2751 ;;;###autoload
2752 (defun message-news-other-window (&optional newsgroups subject)
2753   "Start editing a news article to be sent."
2754   (interactive)
2755   (let ((pop-up-windows t)
2756         (special-display-buffer-names nil)
2757         (special-display-regexps nil)
2758         (same-window-buffer-names nil)
2759         (same-window-regexps nil))
2760     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2761   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2762                    (Subject . ,(or subject "")))))
2763
2764 ;;;###autoload
2765 (defun message-news-other-frame (&optional newsgroups subject)
2766   "Start editing a news article to be sent."
2767   (interactive)
2768   (let ((pop-up-frames t)
2769         (special-display-buffer-names nil)
2770         (special-display-regexps nil)
2771         (same-window-buffer-names nil)
2772         (same-window-regexps nil))
2773     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2774   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2775                    (Subject . ,(or subject "")))))
2776
2777 ;;; underline.el
2778
2779 ;; This code should be moved to underline.el (from which it is stolen). 
2780
2781 ;;;###autoload
2782 (defun bold-region (start end)
2783   "Bold all nonblank characters in the region.
2784 Works by overstriking characters.
2785 Called from program, takes two arguments START and END
2786 which specify the range to operate on."
2787   (interactive "r")
2788   (save-excursion
2789    (let ((end1 (make-marker)))
2790      (move-marker end1 (max start end))
2791      (goto-char (min start end))
2792      (while (< (point) end1)
2793        (or (looking-at "[_\^@- ]")
2794            (insert (following-char) "\b"))
2795        (forward-char 1)))))
2796
2797 ;;;###autoload
2798 (defun unbold-region (start end)
2799   "Remove all boldness (overstruck characters) in the region.
2800 Called from program, takes two arguments START and END
2801 which specify the range to operate on."
2802   (interactive "r")
2803   (save-excursion
2804    (let ((end1 (make-marker)))
2805      (move-marker end1 (max start end))
2806      (goto-char (min start end)) 
2807      (while (re-search-forward "\b" end1 t)
2808        (if (eq (following-char) (char-after (- (point) 2)))
2809            (delete-char -2))))))
2810
2811 ;; Support for toolbar
2812 (when (string-match "XEmacs\\|Lucid" emacs-version)
2813   (require 'messagexmas))
2814
2815 ;;; Group name completion.
2816
2817 (defvar message-newgroups-header-regexp
2818   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
2819   "Regexp that match headers that lists groups.")
2820
2821 (defun message-tab ()
2822   "Expand group names in Newsgroups and Followup-To headers.
2823 Do a `tab-to-tab-stop' if not in those headers."
2824   (interactive)
2825   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
2826         (mail-abbrev-in-expansion-header-p))
2827       (message-expand-group)
2828     (tab-to-tab-stop)))
2829
2830 (defvar gnus-active-hashtb)
2831 (defun message-expand-group ()
2832   (let* ((b (save-excursion (skip-chars-backward "^, :\t\n") (point)))
2833          (completion-ignore-case t)
2834          (string (buffer-substring b (point)))
2835          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
2836          (completions (all-completions string hashtb))
2837          (cur (current-buffer))
2838          comp)
2839     (delete-region b (point))
2840     (cond 
2841      ((= (length completions) 1)
2842       (if (string= (car completions) string)
2843           (progn
2844             (insert string)
2845             (message "Only matching group"))
2846         (insert (car completions))))
2847      ((and (setq comp (try-completion string hashtb))
2848            (not (string= comp string)))
2849       (insert comp))
2850      (t
2851       (insert string)
2852       (if (not comp)
2853           (message "No matching groups")
2854         (pop-to-buffer "*Completions*")
2855         (buffer-disable-undo (current-buffer))
2856         (let ((buffer-read-only nil))
2857           (erase-buffer)
2858           (let ((standard-output (current-buffer)))
2859             (display-completion-list (sort completions 'string<)))
2860           (goto-char (point-min))
2861           (pop-to-buffer cur)))))))
2862
2863 ;;; Help stuff.
2864
2865 (defmacro message-y-or-n-p (question show &rest text)
2866   "Ask QUESTION, displaying the rest of the arguments in a temporary buffer."
2867   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
2868
2869 (defun message-talkative-question (ask question show &rest text)
2870   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
2871 The following arguments may contain lists of values."
2872   (if (and show
2873            (setq text (message-flatten-list text)))
2874       (save-window-excursion
2875         (save-excursion
2876           (with-output-to-temp-buffer " *MESSAGE information message*"
2877             (set-buffer " *MESSAGE information message*")
2878             (mapcar 'princ text)
2879             (goto-char (point-min))))
2880         (funcall ask question))
2881     (funcall ask question)))
2882
2883 (defun message-flatten-list (&rest list)
2884   (message-flatten-list-1 list))
2885
2886 (defun message-flatten-list-1 (list)
2887   (cond ((consp list) 
2888          (apply 'append (mapcar 'message-flatten-list-1 list)))
2889         (list
2890          (list list))))
2891
2892 (provide 'message)
2893
2894 ;;; message.el ends here