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