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