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