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