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