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