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