*** 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     (when message-courtesy-message
2284       (insert message-courtesy-message))))
2285     
2286 ;;;
2287 ;;; Setting up a message buffer
2288 ;;;
2289
2290 (defun message-fill-address (header value)
2291   (save-restriction
2292     (narrow-to-region (point) (point))
2293     (insert (capitalize (symbol-name header))
2294             ": "
2295             (if (consp value) (car value) value)
2296             "\n")
2297     (narrow-to-region (point-min) (1- (point-max)))
2298     (let (quoted last)
2299       (goto-char (point-min))
2300       (while (not (eobp))
2301         (skip-chars-forward "^,\"" (point-max))
2302         (if (or (= (following-char) ?,)
2303                 (eobp))
2304             (when (not quoted)
2305               (if (and (> (current-column) 78)
2306                        last)
2307                   (progn
2308                     (save-excursion
2309                       (goto-char last)
2310                       (insert "\n\t"))
2311                     (setq last (1+ (point))))
2312                 (setq last (1+ (point)))))
2313           (setq quoted (not quoted)))
2314         (unless (eobp)
2315           (forward-char 1))))
2316     (goto-char (point-max))
2317     (widen)
2318     (forward-line 1)))
2319
2320 (defun message-fill-header (header value)
2321   (let ((begin (point))
2322         (fill-column 78)
2323         (fill-prefix "\t"))
2324     (insert (capitalize (symbol-name header))
2325             ": "
2326             (if (consp value) (car value) value)
2327             "\n")
2328     (save-restriction
2329       (narrow-to-region begin (point))
2330       (fill-region-as-paragraph begin (point))
2331       ;; Tapdance around looong Message-IDs.
2332       (forward-line -1)
2333       (when (looking-at "[ \t]*$")
2334         (message-delete-line))
2335       (goto-char begin)
2336       (re-search-forward ":" nil t)
2337       (when (looking-at "\n[ \t]+")
2338         (replace-match " " t t))
2339       (goto-char (point-max)))))
2340
2341 (defun message-position-point ()
2342   "Move point to where the user probably wants to find it."
2343   (message-narrow-to-headers)
2344   (cond 
2345    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
2346     (search-backward ":" )
2347     (widen)
2348     (forward-char 1)
2349     (if (= (following-char) ? )
2350         (forward-char 1)
2351       (insert " ")))
2352    (t
2353     (goto-char (point-max))
2354     (widen)
2355     (forward-line 1)
2356     (unless (looking-at "$")
2357       (forward-line 2)))
2358    (sit-for 0)))
2359
2360 (defun message-buffer-name (type &optional to group)
2361   "Return a new (unique) buffer name based on TYPE and TO."
2362   (cond
2363    ;; Check whether `message-generate-new-buffers' is a function, 
2364    ;; and if so, call it.
2365    ((message-functionp message-generate-new-buffers)
2366     (funcall message-generate-new-buffers type to group))
2367    ;; Generate a new buffer name The Message Way.
2368    (message-generate-new-buffers
2369     (generate-new-buffer-name
2370      (concat "*" type
2371              (if to
2372                  (concat " to "
2373                          (or (car (mail-extract-address-components to))
2374                              to) "")
2375                "")
2376              (if (and group (not (string= group ""))) (concat " on " group) "")
2377              "*")))
2378    ;; Use standard name.
2379    (t
2380     (format "*%s message*" type))))
2381
2382 (defun message-pop-to-buffer (name)
2383   "Pop to buffer NAME, and warn if it already exists and is modified."
2384   (let ((buffer (get-buffer name)))
2385     (if (and buffer
2386              (buffer-name buffer))
2387         (progn
2388           (set-buffer (pop-to-buffer buffer))
2389           (when (and (buffer-modified-p)
2390                      (not (y-or-n-p
2391                            "Message already being composed; erase? ")))
2392             (error "Message being composed")))
2393       (set-buffer (pop-to-buffer name))))
2394   (erase-buffer)
2395   (message-mode))
2396
2397 (defun message-do-send-housekeeping ()
2398   "Kill old message buffers."
2399   ;; We might have sent this buffer already.  Delete it from the
2400   ;; list of buffers.
2401   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
2402   (while (and message-max-buffers
2403               (>= (length message-buffer-list) message-max-buffers))
2404     ;; Kill the oldest buffer -- unless it has been changed.
2405     (let ((buffer (pop message-buffer-list)))
2406       (when (and (buffer-name buffer)
2407                  (not (buffer-modified-p buffer)))
2408         (kill-buffer buffer))))
2409   ;; Rename the buffer.
2410   (if message-send-rename-function
2411       (funcall message-send-rename-function)
2412     (when (string-match "\\`\\*" (buffer-name))
2413       (rename-buffer 
2414        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
2415   ;; Push the current buffer onto the list.
2416   (when message-max-buffers
2417     (setq message-buffer-list 
2418           (nconc message-buffer-list (list (current-buffer))))))
2419
2420 (defvar mc-modes-alist)
2421 (defun message-setup (headers &optional replybuffer actions)
2422   (when (and (boundp 'mc-modes-alist)
2423              (not (assq 'message-mode mc-modes-alist)))
2424     (push '(message-mode (encrypt . mc-encrypt-message)
2425                          (sign . mc-sign-message))
2426           mc-modes-alist))
2427   (when actions
2428     (setq message-send-actions actions))
2429   (setq message-reply-buffer replybuffer)
2430   (goto-char (point-min))
2431   ;; Insert all the headers.
2432   (mail-header-format 
2433    (let ((h headers)
2434          (alist message-header-format-alist))
2435      (while h
2436        (unless (assq (caar h) message-header-format-alist)
2437          (push (list (caar h)) alist))
2438        (pop h))
2439      alist)
2440    headers)
2441   (delete-region (point) (progn (forward-line -1) (point)))
2442   (when message-default-headers
2443     (insert message-default-headers))
2444   (put-text-property
2445    (point)
2446    (progn
2447      (insert mail-header-separator "\n")
2448      (1- (point)))
2449    'read-only nil)
2450   (forward-line -1)
2451   (when (message-news-p)
2452     (when message-default-news-headers
2453       (insert message-default-news-headers))
2454     (when message-generate-headers-first
2455       (message-generate-headers
2456        (delq 'Lines
2457              (delq 'Subject
2458                    (copy-sequence message-required-news-headers))))))
2459   (when (message-mail-p)
2460     (when message-default-mail-headers
2461       (insert message-default-mail-headers))
2462     (when message-generate-headers-first
2463       (message-generate-headers
2464        (delq 'Lines
2465              (delq 'Subject
2466                    (copy-sequence message-required-mail-headers))))))
2467   (run-hooks 'message-signature-setup-hook)
2468   (message-insert-signature)
2469   (message-set-auto-save-file-name)
2470   (save-restriction
2471     (message-narrow-to-headers)
2472     (run-hooks 'message-header-setup-hook))
2473   (set-buffer-modified-p nil)
2474   (run-hooks 'message-setup-hook)
2475   (message-position-point)
2476   (undo-boundary))
2477
2478 (defun message-set-auto-save-file-name ()
2479   "Associate the message buffer with a file in the drafts directory."
2480   (when message-autosave-directory
2481     (unless (file-exists-p message-autosave-directory)
2482       (make-directory message-autosave-directory t))
2483     (let ((name (make-temp-name
2484                  (concat (file-name-as-directory message-autosave-directory)
2485                          "msg."))))
2486       (setq buffer-auto-save-file-name
2487             (save-excursion
2488               (prog1
2489                   (progn
2490                     (set-buffer (get-buffer-create " *draft tmp*"))
2491                     (setq buffer-file-name name)
2492                     (make-auto-save-file-name))
2493                 (kill-buffer (current-buffer)))))
2494       (clear-visited-file-modtime))))
2495
2496 \f
2497
2498 ;;;
2499 ;;; Commands for interfacing with message
2500 ;;;
2501
2502 ;;;###autoload
2503 (defun message-mail (&optional to subject)
2504   "Start editing a mail message to be sent."
2505   (interactive)
2506   (message-pop-to-buffer (message-buffer-name "mail" to))
2507   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2508
2509 ;;;###autoload
2510 (defun message-news (&optional newsgroups subject)
2511   "Start editing a news article to be sent."
2512   (interactive)
2513   (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
2514   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2515                    (Subject . ,(or subject "")))))
2516
2517 ;;;###autoload
2518 (defun message-reply (&optional to-address wide ignore-reply-to)
2519   "Start editing a reply to the article in the current buffer."
2520   (interactive)
2521   (let ((cur (current-buffer))
2522         from subject date reply-to to cc
2523         references message-id follow-to 
2524         (inhibit-point-motion-hooks t)
2525         mct never-mct gnus-warning)
2526     (save-restriction
2527       (message-narrow-to-head)
2528       ;; Allow customizations to have their say.
2529       (if (not wide)
2530           ;; This is a regular reply.
2531           (if (message-functionp message-reply-to-function)
2532               (setq follow-to (funcall message-reply-to-function)))
2533         ;; This is a followup.
2534         (if (message-functionp message-wide-reply-to-function)
2535             (save-excursion
2536               (setq follow-to
2537                     (funcall message-wide-reply-to-function)))))
2538       ;; Find all relevant headers we need.
2539       (setq from (message-fetch-field "from")
2540             date (message-fetch-field "date") 
2541             subject (or (message-fetch-field "subject") "none")
2542             to (message-fetch-field "to")
2543             cc (message-fetch-field "cc")
2544             mct (message-fetch-field "mail-copies-to")
2545             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
2546             references (message-fetch-field "references")
2547             message-id (message-fetch-field "message-id"))
2548       ;; Remove any (buggy) Re:'s that are present and make a
2549       ;; proper one.
2550       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2551         (setq subject (substring subject (match-end 0))))
2552       (setq subject (concat "Re: " subject))
2553
2554       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2555                  (string-match "<[^>]+>" gnus-warning))
2556         (setq message-id (match-string 0 gnus-warning)))
2557             
2558       ;; Handle special values of Mail-Copies-To.
2559       (when mct
2560         (cond ((equal (downcase mct) "never")
2561                (setq never-mct t)
2562                (setq mct nil))
2563               ((equal (downcase mct) "always")
2564                (setq mct (or reply-to from)))))
2565
2566       (unless follow-to
2567         (if (or (not wide)
2568                 to-address)
2569             (setq follow-to (list (cons 'To (or to-address reply-to from))))
2570           (let (ccalist)
2571             (save-excursion
2572               (message-set-work-buffer)
2573               (unless never-mct
2574                 (insert (or reply-to from "")))
2575               (insert (if (bolp) "" ", ") (or to ""))
2576               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
2577               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
2578               ;; Remove addresses that match `rmail-dont-reply-to-names'. 
2579               (insert (prog1 (rmail-dont-reply-to (buffer-string))
2580                         (erase-buffer)))
2581               (goto-char (point-min))
2582               (setq ccalist
2583                     (mapcar
2584                      (lambda (addr)
2585                        (cons (mail-strip-quoted-names addr) addr))
2586                      (message-tokenize-header (buffer-string))))
2587               (let ((s ccalist))
2588                 (while s
2589                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
2590             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
2591             (when ccalist
2592               (push (cons 'Cc
2593                           (mapconcat (lambda (addr) (cdr addr)) ccalist ", "))
2594                     follow-to)))))
2595       (widen))
2596
2597     (message-pop-to-buffer (message-buffer-name
2598                             (if wide "wide reply" "reply") from
2599                             (if wide to-address nil)))
2600
2601     (setq message-reply-headers
2602           (vector 0 subject from date message-id references 0 0 ""))
2603
2604     (message-setup
2605      `((Subject . ,subject)
2606        ,@follow-to 
2607        ,@(if (or references message-id)
2608              `((References . ,(concat (or references "") (and references " ")
2609                                       (or message-id ""))))
2610            nil))
2611      cur)))
2612
2613 ;;;###autoload
2614 (defun message-wide-reply (&optional to-address)
2615   "Make a \"wide\" reply to the message in the current buffer."
2616   (interactive)
2617   (message-reply to-address t))
2618
2619 ;;;###autoload
2620 (defun message-followup (&optional to-newsgroups)
2621   "Follow up to the message in the current buffer.
2622 If TO-NEWSGROUPS, use that as the new Newsgroups line."
2623   (interactive)
2624   (let ((cur (current-buffer))
2625         from subject date reply-to mct
2626         references message-id follow-to 
2627         (inhibit-point-motion-hooks t)
2628         followup-to distribution newsgroups gnus-warning)
2629     (save-restriction
2630       (narrow-to-region
2631        (goto-char (point-min))
2632        (if (search-forward "\n\n" nil t)
2633            (1- (point))
2634          (point-max)))
2635       (when (message-functionp message-followup-to-function)
2636         (setq follow-to
2637               (funcall message-followup-to-function)))
2638       (setq from (message-fetch-field "from")
2639             date (message-fetch-field "date") 
2640             subject (or (message-fetch-field "subject") "none")
2641             references (message-fetch-field "references")
2642             message-id (message-fetch-field "message-id")
2643             followup-to (message-fetch-field "followup-to")
2644             newsgroups (message-fetch-field "newsgroups")
2645             reply-to (message-fetch-field "reply-to")
2646             distribution (message-fetch-field "distribution")
2647             mct (message-fetch-field "mail-copies-to"))
2648       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
2649                  (string-match "<[^>]+>" gnus-warning))
2650         (setq message-id (match-string 0 gnus-warning)))
2651       ;; Remove bogus distribution.
2652       (and (stringp distribution)
2653            (string-match "world" distribution)
2654            (setq distribution nil))
2655       ;; Remove any (buggy) Re:'s that are present and make a
2656       ;; proper one.
2657       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
2658         (setq subject (substring subject (match-end 0))))
2659       (setq subject (concat "Re: " subject))
2660       (widen))
2661
2662     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
2663
2664     (message-setup
2665      `((Subject . ,subject)
2666        ,@(cond 
2667           (to-newsgroups
2668            (list (cons 'Newsgroups to-newsgroups)))
2669           (follow-to follow-to)
2670           ((and followup-to message-use-followup-to)
2671            (list
2672             (cond 
2673              ((equal (downcase followup-to) "poster")
2674               (if (or (eq message-use-followup-to 'use)
2675                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
2676 You should normally obey the Followup-To: header.
2677
2678 `Followup-To: poster' sends your response via e-mail instead of news.
2679
2680 A typical situation where `Followup-To: poster' is used is when the poster
2681 does not read the newsgroup, so he wouldn't see any replies sent to it."))
2682                   (cons 'To (or reply-to from ""))
2683                 (cons 'Newsgroups newsgroups)))
2684              (t
2685               (if (or (equal followup-to newsgroups)
2686                       (not (eq message-use-followup-to 'ask))
2687                       (message-y-or-n-p
2688                        (concat "Obey Followup-To: " followup-to "? ") t "\
2689 You should normally obey the Followup-To: header.
2690
2691         `Followup-To: " followup-to "'
2692 directs your response to " (if (string-match "," followup-to)
2693                                "the specified newsgroups"
2694                              "that newsgroup only") ".
2695
2696 If a message is posted to several newsgroups, Followup-To is often
2697 used to direct the following discussion to one newsgroup only,
2698 because discussions that are spread over several newsgroup tend to
2699 be fragmented and very difficult to follow.
2700
2701 Also, some source/announcment newsgroups are not indented for discussion;
2702 responses here are directed to other newsgroups."))
2703                   (cons 'Newsgroups followup-to)
2704                 (cons 'Newsgroups newsgroups))))))
2705           (t
2706            `((Newsgroups . ,newsgroups))))
2707        ,@(and distribution (list (cons 'Distribution distribution)))
2708        ,@(if (or references message-id)
2709              `((References . ,(concat (or references "") (and references " ")
2710                                       (or message-id "")))))
2711        ,@(when (and mct
2712                     (not (equal (downcase mct) "never")))
2713            (list (cons 'Cc (if (equal (downcase mct) "always")
2714                                (or reply-to from "")
2715                              mct)))))
2716
2717      cur)
2718
2719     (setq message-reply-headers
2720           (vector 0 subject from date message-id references 0 0 ""))))
2721
2722
2723 ;;;###autoload
2724 (defun message-cancel-news ()
2725   "Cancel an article you posted."
2726   (interactive)
2727   (unless (message-news-p)
2728     (error "This is not a news article; canceling is impossible"))
2729   (when (yes-or-no-p "Do you really want to cancel this article? ")
2730     (let (from newsgroups message-id distribution buf)
2731       (save-excursion
2732         ;; Get header info. from original article.
2733         (save-restriction
2734           (message-narrow-to-head)
2735           (setq from (message-fetch-field "from")
2736                 newsgroups (message-fetch-field "newsgroups")
2737                 message-id (message-fetch-field "message-id")
2738                 distribution (message-fetch-field "distribution")))
2739         ;; Make sure that this article was written by the user.
2740         (unless (string-equal
2741                  (downcase (cadr (mail-extract-address-components from)))
2742                  (downcase (message-make-address)))
2743           (error "This article is not yours"))
2744         ;; Make control message.
2745         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
2746         (buffer-disable-undo (current-buffer))
2747         (erase-buffer)
2748         (insert "Newsgroups: " newsgroups "\n"
2749                 "From: " (message-make-from) "\n"
2750                 "Subject: cmsg cancel " message-id "\n"
2751                 "Control: cancel " message-id "\n"
2752                 (if distribution
2753                     (concat "Distribution: " distribution "\n")
2754                   "")
2755                 mail-header-separator "\n"
2756                 message-cancel-message)
2757         (message "Canceling your article...")
2758         (let ((message-syntax-checks 'dont-check-for-anything-just-trust-me))
2759           (funcall message-send-news-function))
2760         (message "Canceling your article...done")
2761         (kill-buffer buf)))))
2762
2763 ;;;###autoload
2764 (defun message-supersede ()
2765   "Start composing a message to supersede the current message.
2766 This is done simply by taking the old article and adding a Supersedes
2767 header line with the old Message-ID."
2768   (interactive)
2769   (let ((cur (current-buffer)))
2770     ;; Check whether the user owns the article that is to be superseded. 
2771     (unless (string-equal
2772              (downcase (cadr (mail-extract-address-components
2773                               (message-fetch-field "from"))))
2774              (downcase (message-make-address)))
2775       (error "This article is not yours"))
2776     ;; Get a normal message buffer.
2777     (message-pop-to-buffer (message-buffer-name "supersede"))
2778     (insert-buffer-substring cur)
2779     (message-narrow-to-head)
2780     ;; Remove unwanted headers.
2781     (when message-ignored-supersedes-headers
2782       (message-remove-header message-ignored-supersedes-headers t))
2783     (goto-char (point-min))
2784     (if (not (re-search-forward "^Message-ID: " nil t))
2785         (error "No Message-ID in this article")
2786       (replace-match "Supersedes: " t t))
2787     (goto-char (point-max))
2788     (insert mail-header-separator)
2789     (widen)
2790     (forward-line 1)))
2791
2792 ;;;###autoload
2793 (defun message-recover ()
2794   "Reread contents of current buffer from its last auto-save file."
2795   (interactive)
2796   (let ((file-name (make-auto-save-file-name)))
2797     (cond ((save-window-excursion
2798              (if (not (eq system-type 'vax-vms))
2799                  (with-output-to-temp-buffer "*Directory*"
2800                    (buffer-disable-undo standard-output)
2801                    (let ((default-directory "/"))
2802                      (call-process
2803                       "ls" nil standard-output nil "-l" file-name))))
2804              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
2805            (let ((buffer-read-only nil))
2806              (erase-buffer)
2807              (insert-file-contents file-name nil)))
2808           (t (error "message-recover cancelled")))))
2809
2810 ;;; Forwarding messages.
2811
2812 (defun message-make-forward-subject ()
2813   "Return a Subject header suitable for the message in the current buffer."
2814   (concat "[" (or (message-fetch-field (if (message-news-p) "newsgroups" "from"))
2815                   "(nowhere)")
2816           "] " (or (message-fetch-field "Subject") "")))
2817
2818 ;;;###autoload
2819 (defun message-forward (&optional news)
2820   "Forward the current message via mail.  
2821 Optional NEWS will use news to forward instead of mail."
2822   (interactive "P")
2823   (let ((cur (current-buffer))
2824         (subject (message-make-forward-subject))
2825         art-beg)
2826     (if news (message-news nil subject) (message-mail nil subject))
2827     ;; Put point where we want it before inserting the forwarded
2828     ;; message. 
2829     (if message-signature-before-forwarded-message
2830         (goto-char (point-max))
2831       (message-goto-body))
2832     ;; Make sure we're at the start of the line.
2833     (unless (eolp)
2834       (insert "\n"))
2835     ;; Narrow to the area we are to insert.
2836     (narrow-to-region (point) (point))
2837     ;; Insert the separators and the forwarded buffer.
2838     (insert message-forward-start-separator)
2839     (setq art-beg (point))
2840     (insert-buffer-substring cur)
2841     (goto-char (point-max))
2842     (insert message-forward-end-separator)
2843     (set-text-properties (point-min) (point-max) nil)
2844     ;; Remove all unwanted headers.
2845     (goto-char art-beg)
2846     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
2847                                   (1- (point))
2848                                 (point)))
2849     (goto-char (point-min))
2850     (message-remove-header message-included-forward-headers t nil t)
2851     (widen)
2852     (message-position-point)))
2853
2854 ;;;###autoload
2855 (defun message-resend (address)
2856   "Resend the current article to ADDRESS."
2857   (interactive "sResend message to: ")
2858   (save-excursion
2859     (let ((cur (current-buffer))
2860           beg)
2861       ;; We first set up a normal mail buffer.
2862       (set-buffer (get-buffer-create " *message resend*"))
2863       (buffer-disable-undo (current-buffer))
2864       (erase-buffer)
2865       (message-setup `((To . ,address)))
2866       ;; Insert our usual headers.
2867       (message-generate-headers '(From Date To))
2868       (message-narrow-to-headers)
2869       ;; Rename them all to "Resent-*".
2870       (while (re-search-forward "^[A-Za-z]" nil t)
2871         (forward-char -1)
2872         (insert "Resent-"))
2873       (widen)
2874       (forward-line)
2875       (delete-region (point) (point-max))
2876       (setq beg (point))
2877       ;; Insert the message to be resent.
2878       (insert-buffer-substring cur)
2879       (goto-char (point-min))
2880       (search-forward "\n\n")
2881       (forward-char -1)
2882       (save-restriction
2883         (narrow-to-region beg (point))
2884         (message-remove-header message-ignored-resent-headers t)
2885         (goto-char (point-max)))
2886       (insert mail-header-separator)
2887       ;; Rename all old ("Also-")Resent headers.
2888       (while (re-search-backward "^\\(Also-\\)?Resent-" beg t)
2889         (beginning-of-line)
2890         (insert "Also-"))
2891       ;; Send it.
2892       (message-send-mail)
2893       (kill-buffer (current-buffer)))))
2894
2895 ;;;###autoload
2896 (defun message-bounce ()
2897   "Re-mail the current message.
2898 This only makes sense if the current message is a bounce message than
2899 contains some mail you have written which has been bounced back to
2900 you."
2901   (interactive)
2902   (let ((cur (current-buffer))
2903         boundary)
2904     (message-pop-to-buffer (message-buffer-name "bounce"))
2905     (insert-buffer-substring cur)
2906     (undo-boundary)
2907     (message-narrow-to-head)
2908     (if (and (message-fetch-field "Mime-Version")
2909              (setq boundary (message-fetch-field "Content-Type")))
2910         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
2911             (setq boundary (concat (match-string 1 boundary) " *\n"
2912                                    "Content-Type: message/rfc822"))
2913           (setq boundary nil)))
2914     (widen)
2915     (goto-char (point-min))
2916     (search-forward "\n\n" nil t)
2917     (or (and boundary
2918              (re-search-forward boundary nil t)
2919              (forward-line 2))
2920         (and (re-search-forward message-unsent-separator nil t)
2921              (forward-line 1))
2922         (and (search-forward "\n\n" nil t)
2923              (re-search-forward "^Return-Path:.*\n" nil t)))
2924     ;; We remove everything before the bounced mail.
2925     (delete-region 
2926      (point-min)
2927      (if (re-search-forward "^[^ \n\t]+:" nil t)
2928          (match-beginning 0)
2929        (point)))
2930     (save-restriction
2931       (message-narrow-to-head)
2932       (message-remove-header message-ignored-bounced-headers t)
2933       (goto-char (point-max))
2934       (insert mail-header-separator))
2935     (message-position-point)))
2936
2937 ;;;
2938 ;;; Interactive entry points for new message buffers.
2939 ;;;
2940
2941 ;;;###autoload
2942 (defun message-mail-other-window (&optional to subject)
2943   "Like `message-mail' command, but display mail buffer in another window."
2944   (interactive)
2945   (let ((pop-up-windows t)
2946         (special-display-buffer-names nil)
2947         (special-display-regexps nil)
2948         (same-window-buffer-names nil)
2949         (same-window-regexps nil))
2950     (message-pop-to-buffer (message-buffer-name "mail" to)))
2951   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2952
2953 ;;;###autoload
2954 (defun message-mail-other-frame (&optional to subject)
2955   "Like `message-mail' command, but display mail buffer in another frame."
2956   (interactive)
2957   (let ((pop-up-frames t)
2958         (special-display-buffer-names nil)
2959         (special-display-regexps nil)
2960         (same-window-buffer-names nil)
2961         (same-window-regexps nil))
2962     (message-pop-to-buffer (message-buffer-name "mail" to)))
2963   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
2964
2965 ;;;###autoload
2966 (defun message-news-other-window (&optional newsgroups subject)
2967   "Start editing a news article to be sent."
2968   (interactive)
2969   (let ((pop-up-windows t)
2970         (special-display-buffer-names nil)
2971         (special-display-regexps nil)
2972         (same-window-buffer-names nil)
2973         (same-window-regexps nil))
2974     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2975   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2976                    (Subject . ,(or subject "")))))
2977
2978 ;;;###autoload
2979 (defun message-news-other-frame (&optional newsgroups subject)
2980   "Start editing a news article to be sent."
2981   (interactive)
2982   (let ((pop-up-frames t)
2983         (special-display-buffer-names nil)
2984         (special-display-regexps nil)
2985         (same-window-buffer-names nil)
2986         (same-window-regexps nil))
2987     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
2988   (message-setup `((Newsgroups . ,(or newsgroups "")) 
2989                    (Subject . ,(or subject "")))))
2990
2991 ;;; underline.el
2992
2993 ;; This code should be moved to underline.el (from which it is stolen). 
2994
2995 ;;;###autoload
2996 (defun bold-region (start end)
2997   "Bold all nonblank characters in the region.
2998 Works by overstriking characters.
2999 Called from program, takes two arguments START and END
3000 which specify the range to operate on."
3001   (interactive "r")
3002   (save-excursion
3003    (let ((end1 (make-marker)))
3004      (move-marker end1 (max start end))
3005      (goto-char (min start end))
3006      (while (< (point) end1)
3007        (or (looking-at "[_\^@- ]")
3008            (insert (following-char) "\b"))
3009        (forward-char 1)))))
3010
3011 ;;;###autoload
3012 (defun unbold-region (start end)
3013   "Remove all boldness (overstruck characters) in the region.
3014 Called from program, takes two arguments START and END
3015 which specify the range to operate on."
3016   (interactive "r")
3017   (save-excursion
3018    (let ((end1 (make-marker)))
3019      (move-marker end1 (max start end))
3020      (goto-char (min start end)) 
3021      (while (re-search-forward "\b" end1 t)
3022        (if (eq (following-char) (char-after (- (point) 2)))
3023            (delete-char -2))))))
3024
3025 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3026
3027 ;; Support for toolbar
3028 (when (string-match "XEmacs\\|Lucid" emacs-version)
3029   (require 'messagexmas))
3030
3031 ;;; Group name completion.
3032
3033 (defvar message-newgroups-header-regexp
3034   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\):"
3035   "Regexp that match headers that lists groups.")
3036
3037 (defun message-tab ()
3038   "Expand group names in Newsgroups and Followup-To headers.
3039 Do a `tab-to-tab-stop' if not in those headers."
3040   (interactive)
3041   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3042         (mail-abbrev-in-expansion-header-p))
3043       (message-expand-group)
3044     (tab-to-tab-stop)))
3045
3046 (defvar gnus-active-hashtb)
3047 (defun message-expand-group ()
3048   (let* ((b (save-excursion (skip-chars-backward "^, :\t\n") (point)))
3049          (completion-ignore-case t)
3050          (string (buffer-substring b (point)))
3051          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3052          (completions (all-completions string hashtb))
3053          (cur (current-buffer))
3054          comp)
3055     (delete-region b (point))
3056     (cond 
3057      ((= (length completions) 1)
3058       (if (string= (car completions) string)
3059           (progn
3060             (insert string)
3061             (message "Only matching group"))
3062         (insert (car completions))))
3063      ((and (setq comp (try-completion string hashtb))
3064            (not (string= comp string)))
3065       (insert comp))
3066      (t
3067       (insert string)
3068       (if (not comp)
3069           (message "No matching groups")
3070         (pop-to-buffer "*Completions*")
3071         (buffer-disable-undo (current-buffer))
3072         (let ((buffer-read-only nil))
3073           (erase-buffer)
3074           (let ((standard-output (current-buffer)))
3075             (display-completion-list (sort completions 'string<)))
3076           (goto-char (point-min))
3077           (pop-to-buffer cur)))))))
3078
3079 ;;; Help stuff.
3080
3081 (defun message-talkative-question (ask question show &rest text)
3082   "Call FUNCTION with argument QUESTION, displaying the rest of the arguments in a temporary buffer if SHOW.  
3083 The following arguments may contain lists of values."
3084   (if (and show
3085            (setq text (message-flatten-list text)))
3086       (save-window-excursion
3087         (save-excursion
3088           (with-output-to-temp-buffer " *MESSAGE information message*"
3089             (set-buffer " *MESSAGE information message*")
3090             (mapcar 'princ text)
3091             (goto-char (point-min))))
3092         (funcall ask question))
3093     (funcall ask question)))
3094
3095 (defun message-flatten-list (&rest list)
3096   (message-flatten-list-1 list))
3097
3098 (defun message-flatten-list-1 (list)
3099   (cond ((consp list) 
3100          (apply 'append (mapcar 'message-flatten-list-1 list)))
3101         (list
3102          (list list))))
3103
3104 (run-hooks 'message-load-hook)
3105
3106 (provide 'message)
3107
3108 ;;; message.el ends here