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