*** 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     (when (message-check-news-syntax)
1533       (unwind-protect
1534           (save-excursion
1535             (set-buffer tembuf)
1536             (buffer-disable-undo (current-buffer))
1537             (erase-buffer) 
1538             ;; Avoid copying text props.
1539           (insert (format 
1540                    "%s" (save-excursion
1541                           (set-buffer messbuf)
1542                           (buffer-string))))
1543             ;; Remove some headers.
1544             (save-restriction
1545               (message-narrow-to-headers)
1546               ;; Remove some headers.
1547               (message-remove-header message-ignored-news-headers t))
1548             (goto-char (point-max))
1549             ;; require one newline at the end.
1550             (or (= (preceding-char) ?\n)
1551                 (insert ?\n))
1552             (let ((case-fold-search t))
1553               ;; Remove the delimeter.
1554               (goto-char (point-min))
1555               (re-search-forward
1556                (concat "^" (regexp-quote mail-header-separator) "\n"))
1557               (replace-match "\n")
1558               (backward-char 1))
1559             (require (car method))
1560             (funcall (intern (format "%s-open-server" (car method)))
1561                      (cadr method) (cddr method))
1562             (setq result
1563                   (funcall (intern (format "%s-request-post" (car method))))))
1564         (kill-buffer tembuf))
1565       (set-buffer messbuf)
1566       (if result
1567           (push 'news message-sent-message-via)
1568         (message "Couldn't send message via news: %s"
1569                  (nnheader-get-report (car method)))
1570         nil))))
1571
1572 ;;;
1573 ;;; Header generation & syntax checking.
1574 ;;;
1575
1576 (defun message-check-news-syntax ()
1577   "Check the syntax of the message."
1578   (and 
1579    ;; We narrow to the headers and check them first.
1580    (save-excursion
1581      (save-restriction
1582        (message-narrow-to-headers)
1583        (and 
1584         ;; Check for commands in Subject.
1585         (or 
1586          (message-check-element 'subject-cmsg)
1587          (save-excursion
1588            (if (string-match "^cmsg " (message-fetch-field "subject"))
1589                (y-or-n-p
1590                 "The control code \"cmsg \" is in the subject. Really post? ")
1591              t)))
1592         ;; Check for multiple identical headers.
1593         (or (message-check-element 'multiple-headers)
1594             (save-excursion
1595               (let (found)
1596                 (while (and (not found) 
1597                             (re-search-forward "^[^ \t:]+: " nil t))
1598                   (save-excursion
1599                     (or (re-search-forward 
1600                          (concat "^" (setq found
1601                                            (buffer-substring 
1602                                             (match-beginning 0) 
1603                                             (- (match-end 0) 2))))
1604                          nil t)
1605                         (setq found nil))))
1606                 (if found
1607                     (y-or-n-p 
1608                      (format "Multiple %s headers. Really post? " found))
1609                   t))))
1610         ;; Check for Version and Sendsys.
1611         (or (message-check-element 'sendsys)
1612             (save-excursion
1613               (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
1614                   (y-or-n-p
1615                    (format "The article contains a %s command. Really post? "
1616                            (buffer-substring (match-beginning 0) 
1617                                              (1- (match-end 0)))))
1618                 t)))
1619         ;; See whether we can shorten Followup-To.
1620         (or (message-check-element 'shorten-followup-to)
1621             (let ((newsgroups (message-fetch-field "newsgroups"))
1622                   (followup-to (message-fetch-field "followup-to"))
1623                   to)
1624               (when (and newsgroups (string-match "," newsgroups)
1625                          (not followup-to)
1626                          (not
1627                           (zerop
1628                            (length
1629                             (setq to (completing-read 
1630                                       "Followups to: (default all groups) " 
1631                                       (mapcar (lambda (g) (list g))
1632                                               (cons "poster" 
1633                                                     (message-tokenize-header 
1634                                                      newsgroups)))))))))
1635                 (goto-char (point-min))
1636                 (insert "Followup-To: " to "\n"))
1637               t))
1638         ;; Check "Shoot me".
1639         (or (message-check-element 'shoot)
1640             (save-excursion
1641               (if (re-search-forward
1642                    "Message-ID.*.i-have-a-misconfigured-system-so-shoot-me"
1643                    nil t)
1644                   (y-or-n-p
1645                    "You appear to have a misconfigured system.  Really post? ")
1646                 t)))
1647         ;; Check for Approved.
1648         (or (message-check-element 'approved)
1649             (save-excursion
1650               (if (re-search-forward "^Approved:" nil t)
1651                   (y-or-n-p
1652                    "The article contains an Approved header. Really post? ")
1653                 t)))
1654         ;; Check the Message-Id header.
1655         (or (message-check-element 'message-id)
1656             (save-excursion
1657               (let* ((case-fold-search t)
1658                      (message-id (message-fetch-field "message-id")))
1659                 (or (not message-id)
1660                     (and (string-match "@" message-id)
1661                          (string-match "@[^\\.]*\\." message-id))
1662                     (y-or-n-p
1663                      (format 
1664                       "The Message-ID looks strange: \"%s\". Really post? "
1665                       message-id))))))
1666         ;; Check the Subject header.
1667         (or 
1668          (message-check-element 'subject)
1669          (save-excursion
1670            (let* ((case-fold-search t)
1671                   (subject (message-fetch-field "subject")))
1672              (or
1673               (and subject
1674                    (not (string-match "\\`[ \t]*\\'" subject)))
1675               (progn
1676                 (message 
1677                  "The subject field is empty or missing.  Posting is denied.")
1678                 nil)))))
1679         ;; Check the Newsgroups & Followup-To headers.
1680         (or
1681          (message-check-element 'existing-newsgroups)
1682          (let* ((case-fold-search t)
1683                 (newsgroups (message-fetch-field "newsgroups"))
1684                 (followup-to (message-fetch-field "followup-to"))
1685                 (groups (message-tokenize-header
1686                          (if followup-to
1687                              (concat newsgroups "," followup-to)
1688                            newsgroups)))
1689                 (hashtb (and (boundp 'gnus-active-hashtb)
1690                              gnus-active-hashtb))
1691                 errors)
1692            (if (not hashtb)
1693                t
1694              (while groups
1695                (when (and (not (boundp (intern (car groups) hashtb)))
1696                           (not (equal (car groups) "poster")))
1697                  (push (car groups) errors))
1698                (pop groups))
1699              (if (not errors)
1700                  t
1701                (y-or-n-p
1702                 (format
1703                  "Really post to %s unknown group%s: %s "
1704                  (if (= (length errors) 1) "this" "these")
1705                  (if (= (length errors) 1) "" "s")
1706                  (mapconcat 'identity errors ", ")))))))
1707         ;; Check the Newsgroups & Followup-To headers for syntax errors.
1708         (or
1709          (message-check-element 'valid-newsgroups)
1710          (let ((case-fold-search t)
1711                (headers '("Newsgroups" "Followup-To"))
1712                header error)
1713            (while (and headers (not error))
1714              (when (setq header (mail-fetch-field (car headers)))
1715                (if (or
1716                     (not 
1717                      (string-match
1718                       "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
1719                       header))
1720                     (memq 
1721                      nil (mapcar 
1722                           (lambda (g)
1723                             (not (string-match "\\.\\'\\|\\.\\." g)))
1724                           (message-tokenize-header header ","))))
1725                    (setq error t)))
1726              (unless error
1727                (pop headers)))
1728            (if (not error)
1729                t
1730              (y-or-n-p
1731               (format "The %s header looks odd: \"%s\".  Really post? "
1732                       (car headers) header)))))
1733         ;; Check the From header.
1734         (or 
1735          (save-excursion
1736            (let* ((case-fold-search t)
1737                   (from (message-fetch-field "from")))
1738              (cond
1739               ((not from)
1740                (message "There is no From line.  Posting is denied.")
1741                nil)
1742               ((not (string-match "@[^\\.]*\\." from))
1743                (message
1744                 "Denied posting -- the From looks strange: \"%s\"." from)
1745                nil)
1746               ((string-match "@[^@]*@" from)
1747                (message 
1748                 "Denied posting -- two \"@\"'s in the From header: %s." from)
1749                nil)
1750               ((string-match "(.*).*(.*)" from)
1751                (message
1752                 "Denied posting -- the From header looks strange: \"%s\"." 
1753                 from)
1754                nil)
1755               (t t))))))))
1756    ;; Check for long lines.
1757    (or (message-check-element 'long-lines)
1758        (save-excursion
1759          (goto-char (point-min))
1760          (re-search-forward
1761           (concat "^" (regexp-quote mail-header-separator) "$"))
1762          (while (and
1763                  (progn
1764                    (end-of-line)
1765                    (< (current-column) 80))
1766                  (zerop (forward-line 1))))
1767          (or (bolp)
1768              (eobp)
1769              (y-or-n-p
1770               "You have lines longer than 79 characters.  Really post? "))))
1771    ;; Check whether the article is empty.
1772    (or (message-check-element 'empty)
1773        (save-excursion
1774          (goto-char (point-min))
1775          (re-search-forward
1776           (concat "^" (regexp-quote mail-header-separator) "$"))
1777          (forward-line 1)
1778          (let ((b (point)))
1779            (goto-char (point-max))
1780            (re-search-backward message-signature-separator nil t)
1781            (beginning-of-line)
1782            (or (re-search-backward "[^ \n\t]" b t)
1783                (y-or-n-p "Empty article.  Really post? ")))))
1784    ;; Check for control characters.
1785    (or (message-check-element 'control-chars)
1786        (save-excursion
1787          (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
1788              (y-or-n-p 
1789               "The article contains control characters. Really post? ")
1790            t)))
1791    ;; Check excessive size.
1792    (or (message-check-element 'size)
1793        (if (> (buffer-size) 60000)
1794            (y-or-n-p
1795             (format "The article is %d octets long. Really post? "
1796                     (buffer-size)))
1797          t))
1798    ;; Check whether any new text has been added.
1799    (or (message-check-element 'new-text)
1800        (not message-checksum)
1801        (not (and (eq (message-checksum) (car message-checksum))
1802                  (eq (buffer-size) (cdr message-checksum))))
1803        (y-or-n-p
1804         "It looks like no new text has been added.  Really post? "))
1805    ;; Check the length of the signature.
1806    (or
1807     (message-check-element 'signature)
1808     (progn
1809       (goto-char (point-max))
1810       (if (or (not (re-search-backward message-signature-separator nil t))
1811               (search-forward message-forward-end-separator nil t))
1812           t
1813         (if (> (count-lines (point) (point-max)) 5)
1814             (y-or-n-p
1815              (format
1816               "Your .sig is %d lines; it should be max 4.  Really post? "
1817               (1- (count-lines (point) (point-max)))))
1818           t))))))
1819
1820 (defun message-check-element (type)
1821   "Returns non-nil if this type is not to be checked."
1822   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
1823       t
1824     (let ((able (assq type message-syntax-checks)))
1825       (and (consp able)
1826            (eq (cdr able) 'disabled)))))
1827
1828 (defun message-checksum ()
1829   "Return a \"checksum\" for the current buffer."
1830   (let ((sum 0))
1831     (save-excursion
1832       (goto-char (point-min))
1833       (re-search-forward
1834        (concat "^" (regexp-quote mail-header-separator) "$"))
1835       (while (not (eobp))
1836         (when (not (looking-at "[ \t\n]"))
1837           (setq sum (logxor (ash sum 1) (following-char))))
1838         (forward-char 1)))
1839     sum))
1840
1841 (defun message-do-fcc ()
1842   "Process Fcc headers in the current buffer."
1843   (let ((case-fold-search t)
1844         (buf (current-buffer))
1845         list file)
1846     (save-excursion
1847       (set-buffer (get-buffer-create " *message temp*"))
1848       (buffer-disable-undo (current-buffer))
1849       (erase-buffer)
1850       (insert-buffer-substring buf)
1851       (save-restriction
1852         (message-narrow-to-headers)
1853         (while (setq file (message-fetch-field "fcc"))
1854           (push file list)
1855           (message-remove-header "fcc" nil t)))
1856       (goto-char (point-min))
1857       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
1858       (replace-match "" t t)
1859       ;; Process FCC operations.
1860       (while list
1861         (setq file (pop list))
1862         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
1863             ;; Pipe the article to the program in question.
1864             (call-process-region (point-min) (point-max) shell-file-name
1865                                  nil nil nil shell-command-switch
1866                                  (match-string 1 file))
1867           ;; Save the article.
1868           (setq file (expand-file-name file))
1869           (unless (file-exists-p (file-name-directory file))
1870             (make-directory (file-name-directory file) t))
1871           (if (and message-fcc-handler-function
1872                    (not (eq message-fcc-handler-function 'rmail-output)))
1873               (funcall message-fcc-handler-function file)
1874             (if (and (file-readable-p file) (mail-file-babyl-p file))
1875                 (rmail-output file 1)
1876               (let ((mail-use-rfc822 t))
1877                 (rmail-output file 1 t t))))))
1878       (kill-buffer (current-buffer)))))
1879
1880 (defun message-cleanup-headers ()
1881   "Do various automatic cleanups of the headers."
1882   ;; Remove empty lines in the header.
1883   (save-restriction
1884     (message-narrow-to-headers)
1885     (while (re-search-forward "^[ \t]*\n" nil t)
1886       (replace-match "" t t)))
1887
1888   ;; Correct Newsgroups and Followup-To headers: change sequence of
1889   ;; spaces to comma and eliminate spaces around commas.  Eliminate
1890   ;; embedded line breaks.
1891   (goto-char (point-min))
1892   (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
1893     (save-restriction
1894       (narrow-to-region
1895        (point)
1896        (if (re-search-forward "^[^ \t]" nil t)
1897            (match-beginning 0)
1898          (forward-line 1)
1899          (point)))
1900       (goto-char (point-min))
1901       (while (re-search-forward "\n[ \t]+" nil t)
1902         (replace-match " " t t))        ;No line breaks (too confusing)
1903       (goto-char (point-min))
1904       (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
1905         (replace-match "," t t))
1906       (goto-char (point-min))
1907       ;; Remove trailing commas.
1908       (when (re-search-forward ",+$" nil t)
1909         (replace-match "" t t)))))
1910
1911 (defun message-make-date ()
1912   "Make a valid data header."
1913   (let ((now (current-time)))
1914     (timezone-make-date-arpa-standard 
1915      (current-time-string now) (current-time-zone now))))
1916
1917 (defun message-make-message-id ()
1918   "Make a unique Message-ID."
1919   (concat "<" (message-unique-id) 
1920           (let ((psubject (save-excursion (message-fetch-field "subject"))))
1921             (if (and message-reply-headers
1922                      (mail-header-references message-reply-headers)
1923                      (mail-header-subject message-reply-headers)
1924                      psubject
1925                      (mail-header-subject message-reply-headers)
1926                      (not (string= 
1927                            (message-strip-subject-re
1928                             (mail-header-subject message-reply-headers))
1929                            (message-strip-subject-re psubject))))
1930                 "_-_" ""))
1931           "@" (message-make-fqdn) ">"))
1932
1933 (defvar message-unique-id-char nil)
1934
1935 ;; If you ever change this function, make sure the new version
1936 ;; cannot generate IDs that the old version could.
1937 ;; You might for example insert a "." somewhere (not next to another dot
1938 ;; or string boundary), or modify the "fsf" string.
1939 (defun message-unique-id ()
1940   ;; Don't use microseconds from (current-time), they may be unsupported.
1941   ;; Instead we use this randomly inited counter.
1942   (setq message-unique-id-char
1943         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
1944            ;; (current-time) returns 16-bit ints,
1945            ;; and 2^16*25 just fits into 4 digits i base 36.
1946            (* 25 25)))
1947   (let ((tm (current-time)))
1948     (concat
1949      (if (memq system-type '(ms-dos emx vax-vms))
1950          (let ((user (downcase (user-login-name))))
1951            (while (string-match "[^a-z0-9_]" user)
1952              (aset user (match-beginning 0) ?_))
1953            user)
1954        (message-number-base36 (user-uid) -1))
1955      (message-number-base36 (+ (car   tm) 
1956                                (lsh (% message-unique-id-char 25) 16)) 4)
1957      (message-number-base36 (+ (nth 1 tm)
1958                                (lsh (/ message-unique-id-char 25) 16)) 4)
1959      ;; Append the newsreader name, because while the generated
1960      ;; ID is unique to this newsreader, other newsreaders might
1961      ;; otherwise generate the same ID via another algorithm.
1962      ".fsf")))
1963
1964 (defun message-number-base36 (num len)
1965   (if (if (< len 0) (<= num 0) (= len 0))
1966       ""
1967     (concat (message-number-base36 (/ num 36) (1- len))
1968             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
1969                                   (% num 36))))))
1970
1971 (defun message-make-organization ()
1972   "Make an Organization header."
1973   (let* ((organization 
1974           (or (getenv "ORGANIZATION")
1975               (when message-user-organization
1976                 (if (message-functionp message-user-organization)
1977                     (funcall message-user-organization)
1978                   message-user-organization)))))
1979     (save-excursion
1980       (message-set-work-buffer)
1981       (cond ((stringp organization)
1982              (insert organization))
1983             ((and (eq t organization)
1984                   message-user-organization-file
1985                   (file-exists-p message-user-organization-file))
1986              (insert-file-contents message-user-organization-file)))
1987       (goto-char (point-min))
1988       (while (re-search-forward "[\t\n]+" nil t)
1989         (replace-match "" t t))
1990       (unless (zerop (buffer-size))
1991         (buffer-string)))))
1992
1993 (defun message-make-lines ()
1994   "Count the number of lines and return numeric string."
1995   (save-excursion
1996     (save-restriction
1997       (widen)
1998       (goto-char (point-min))
1999       (re-search-forward 
2000        (concat "^" (regexp-quote mail-header-separator) "$"))
2001       (forward-line 1)
2002       (int-to-string (count-lines (point) (point-max))))))
2003
2004 (defun message-make-in-reply-to ()
2005   "Return the In-Reply-To header for this message."
2006   (when message-reply-headers
2007     (let ((from (mail-header-from message-reply-headers))
2008           (date (mail-header-date message-reply-headers)))
2009       (when from
2010         (let ((stop-pos 
2011                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2012           (concat (if stop-pos (substring from 0 stop-pos) from)
2013                   "'s message of " 
2014                   (if (or (not date) (string= date ""))
2015                       "(unknown date)" date)))))))
2016
2017 (defun message-make-distribution ()
2018   "Make a Distribution header."
2019   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2020     (cond ((message-functionp message-distribution-function)
2021            (funcall message-distribution-function))
2022           (t orig-distribution))))
2023
2024 (defun message-make-expires ()
2025   "Return an Expires header based on `message-expires'."
2026   (let ((current (current-time))
2027         (future (* 1.0 message-expires 60 60 24)))
2028     ;; Add the future to current.
2029     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2030     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2031     ;; Return the date in the future in UT.
2032     (timezone-make-date-arpa-standard 
2033      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2034
2035 (defun message-make-path ()
2036   "Return uucp path."
2037   (let ((login-name (user-login-name)))
2038     (cond ((null message-user-path)
2039            (concat (system-name) "!" login-name))
2040           ((stringp message-user-path)
2041            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2042            (concat message-user-path "!" login-name))
2043           (t login-name))))
2044
2045 (defun message-make-from ()
2046   "Make a From header."
2047   (let* ((login (message-make-address))
2048          (fullname 
2049           (or (and (boundp 'user-full-name)
2050                    user-full-name)
2051               (user-full-name))))
2052     (when (string= fullname "&")
2053       (setq fullname (user-login-name)))
2054     (save-excursion
2055       (message-set-work-buffer)
2056       (cond 
2057        ((or (null message-from-style)
2058             (equal fullname ""))
2059         (insert login))
2060        ((or (eq message-from-style 'angles)
2061             (and (not (eq message-from-style 'parens))
2062                  ;; Use angles if no quoting is needed, or if parens would
2063                  ;; need quoting too.
2064                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2065                      (let ((tmp (concat fullname nil)))
2066                        (while (string-match "([^()]*)" tmp)
2067                          (aset tmp (match-beginning 0) ?-)
2068                          (aset tmp (1- (match-end 0)) ?-))
2069                        (string-match "[\\()]" tmp)))))
2070         (insert fullname)
2071         (goto-char (point-min))
2072         ;; Look for a character that cannot appear unquoted
2073         ;; according to RFC 822.
2074         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2075           ;; Quote fullname, escaping specials.
2076           (goto-char (point-min))
2077           (insert "\"")
2078           (while (re-search-forward "[\"\\]" nil 1)
2079             (replace-match "\\\\\\&" t))
2080           (insert "\""))
2081         (insert " <" login ">"))
2082        (t                               ; 'parens or default
2083         (insert login " (")
2084         (let ((fullname-start (point)))
2085           (insert fullname)
2086           (goto-char fullname-start)
2087           ;; RFC 822 says \ and nonmatching parentheses
2088           ;; must be escaped in comments.
2089           ;; Escape every instance of ()\ ...
2090           (while (re-search-forward "[()\\]" nil 1)
2091             (replace-match "\\\\\\&" t))
2092           ;; ... then undo escaping of matching parentheses,
2093           ;; including matching nested parentheses.
2094           (goto-char fullname-start)
2095           (while (re-search-forward 
2096                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2097                     nil 1)
2098             (replace-match "\\1(\\3)" t)
2099             (goto-char fullname-start)))
2100         (insert ")")))
2101       (buffer-string))))
2102
2103 (defun message-make-sender ()
2104   "Return the \"real\" user address.
2105 This function tries to ignore all user modifications, and 
2106 give as trustworthy answer as possible."
2107   (concat (user-login-name) "@" (system-name)))
2108
2109 (defun message-make-address ()
2110   "Make the address of the user."
2111   (or (message-user-mail-address)
2112       (concat (user-login-name) "@" (message-make-domain))))
2113
2114 (defun message-user-mail-address ()
2115   "Return the pertinent part of `user-mail-address'."
2116   (when user-mail-address
2117     (nth 1 (mail-extract-address-components user-mail-address))))
2118
2119 (defun message-make-fqdn ()
2120   "Return user's fully qualified domain name."
2121   (let ((system-name (system-name))
2122         (user-mail (message-user-mail-address)))
2123     (cond 
2124      ((string-match "[^.]\\.[^.]" system-name)
2125       ;; `system-name' returned the right result.
2126       system-name)
2127      ;; Try `mail-host-address'.
2128      ((and (boundp 'mail-host-address)
2129            (stringp mail-host-address)
2130            (string-match "\\." mail-host-address))
2131       mail-host-address)
2132      ;; We try `user-mail-address' as a backup.
2133      ((and (string-match "\\." user-mail)
2134            (string-match "@\\(.*\\)\\'" user-mail))
2135       (match-string 1 user-mail))
2136      ;; Default to this bogus thing.
2137      (t
2138       (concat system-name ".i-have-a-misconfigured-system-so-shoot-me")))))
2139
2140 (defun message-make-host-name ()
2141   "Return the name of the host."
2142   (let ((fqdn (message-make-fqdn)))
2143     (string-match "^[^.]+\\." fqdn)
2144     (substring fqdn 0 (1- (match-end 0)))))
2145
2146 (defun message-make-domain ()
2147   "Return the domain name."
2148   (or mail-host-address
2149       (message-make-fqdn)))
2150
2151 (defun message-generate-headers (headers)
2152   "Prepare article HEADERS.
2153 Headers already prepared in the buffer are not modified."
2154   (save-restriction
2155     (message-narrow-to-headers)
2156     (let* ((Date (message-make-date))
2157            (Message-ID (message-make-message-id))
2158            (Organization (message-make-organization))
2159            (From (message-make-from))
2160            (Path (message-make-path))
2161            (Subject nil)
2162            (Newsgroups nil)
2163            (In-Reply-To (message-make-in-reply-to))
2164            (To nil)
2165            (Distribution (message-make-distribution))
2166            (Lines (message-make-lines))
2167            (X-Newsreader message-newsreader)
2168            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2169                           message-mailer))
2170            (Expires (message-make-expires))
2171            (case-fold-search t)
2172            header value elem)
2173       ;; First we remove any old generated headers.
2174       (let ((headers message-deletable-headers))
2175         (while headers
2176           (goto-char (point-min))
2177           (and (re-search-forward 
2178                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2179                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
2180                (message-delete-line))
2181           (pop headers)))
2182       ;; Go through all the required headers and see if they are in the
2183       ;; articles already. If they are not, or are empty, they are
2184       ;; inserted automatically - except for Subject, Newsgroups and
2185       ;; Distribution. 
2186       (while headers
2187         (goto-char (point-min))
2188         (setq elem (pop headers))
2189         (if (consp elem)
2190             (if (eq (car elem) 'optional)
2191                 (setq header (cdr elem))
2192               (setq header (car elem)))
2193           (setq header elem))
2194         (when (or (not (re-search-forward 
2195                         (concat "^" (downcase (symbol-name header)) ":") 
2196                         nil t))
2197                   (progn
2198                     ;; The header was found. We insert a space after the
2199                     ;; colon, if there is none.
2200                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
2201                     ;; Find out whether the header is empty...
2202                     (looking-at "[ \t]*$")))
2203           ;; So we find out what value we should insert.
2204           (setq value
2205                 (cond 
2206                  ((and (consp elem) (eq (car elem) 'optional))
2207                   ;; This is an optional header.  If the cdr of this
2208                   ;; is something that is nil, then we do not insert
2209                   ;; this header.
2210                   (setq header (cdr elem))
2211                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
2212                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
2213                  ((consp elem)
2214                   ;; The element is a cons.  Either the cdr is a
2215                   ;; string to be inserted verbatim, or it is a
2216                   ;; function, and we insert the value returned from
2217                   ;; this function.
2218                   (or (and (stringp (cdr elem)) (cdr elem))
2219                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
2220                  ((and (boundp header) (symbol-value header))
2221                   ;; The element is a symbol.  We insert the value
2222                   ;; of this symbol, if any.
2223                   (symbol-value header))
2224                  (t
2225                   ;; We couldn't generate a value for this header,
2226                   ;; so we just ask the user.
2227                   (read-from-minibuffer
2228                    (format "Empty header for %s; enter value: " header)))))
2229           ;; Finally insert the header.
2230           (when (and value 
2231                      (not (equal value "")))
2232             (save-excursion
2233               (if (bolp)
2234                   (progn
2235                     ;; This header didn't exist, so we insert it.
2236                     (goto-char (point-max))
2237                     (insert (symbol-name header) ": " value "\n")
2238                     (forward-line -1))
2239                 ;; The value of this header was empty, so we clear
2240                 ;; totally and insert the new value.
2241                 (delete-region (point) (message-point-at-eol))
2242                 (insert value))
2243               ;; Add the deletable property to the headers that require it.
2244               (and (memq header message-deletable-headers)
2245                    (progn (beginning-of-line) (looking-at "[^:]+: "))
2246                    (add-text-properties 
2247                     (point) (match-end 0)
2248                     '(message-deletable t face italic) (current-buffer)))))))
2249       ;; Insert new Sender if the From is strange. 
2250       (let ((from (message-fetch-field "from"))
2251             (sender (message-fetch-field "sender"))
2252             (secure-sender (message-make-sender)))
2253         (when (and from 
2254                    (not (message-check-element 'sender))
2255                    (not (string=
2256                          (downcase
2257                           (cadr (mail-extract-address-components from)))
2258                          (downcase secure-sender)))
2259                    (or (null sender)
2260                        (not 
2261                         (string=
2262                          (downcase
2263                           (cadr (mail-extract-address-components sender)))
2264                          (downcase secure-sender)))))
2265           (goto-char (point-min))    
2266           ;; Rename any old Sender headers to Original-Sender.
2267           (when (re-search-forward "^Sender:" nil t)
2268             (beginning-of-line)
2269             (insert "Original-")
2270             (beginning-of-line))
2271           (insert "Sender: " secure-sender "\n"))))))
2272
2273 (defun message-insert-courtesy-copy ()
2274   "Insert a courtesy message in mail copies of combined messages."
2275   (save-excursion
2276     (save-restriction
2277       (message-narrow-to-headers)
2278       (let ((newsgroups (message-fetch-field "newsgroups")))
2279         (when newsgroups
2280           (goto-char (point-max))
2281           (insert "Posted-To: " newsgroups "\n"))))
2282     (forward-line 1)
2283     (insert message-courtesy-message)))
2284     
2285 ;;;
2286 ;;; Setting up a message buffer
2287 ;;;
2288
2289 (defun message-fill-address (header value)
2290   (save-restriction
2291     (narrow-to-region (point) (point))
2292     (insert (capitalize (symbol-name header))
2293             ": "
2294             (if (consp value) (car value) value)
2295             "\n")
2296     (narrow-to-region (point-min) (1- (point-max)))
2297     (let (quoted last)
2298       (goto-char (point-min))
2299       (while (not (eobp))
2300         (skip-chars-forward "^,\"" (point-max))
2301         (if (or (= (following-char) ?,)
2302                 (eobp))
2303             (when (not quoted)
2304               (if (and (> (current-column) 78)
2305                        last)
2306                   (progn
2307                     (save-excursion
2308                       (goto-char last)
2309                       (insert "\n\t"))
2310                     (setq last (1+ (point))))
2311                 (setq last (1+ (point)))))
2312           (setq quoted (not quoted)))
2313         (unless (eobp)
2314           (forward-char 1))))
2315     (goto-char (point-max))
2316     (widen)
2317     (forward-line 1)))
2318
2319 (defun message-fill-header (header value)
2320   (let ((begin (point))
2321         (fill-column 78)
2322         (fill-prefix "\t"))
2323     (insert (capitalize (symbol-name header))
2324             ": "
2325             (if (consp value) (car value) value)
2326             "\n")
2327     (save-restriction
2328       (narrow-to-region begin (point))
2329       (fill-region-as-paragraph begin (point))
2330       ;; Tapdance around looong Message-IDs.
2331       (forward-line -1)
2332       (when (looking-at "[ \t]*$")
2333         (message-delete-line))
2334       (goto-char begin)
2335       (re-search-forward ":" nil t)
2336       (when (looking-at "\n[ \t]+")
2337         (replace-match " " t t))
2338       (goto-char (point-max)))))
2339
2340 (defun message-position-point ()
2341   "Move point to where the user probably wants to find it."
2342   (message-narrow-to-headers)
2343   (cond 
2344    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2345     (search-backward ":" )
2346     (widen)
2347     (forward-char 1)
2348     (if (= (following-char) ? )
2349         (forward-char 1)
2350       (insert " ")))
2351    (t
2352     (goto-char (point-max))
2353     (widen)
2354     (forward-line 1)
2355     (unless (looking-at "$")
2356       (forward-line 2)))
2357    (sit-for 0)))
2358
2359 (defun message-buffer-name (type &optional to group)
2360   "Return a new (unique) buffer name based on TYPE and TO."
2361   (cond
2362    ;; Check whether `message-generate-new-buffers' is a function, 
2363    ;; and if so, call it.
2364    ((message-functionp message-generate-new-buffers)
2365     (funcall message-generate-new-buffers type to group))
2366    ;; Generate a new buffer name The Message Way.
2367    (message-generate-new-buffers
2368     (generate-new-buffer-name
2369      (concat "*" type
2370              (if to
2371                  (concat " to "
2372                          (or (car (mail-extract-address-components to))
2373                              to) "")
2374                "")
2375              (if (and group (not (string= group ""))) (concat " on " group) "")
2376              "*")))
2377    ;; Use standard name.
2378    (t
2379     (format "*%s message*" type))))
2380
2381 (defun message-pop-to-buffer (name)
2382   "Pop to buffer NAME, and warn if it already exists and is modified."
2383   (let ((buffer (get-buffer name)))
2384     (if (and buffer
2385              (buffer-name buffer))
2386         (progn
2387           (set-buffer (pop-to-buffer buffer))
2388           (when (and (buffer-modified-p)
2389                      (not (y-or-n-p
2390                            "Message already being composed; erase? ")))
2391             (error "Message being composed")))
2392       (set-buffer (pop-to-buffer name))))
2393   (erase-buffer)
2394   (message-mode))
2395
2396 (defun message-do-send-housekeeping ()
2397   "Kill old message buffers."
2398   ;; We might have sent this buffer already.  Delete it from the
2399   ;; list of buffers.
2400   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2401   (while (and message-max-buffers
2402               (>= (length message-buffer-list) message-max-buffers))
2403     ;; Kill the oldest buffer -- unless it has been changed.
2404     (let ((buffer (pop message-buffer-list)))
2405       (when (and (buffer-name buffer)
2406                  (not (buffer-modified-p buffer)))
2407         (kill-buffer buffer))))
2408   ;; Rename the buffer.
2409   (if message-send-rename-function
2410       (funcall message-send-rename-function)
2411     (when (string-match "\\`\\*" (buffer-name))
2412       (rename-buffer 
2413        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2414   ;; Push the current buffer onto the list.
2415   (when message-max-buffers
2416     (setq message-buffer-list 
2417           (nconc message-buffer-list (list (current-buffer))))))
2418
2419 (defvar mc-modes-alist)
2420 (defun message-setup (headers &optional replybuffer actions)
2421   (when (and (boundp 'mc-modes-alist)
2422              (not (assq 'message-mode mc-modes-alist)))
2423     (push '(message-mode (encrypt . mc-encrypt-message)
2424                          (sign . mc-sign-message))
2425           mc-modes-alist))
2426   (when actions
2427     (setq message-send-actions actions))
2428   (setq message-reply-buffer replybuffer)
2429   (goto-char (point-min))
2430   ;; Insert all the headers.
2431   (mail-header-format 
2432    (let ((h headers)
2433          (alist message-header-format-alist))
2434      (while h
2435        (unless (assq (caar h) message-header-format-alist)
2436          (push (list (caar h)) alist))
2437        (pop h))
2438      alist)
2439    headers)
2440   (delete-region (point) (progn (forward-line -1) (point)))
2441   (when message-default-headers
2442     (insert message-default-headers))
2443   (put-text-property
2444    (point)
2445    (progn
2446      (insert mail-header-separator "\n")
2447      (1- (point)))
2448    'read-only nil)
2449   (forward-line -1)
2450   (when (message-news-p)
2451     (when message-default-news-headers
2452       (insert message-default-news-headers))
2453     (when message-generate-headers-first
2454       (message-generate-headers
2455        (delq 'Lines
2456              (delq 'Subject
2457                    (copy-sequence message-required-news-headers))))))
2458   (when (message-mail-p)
2459     (when message-default-mail-headers
2460       (insert message-default-mail-headers))
2461     (when message-generate-headers-first
2462       (message-generate-headers
2463        (delq 'Lines
2464              (delq 'Subject
2465                    (copy-sequence message-required-mail-headers))))))
2466   (run-hooks 'message-signature-setup-hook)
2467   (message-insert-signature)
2468   (message-set-auto-save-file-name)
2469   (save-restriction
2470     (message-narrow-to-headers)
2471     (run-hooks 'message-header-setup-hook))
2472   (set-buffer-modified-p nil)
2473   (run-hooks 'message-setup-hook)
2474   (message-position-point)
2475   (undo-boundary))
2476
2477 (defun message-set-auto-save-file-name ()
2478   "Associate the message buffer with a file in the drafts directory."
2479   (when message-autosave-directory
2480     (unless (file-exists-p message-autosave-directory)
2481       (make-directory message-autosave-directory t))
2482     (let ((name (make-temp-name
2483                  (concat (file-name-as-directory message-autosave-directory)
2484                          "msg."))))
2485       (setq buffer-auto-save-file-name
2486             (save-excursion
2487               (prog1
2488                   (progn
2489                     (set-buffer (get-buffer-create " *draft tmp*"))
2490                     (setq buffer-file-name name)
2491                     (make-auto-save-file-name))
2492                 (kill-buffer (current-buffer)))))
2493       (clear-visited-file-modtime))))
2494
2495 \f
2496
2497 ;;;
2498 ;;; Commands for interfacing with message
2499 ;;;
2500
2501 ;;;###autoload
2502 (defun message-mail (&optional to subject)
2503   "Start editing a mail message to be sent."
2504   (interactive)
2505   (message-pop-to-buffer (message-buffer-name "mail" to))
2506   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2507
2508 ;;;###autoload
2509 (defun message-news (&optional newsgroups subject)
2510   "Start editing a news article to be sent."
2511   (interactive)
2512   (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2513   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2514                    (Subject . ,(or subject "")))))
2515
2516 ;;;###autoload
2517 (defun message-reply (&optional to-address wide ignore-reply-to)
2518   "Start editing a reply to the article in the current buffer."
2519   (interactive)
2520   (let ((cur (current-buffer))
2521         from subject date reply-to to cc
2522         references message-id follow-to 
2523         (inhibit-point-motion-hooks t)
2524         mct never-mct gnus-warning)
2525     (save-restriction
2526       (message-narrow-to-head)
2527       ;; Allow customizations to have their say.
2528       (if (not wide)
2529           ;; This is a regular reply.
2530           (if (message-functionp message-reply-to-function)
2531               (setq follow-to (funcall message-reply-to-function)))
2532         ;; This is a followup.
2533         (if (message-functionp message-wide-reply-to-function)
2534             (save-excursion
2535               (setq follow-to
2536                     (funcall message-wide-reply-to-function)))))
2537       ;; Find all relevant headers we need.
2538       (setq from (message-fetch-field "from")
2539             date (message-fetch-field "date") 
2540             subject (or (message-fetch-field "subject") "none")
2541             to (message-fetch-field "to")
2542             cc (message-fetch-field "cc")
2543             mct (message-fetch-field "mail-copies-to")
2544             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2545             references (message-fetch-field "references")
2546             message-id (message-fetch-field "message-id"))
2547       ;; Remove any (buggy) Re:'s that are present and make a
2548       ;; proper one.
2549       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2550         (setq subject (substring subject (match-end 0))))
2551       (setq subject (concat "Re: " subject))
2552
2553       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2554                  (string-match "<[^>]+>" gnus-warning))
2555         (setq message-id (match-string 0 gnus-warning)))
2556             
2557       ;; Handle special values of Mail-Copies-To.
2558       (when mct
2559         (cond ((equal (downcase mct) "never")
2560                (setq never-mct t)
2561                (setq mct nil))
2562               ((equal (downcase mct) "always")
2563                (setq mct (or reply-to from)))))
2564
2565       (unless follow-to
2566         (if (or (not wide)
2567                 to-address)
2568             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2569           (let (ccalist)
2570             (save-excursion
2571               (message-set-work-buffer)
2572               (unless never-mct
2573                 (insert (or reply-to from "")))
2574               (insert (if (bolp) "" ", ") (or to ""))
2575               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2576               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2577               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2578               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2579                         (erase-buffer)))
2580               (goto-char (point-min))
2581               (setq ccalist
2582                     (mapcar
2583                      (lambda (addr)
2584                        (cons (mail-strip-quoted-names addr) addr))
2585                      (message-tokenize-header (buffer-string))))
2586               (let ((s ccalist))
2587                 (while s
2588                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2589             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2590             (when ccalist
2591               (push (cons 'Cc
2592                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2593                     follow-to)))))
2594       (widen))
2595
2596     (message-pop-to-buffer (message-buffer-name
2597                             (if wide "wide reply" "reply") from
2598                             (if wide to-address nil)))
2599
2600     (setq message-reply-headers
2601           (vector 0 subject from date message-id references 0 0 ""))
2602
2603     (message-setup
2604      `((Subject . ,subject)
2605        ,@follow-to 
2606        ,@(if (or references message-id)
2607              `((References . ,(concat (or references "") (and references " ")
2608                                       (or message-id ""))))
2609            nil))
2610      cur)))
2611
2612 ;;;###autoload
2613 (defun message-wide-reply (&optional to-address)
2614   (interactive)
2615   (message-reply to-address t))
2616
2617 ;;;###autoload
2618 (defun message-followup ()
2619   (interactive)
2620   (let ((cur (current-buffer))
2621         from subject date reply-to mct
2622         references message-id follow-to 
2623         (inhibit-point-motion-hooks t)
2624         followup-to distribution newsgroups gnus-warning)
2625     (save-restriction
2626       (narrow-to-region
2627        (goto-char (point-min))
2628        (if (search-forward "\n\n" nil t)
2629            (1- (point))
2630          (point-max)))
2631       (when (message-functionp message-followup-to-function)
2632         (setq follow-to
2633               (funcall message-followup-to-function)))
2634       (setq from (message-fetch-field "from")
2635             date (message-fetch-field "date") 
2636             subject (or (message-fetch-field "subject") "none")
2637             references (message-fetch-field "references")
2638             message-id (message-fetch-field "message-id")
2639             followup-to (message-fetch-field "followup-to")
2640             newsgroups (message-fetch-field "newsgroups")
2641             reply-to (message-fetch-field "reply-to")
2642             distribution (message-fetch-field "distribution")
2643             mct (message-fetch-field "mail-copies-to"))
2644       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2645                  (string-match "<[^>]+>" gnus-warning))
2646         (setq message-id (match-string 0 gnus-warning)))
2647       ;; Remove bogus distribution.
2648       (and (stringp distribution)
2649            (string-match "world" distribution)
2650            (setq distribution nil))
2651       ;; Remove any (buggy) Re:'s that are present and make a
2652       ;; proper one.
2653       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2654         (setq subject (substring subject (match-end 0))))
2655       (setq subject (concat "Re: " subject))
2656       (widen))
2657
2658     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2659
2660     (message-setup
2661      `((Subject . ,subject)
2662        ,@(cond 
2663           (follow-to follow-to)
2664           ((and followup-to message-use-followup-to)
2665            (list
2666             (cond 
2667              ((equal (downcase followup-to) "poster")
2668               (if (or (eq message-use-followup-to 'use)
2669                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2670 You should normally obey the Followup-To: header.
2671
2672 `Followup-To: poster' sends your response via e-mail instead of news.
2673
2674 A typical situation where `Followup-To: poster' is used is when the poster
2675 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2676                   (cons 'To (or reply-to from ""))
2677                 (cons 'Newsgroups newsgroups)))
2678              (t
2679               (if (or (equal followup-to newsgroups)
2680                       (not (eq message-use-followup-to 'ask))
2681                       (message-y-or-n-p
2682                        (concat "Obey Followup-To: " followup-to "? ") t "\
2683 You should normally obey the Followup-To: header.
2684
2685         `Followup-To: " followup-to "'
2686 directs your response to " (if (string-match "," followup-to)
2687                                "the specified newsgroups"
2688                              "that newsgroup only") ".
2689
2690 If a message is posted to several newsgroups, Followup-To is often
2691 used to direct the following discussion to one newsgroup only,
2692 because discussions that are spread over several newsgroup tend to
2693 be fragmented and very difficult to follow.
2694
2695 Also, some source/announcment newsgroups are not indented for discussion;
2696 responses here are directed to other newsgroups."))
2697                   (cons 'Newsgroups followup-to)
2698                 (cons 'Newsgroups newsgroups))))))
2699           (t
2700            `((Newsgroups . ,newsgroups))))
2701        ,@(and distribution (list (cons 'Distribution distribution)))
2702        (References . ,(concat (or references "") (and references " ")
2703                               (or message-id "")))
2704        ,@(when (and mct
2705                     (not (equal (downcase mct) "never")))
2706            (list (cons 'Cc (if (equal (downcase mct) "always")
2707                                (or reply-to from "")
2708                              mct)))))
2709
2710      cur)
2711
2712     (setq message-reply-headers
2713           (vector 0 subject from date message-id references 0 0 ""))))
2714
2715
2716 ;;;###autoload
2717 (defun message-cancel-news ()
2718   "Cancel an article you posted."
2719   (interactive)
2720   (unless (message-news-p)
2721     (error "This is not a news article; canceling is impossible"))
2722   (when (yes-or-no-p "Do you really want to cancel this article? ")
2723     (let (from newsgroups message-id distribution buf)
2724       (save-excursion
2725         ;; Get header info. from original article.
2726         (save-restriction
2727           (message-narrow-to-head)
2728           (setq from (message-fetch-field "from")
2729                 newsgroups (message-fetch-field "newsgroups")
2730                 message-id (message-fetch-field "message-id")
2731                 distribution (message-fetch-field "distribution")))
2732         ;; Make sure that this article was written by the user.
2733         (unless (string-equal
2734                  (downcase (cadr (mail-extract-address-components from)))
2735                  (downcase (message-make-address)))
2736           (error "This article is not yours"))
2737         ;; Make control message.
2738         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2739         (buffer-disable-undo (current-buffer))
2740         (erase-buffer)
2741         (insert "Newsgroups: " newsgroups "\n"
2742                 "From: " (message-make-from) "\n"
2743                 "Subject: cmsg cancel " message-id "\n"
2744                 "Control: cancel " message-id "\n"
2745                 (if distribution
2746                     (concat "Distribution: " distribution "\n")
2747                   "")
2748                 mail-header-separator "\n"
2749                 message-cancel-message)
2750         (message "Canceling your article...")
2751         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
2752           (funcall message-send-news-function))
2753         (message "Canceling your article...done")
2754         (kill-buffer buf)))))
2755
2756 ;;;###autoload
2757 (defun message-supersede ()
2758   "Start composing a message to supersede the current message.
2759 This is done simply by taking the old article and adding a Supersedes
2760 header line with the old Message-ID."
2761   (interactive)
2762   (let ((cur (current-buffer)))
2763     ;; Check whether the user owns the article that is to be superseded. 
2764     (unless (string-equal
2765              (downcase (cadr (mail-extract-address-components
2766                               (message-fetch-field "from"))))
2767              (downcase (message-make-address)))
2768       (error "This article is not yours"))
2769     ;; Get a normal message buffer.
2770     (message-pop-to-buffer (message-buffer-name "supersede"))
2771     (insert-buffer-substring cur)
2772     (message-narrow-to-head)
2773     ;; Remove unwanted headers.
2774     (when message-ignored-supersedes-headers
2775       (message-remove-header message-ignored-supersedes-headers t))
2776     (goto-char (point-min))
2777     (if (not (re-search-forward "^Message-ID: " nil t))
2778         (error "No Message-ID in this article")
2779       (replace-match "Supersedes: " t t))
2780     (goto-char (point-max))
2781     (insert mail-header-separator)
2782     (widen)
2783     (forward-line 1)))
2784
2785 ;;;###autoload
2786 (defun message-recover ()
2787   "Reread contents of current buffer from its last auto-save file."
2788   (interactive)
2789   (let ((file-name (make-auto-save-file-name)))
2790     (cond ((save-window-excursion
2791              (if (not (eq system-type 'vax-vms))
2792                  (with-output-to-temp-buffer "*Directory*"
2793                    (buffer-disable-undo standard-output)
2794                    (let ((default-directory "/"))
2795                      (call-process
2796                       "ls" nil standard-output nil "-l" file-name))))
2797              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2798            (let ((buffer-read-only nil))
2799              (erase-buffer)
2800              (insert-file-contents file-name nil)))
2801           (t (error "message-recover cancelled")))))
2802
2803 ;;; Forwarding messages.
2804
2805 (defun message-make-forward-subject ()
2806   "Return a Subject header suitable for the message in the current buffer."
2807   (concat "[" (or (message-fetch-field (if (message-news-p) "newsgroups" "from"))
2808                   "(nowhere)")
2809           "] " (or (message-fetch-field "Subject") "")))
2810
2811 ;;;###autoload
2812 (defun message-forward (&optional news)
2813   "Forward the current message via mail.  
2814 Optional NEWS will use news to forward instead of mail."
2815   (interactive "P")
2816   (let ((cur (current-buffer))
2817         (subject (message-make-forward-subject))
2818         art-beg)
2819     (if news (message-news nil subject) (message-mail nil subject))
2820     ;; Put point where we want it before inserting the forwarded
2821     ;; message. 
2822     (if message-signature-before-forwarded-message
2823         (goto-char (point-max))
2824       (message-goto-body))
2825     ;; Make sure we're at the start of the line.
2826     (unless (eolp)
2827       (insert "\n"))
2828     ;; Narrow to the area we are to insert.
2829     (narrow-to-region (point) (point))
2830     ;; Insert the separators and the forwarded buffer.
2831     (insert message-forward-start-separator)
2832     (setq art-beg (point))
2833     (insert-buffer-substring cur)
2834     (goto-char (point-max))
2835     (insert message-forward-end-separator)
2836     (set-text-properties (point-min) (point-max) nil)
2837     ;; Remove all unwanted headers.
2838     (goto-char art-beg)
2839     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2840                                   (1- (point))
2841                                 (point)))
2842     (goto-char (point-min))
2843     (message-remove-header message-included-forward-headers t nil t)
2844     (widen)
2845     (message-position-point)))
2846
2847 ;;;###autoload
2848 (defun message-resend (address)
2849   "Resend the current article to ADDRESS."
2850   (interactive "sResend message to: ")
2851   (save-excursion
2852     (let ((cur (current-buffer))
2853           beg)
2854       ;; We first set up a normal mail buffer.
2855       (set-buffer (get-buffer-create " *message resend*"))
2856       (buffer-disable-undo (current-buffer))
2857       (erase-buffer)
2858       (message-setup `((To . ,address)))
2859       ;; Insert our usual headers.
2860       (message-generate-headers '(From Date To))
2861       (message-narrow-to-headers)
2862       ;; Rename them all to "Resent-*".
2863       (while (re-search-forward "^[A-Za-z]" nil t)
2864         (forward-char -1)
2865         (insert "Resent-"))
2866       (widen)
2867       (forward-line)
2868       (delete-region (point) (point-max))
2869       (setq beg (point))
2870       ;; Insert the message to be resent.
2871       (insert-buffer-substring cur)
2872       (goto-char (point-min))
2873       (search-forward "\n\n")
2874       (forward-char -1)
2875       (save-restriction
2876         (narrow-to-region beg (point))
2877         (message-remove-header message-ignored-resent-headers t)
2878         (goto-char (point-max)))
2879       (insert mail-header-separator)
2880       ;; Rename all old ("Also-")Resent headers.
2881       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2882         (beginning-of-line)
2883         (insert "Also-"))
2884       ;; Send it.
2885       (message-send-mail)
2886       (kill-buffer (current-buffer)))))
2887
2888 ;;;###autoload
2889 (defun message-bounce ()
2890   "Re-mail the current message.
2891 This only makes sense if the current message is a bounce message than
2892 contains some mail you have written which has been bounced back to
2893 you."
2894   (interactive)
2895   (let ((cur (current-buffer))
2896         boundary)
2897     (message-pop-to-buffer (message-buffer-name "bounce"))
2898     (insert-buffer-substring cur)
2899     (undo-boundary)
2900     (message-narrow-to-head)
2901     (if (and (message-fetch-field "Mime-Version")
2902              (setq boundary (message-fetch-field "Content-Type")))
2903         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
2904             (setq boundary (concat (match-string 1 boundary) " *\n"
2905                                    "Content-Type: message/rfc822"))
2906           (setq boundary nil)))
2907     (widen)
2908     (goto-char (point-min))
2909     (search-forward "\n\n" nil t)
2910     (or (and boundary
2911              (re-search-forward boundary nil t)
2912              (forward-line 2))
2913         (and (re-search-forward message-unsent-separator nil t)
2914              (forward-line 1))
2915         (and (search-forward "\n\n" nil t)
2916              (re-search-forward "^Return-Path:.*\n" nil t)))
2917     ;; We remove everything before the bounced mail.
2918     (delete-region 
2919      (point-min)
2920      (if (re-search-forward "^[^ \n\t]+:" nil t)
2921          (match-beginning 0)
2922        (point)))
2923     (save-restriction
2924       (message-narrow-to-head)
2925       (message-remove-header message-ignored-bounced-headers t)
2926       (goto-char (point-max))
2927       (insert mail-header-separator))
2928     (message-position-point)))
2929
2930 ;;;
2931 ;;; Interactive entry points for new message buffers.
2932 ;;;
2933
2934 ;;;###autoload
2935 (defun message-mail-other-window (&optional to subject)
2936   "Like `message-mail' command, but display mail buffer in another window."
2937   (interactive)
2938   (let ((pop-up-windows t)
2939         (special-display-buffer-names nil)
2940         (special-display-regexps nil)
2941         (same-window-buffer-names nil)
2942         (same-window-regexps nil))
2943     (message-pop-to-buffer (message-buffer-name "mail" to)))
2944   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2945
2946 ;;;###autoload
2947 (defun message-mail-other-frame (&optional to subject)
2948   "Like `message-mail' command, but display mail buffer in another frame."
2949   (interactive)
2950   (let ((pop-up-frames 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-news-other-window (&optional newsgroups subject)
2960   "Start editing a news article to be sent."
2961   (interactive)
2962   (let ((pop-up-windows 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 "news" nil newsgroups)))
2968   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2969                    (Subject . ,(or subject "")))))
2970
2971 ;;;###autoload
2972 (defun message-news-other-frame (&optional newsgroups subject)
2973   "Start editing a news article to be sent."
2974   (interactive)
2975   (let ((pop-up-frames t)
2976         (special-display-buffer-names nil)
2977         (special-display-regexps nil)
2978         (same-window-buffer-names nil)
2979         (same-window-regexps nil))
2980     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2981   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2982                    (Subject . ,(or subject "")))))
2983
2984 ;;; underline.el
2985
2986 ;; This code should be moved to underline.el (from which it is stolen). 
2987
2988 ;;;###autoload
2989 (defun bold-region (start end)
2990   "Bold all nonblank characters in the region.
2991 Works by overstriking characters.
2992 Called from program, takes two arguments START and END
2993 which specify the range to operate on."
2994   (interactive "r")
2995   (save-excursion
2996    (let ((end1 (make-marker)))
2997      (move-marker end1 (max start end))
2998      (goto-char (min start end))
2999      (while (< (point) end1)
3000        (or (looking-at "[_\^@- ]")
3001            (insert (following-char) "\b"))
3002        (forward-char 1)))))
3003
3004 ;;;###autoload
3005 (defun unbold-region (start end)
3006   "Remove all boldness (overstruck characters) in the region.
3007 Called from program, takes two arguments START and END
3008 which specify the range to operate on."
3009   (interactive "r")
3010   (save-excursion
3011    (let ((end1 (make-marker)))
3012      (move-marker end1 (max start end))
3013      (goto-char (min start end)) 
3014      (while (re-search-forward "\b" end1 t)
3015        (if (eq (following-char) (char-after (- (point) 2)))
3016            (delete-char -2))))))
3017
3018 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3019
3020 ;; Support for toolbar
3021 (when (string-match "XEmacs\\|Lucid" emacs-version)
3022   (require 'messagexmas))
3023
3024 ;;; Group name completion.
3025
3026 (defvar message-newgroups-header-regexp
3027   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
3028   "Regexp that match headers that lists groups.")
3029
3030 (defun message-tab ()
3031   "Expand group names in Newsgroups and Followup-To headers.
3032 Do a `tab-to-tab-stop' if not in those headers."
3033   (interactive)
3034   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3035         (mail-abbrev-in-expansion-header-p))
3036       (message-expand-group)
3037     (tab-to-tab-stop)))
3038
3039 (defvar gnus-active-hashtb)
3040 (defun message-expand-group ()
3041   (let* ((b (save-excursion (skip-chars-backward "^, :\t\n") (point)))
3042          (completion-ignore-case t)
3043          (string (buffer-substring b (point)))
3044          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3045          (completions (all-completions string hashtb))
3046          (cur (current-buffer))
3047          comp)
3048     (delete-region b (point))
3049     (cond 
3050      ((= (length completions) 1)
3051       (if (string= (car completions) string)
3052           (progn
3053             (insert string)
3054             (message "Only matching group"))
3055         (insert (car completions))))
3056      ((and (setq comp (try-completion string hashtb))
3057            (not (string= comp string)))
3058       (insert comp))
3059      (t
3060       (insert string)
3061       (if (not comp)
3062           (message "No matching groups")
3063         (pop-to-buffer "*Completions*")
3064         (buffer-disable-undo (current-buffer))
3065         (let ((buffer-read-only nil))
3066           (erase-buffer)
3067           (let ((standard-output (current-buffer)))
3068             (display-completion-list (sort completions 'string<)))
3069           (goto-char (point-min))
3070           (pop-to-buffer cur)))))))
3071
3072 ;;; Help stuff.
3073
3074 (defun message-talkative-question (ask question show &rest text)
3075   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
3076 The following arguments may contain lists of values."
3077   (if (and show
3078            (setq text (message-flatten-list text)))
3079       (save-window-excursion
3080         (save-excursion
3081           (with-output-to-temp-buffer " *MESSAGE information message*"
3082             (set-buffer " *MESSAGE information message*")
3083             (mapcar 'princ text)
3084             (goto-char (point-min))))
3085         (funcall ask question))
3086     (funcall ask question)))
3087
3088 (defun message-flatten-list (&rest list)
3089   (message-flatten-list-1 list))
3090
3091 (defun message-flatten-list-1 (list)
3092   (cond ((consp list) 
3093          (apply 'append (mapcar 'message-flatten-list-1 list)))
3094         (list
3095          (list list))))
3096
3097 (run-hooks 'message-load-hook)
3098
3099 (provide 'message)
3100
3101 ;;; message.el ends here