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