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