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