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