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