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