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