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