* gnus-draft.el: Mark articles as replied.
[gnus] / lisp / message.el
1 ;;; message.el --- composing mail and news messages  -*- coding: iso-latin-1 -*-
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: mail, news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This mode provides mail-sending facilities from within Emacs.  It
28 ;; consists mainly of large chunks of code from the sendmail.el,
29 ;; gnus-msg.el and rnewspost.el files.
30
31 ;;; Code:
32
33 (eval-when-compile
34   (require 'cl)
35   (defvar gnus-list-identifiers))       ; gnus-sum is required where necessary
36 (require 'mailheader)
37 (require 'nnheader)
38 ;; This is apparently necessary even though things are autoloaded:
39 (if (featurep 'xemacs)
40     (require 'mail-abbrevs))
41 (require 'mail-parse)
42 (require 'mml)
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 'mail
49   :group 'news)
50
51 (put 'user-mail-address 'custom-type 'string)
52 (put 'user-full-name 'custom-type 'string)
53
54 (defgroup message-various nil
55   "Various Message Variables"
56   :link '(custom-manual "(message)Various Message Variables")
57   :group 'message)
58
59 (defgroup message-buffers nil
60   "Message Buffers"
61   :link '(custom-manual "(message)Message Buffers")
62   :group 'message)
63
64 (defgroup message-sending nil
65   "Message Sending"
66   :link '(custom-manual "(message)Sending Variables")
67   :group 'message)
68
69 (defgroup message-interface nil
70   "Message Interface"
71   :link '(custom-manual "(message)Interface")
72   :group 'message)
73
74 (defgroup message-forwarding nil
75   "Message Forwarding"
76   :link '(custom-manual "(message)Forwarding")
77   :group 'message-interface)
78
79 (defgroup message-insertion nil
80   "Message Insertion"
81   :link '(custom-manual "(message)Insertion")
82   :group 'message)
83
84 (defgroup message-headers nil
85   "Message Headers"
86   :link '(custom-manual "(message)Message Headers")
87   :group 'message)
88
89 (defgroup message-news nil
90   "Composing News Messages"
91   :group 'message)
92
93 (defgroup message-mail nil
94   "Composing Mail Messages"
95   :group 'message)
96
97 (defgroup message-faces nil
98   "Faces used for message composing."
99   :group 'message
100   :group 'faces)
101
102 (defcustom message-directory "~/Mail/"
103   "*Directory from which all other mail file variables are derived."
104   :group 'message-various
105   :type 'directory)
106
107 (defcustom message-max-buffers 10
108   "*How many buffers to keep before starting to kill them off."
109   :group 'message-buffers
110   :type 'integer)
111
112 (defcustom message-send-rename-function nil
113   "Function called to rename the buffer after sending it."
114   :group 'message-buffers
115   :type 'function)
116
117 (defcustom message-fcc-handler-function 'message-output
118   "*A function called to save outgoing articles.
119 This function will be called with the name of the file to store the
120 article in.  The default function is `message-output' which saves in Unix
121 mailbox format."
122   :type '(radio (function-item message-output)
123                 (function :tag "Other"))
124   :group 'message-sending)
125
126 (defcustom message-courtesy-message
127   "The following message is a courtesy copy of an article\nthat has been posted to %s as well.\n\n"
128   "*This is inserted at the start of a mailed copy of a posted message.
129 If the string contains the format spec \"%s\", the Newsgroups
130 the article has been posted to will be inserted there.
131 If this variable is nil, no such courtesy message will be added."
132   :group 'message-sending
133   :type 'string)
134
135 (defcustom message-ignored-bounced-headers "^\\(Received\\|Return-Path\\):"
136   "*Regexp that matches headers to be removed in resent bounced mail."
137   :group 'message-interface
138   :type 'regexp)
139
140 ;;;###autoload
141 (defcustom message-from-style 'default
142   "*Specifies how \"From\" headers look.
143
144 If `nil', they contain just the return address like:
145         king@grassland.com
146 If `parens', they look like:
147         king@grassland.com (Elvis Parsley)
148 If `angles', they look like:
149         Elvis Parsley <king@grassland.com>
150
151 Otherwise, most addresses look like `angles', but they look like
152 `parens' if `angles' would need quoting and `parens' would not."
153   :type '(choice (const :tag "simple" nil)
154                  (const parens)
155                  (const angles)
156                  (const default))
157   :group 'message-headers)
158
159 (defcustom message-syntax-checks nil
160   ;; Guess this one shouldn't be easy to customize...
161   "*Controls what syntax checks should not be performed on outgoing posts.
162 To disable checking of long signatures, for instance, add
163  `(signature . disabled)' to this list.
164
165 Don't touch this variable unless you really know what you're doing.
166
167 Checks include subject-cmsg multiple-headers sendsys message-id from
168 long-lines control-chars size new-text quoting-style
169 redirected-followup signature approved sender empty empty-headers
170 message-id from subject shorten-followup-to existing-newsgroups
171 buffer-file-name unchanged newsgroups."
172   :group 'message-news
173   :type '(repeat sexp))
174
175 (defcustom message-required-news-headers
176   '(From Newsgroups Subject Date Message-ID
177          (optional . Organization) Lines
178          (optional . User-Agent))
179   "*Headers to be generated or prompted for when posting an article.
180 RFC977 and RFC1036 require From, Date, Newsgroups, Subject,
181 Message-ID.  Organization, Lines, In-Reply-To, Expires, and
182 User-Agent are optional.  If don't you want message to insert some
183 header, remove it from this list."
184   :group 'message-news
185   :group 'message-headers
186   :type '(repeat sexp))
187
188 (defcustom message-required-mail-headers
189   '(From Subject Date (optional . In-Reply-To) Message-ID Lines
190          (optional . User-Agent))
191   "*Headers to be generated or prompted for when mailing a message.
192 RFC822 required that From, Date, To, Subject and Message-ID be
193 included.  Organization, Lines and User-Agent are optional."
194   :group 'message-mail
195   :group 'message-headers
196   :type '(repeat sexp))
197
198 (defcustom message-deletable-headers '(Message-ID Date Lines)
199   "Headers to be deleted if they already exist and were generated by message previously."
200   :group 'message-headers
201   :type 'sexp)
202
203 (defcustom message-ignored-news-headers
204   "^NNTP-Posting-Host:\\|^Xref:\\|^[BGF]cc:\\|^Resent-Fcc:\\|X-Draft-From:"
205   "*Regexp of headers to be removed unconditionally before posting."
206   :group 'message-news
207   :group 'message-headers
208   :type 'regexp)
209
210 (defcustom message-ignored-mail-headers "^[GF]cc:\\|^Resent-Fcc:\\|^Xref:"
211   "*Regexp of headers to be removed unconditionally before mailing."
212   :group 'message-mail
213   :group 'message-headers
214   :type 'regexp)
215
216 (defcustom message-ignored-supersedes-headers "^Path:\\|^Date\\|^NNTP-Posting-Host:\\|^Xref:\\|^Lines:\\|^Received:\\|^X-From-Line:\\|^X-Trace:\\|^X-Complaints-To:\\|Return-Path:\\|^Supersedes:\\|^NNTP-Posting-Date:\\|^X-Trace:\\|^X-Complaints-To:"
217   "*Header lines matching this regexp will be deleted before posting.
218 It's best to delete old Path and Date headers before posting to avoid
219 any confusion."
220   :group 'message-interface
221   :type 'regexp)
222
223 (defcustom message-subject-re-regexp "^[ \t]*\\([Rr][Ee]:[ \t]*\\)*[ \t]*"
224   "*Regexp matching \"Re: \" in the subject line."
225   :group 'message-various
226   :type 'regexp)
227
228 ;;;###autoload
229 (defcustom message-signature-separator "^-- *$"
230   "Regexp matching the signature separator."
231   :type 'regexp
232   :group 'message-various)
233
234 (defcustom message-elide-ellipsis "\n[...]\n\n"
235   "*The string which is inserted for elided text."
236   :type 'string
237   :group 'message-various)
238
239 (defcustom message-interactive nil
240   "Non-nil means when sending a message wait for and display errors.
241 nil means let mailer mail back a message to report errors."
242   :group 'message-sending
243   :group 'message-mail
244   :type 'boolean)
245
246 (defcustom message-generate-new-buffers 'unique
247   "*Non-nil means that a new message buffer will be created whenever `message-setup' is called.
248 If this is a function, call that function with three parameters:  The type,
249 the to address and the group name.  (Any of these may be nil.)  The function
250 should return the new buffer name."
251   :group 'message-buffers
252   :type '(choice (const :tag "off" nil)
253                  (const :tag "unique" unique)
254                  (const :tag "unsent" unsent)
255                  (function fun)))
256
257 (defcustom message-kill-buffer-on-exit nil
258   "*Non-nil means that the message buffer will be killed after sending a message."
259   :group 'message-buffers
260   :type 'boolean)
261
262 (eval-when-compile
263   (defvar gnus-local-organization))
264 (defcustom message-user-organization
265   (or (and (boundp 'gnus-local-organization)
266            (stringp gnus-local-organization)
267            gnus-local-organization)
268       (getenv "ORGANIZATION")
269       t)
270   "*String to be used as an Organization header.
271 If t, use `message-user-organization-file'."
272   :group 'message-headers
273   :type '(choice string
274                  (const :tag "consult file" t)))
275
276 ;;;###autoload
277 (defcustom message-user-organization-file "/usr/lib/news/organization"
278   "*Local news organization file."
279   :type 'file
280   :group 'message-headers)
281
282 (defcustom message-make-forward-subject-function
283   'message-forward-subject-author-subject
284   "*A list of functions that are called to generate a subject header for forwarded messages.
285 The subject generated by the previous function is passed into each
286 successive function.
287
288 The provided functions are:
289
290 * message-forward-subject-author-subject (Source of article (author or
291       newsgroup)), in brackets followed by the subject
292 * message-forward-subject-fwd (Subject of article with 'Fwd:' prepended
293       to it."
294   :group 'message-forwarding
295   :type '(radio (function-item message-forward-subject-author-subject)
296                 (function-item message-forward-subject-fwd)))
297
298 (defcustom message-forward-as-mime t
299   "*If non-nil, forward messages as an inline/rfc822 MIME section.  Otherwise, directly inline the old message in the forwarded message."
300   :version "21.1"
301   :group 'message-forwarding
302   :type 'boolean)
303
304 (defcustom message-forward-show-mml t
305   "*If non-nil, forward messages are shown as mml.  Otherwise, forward messages are unchanged."
306   :version "21.1"
307   :group 'message-forwarding
308   :type 'boolean)
309
310 (defcustom message-forward-before-signature t
311   "*If non-nil, put forwarded message before signature, else after."
312   :group 'message-forwarding
313   :type 'boolean)
314
315 (defcustom message-wash-forwarded-subjects nil
316   "*If non-nil, try to remove as much old cruft as possible from the subject of messages before generating the new subject of a forward."
317   :group 'message-forwarding
318   :type 'boolean)
319
320 (defcustom message-ignored-resent-headers "^Return-receipt\\|^X-Gnus\\|^Gnus-Warning:"
321   "*All headers that match this regexp will be deleted when resending a message."
322   :group 'message-interface
323   :type 'regexp)
324
325 (defcustom message-forward-ignored-headers "^Content-Transfer-Encoding:\\|^X-Gnus"
326   "*All headers that match this regexp will be deleted when forwarding a message."
327   :version "21.1"
328   :group 'message-forwarding
329   :type '(choice (const :tag "None" nil)
330                  regexp))
331
332 (defcustom message-ignored-cited-headers "."
333   "*Delete these headers from the messages you yank."
334   :group 'message-insertion
335   :type 'regexp)
336
337 (defcustom message-cite-prefix-regexp
338   ;; ?-, ?_ or ?. MUST NOT be in syntax entry w.
339   "\\([ \t]*\\(\\w\\|[-_.]\\)+>+\\|[ \t]*[]>»|:}+]\\)+"
340   "*Regexp matching the longest possible citation prefix on a line."
341   :group 'message-insertion
342   :type 'regexp)
343
344 (defcustom message-cancel-message "I am canceling my own article.\n"
345   "Message to be inserted in the cancel message."
346   :group 'message-interface
347   :type 'string)
348
349 ;; Useful to set in site-init.el
350 ;;;###autoload
351 (defcustom message-send-mail-function 'message-send-mail-with-sendmail
352   "Function to call to send the current buffer as mail.
353 The headers should be delimited by a line whose contents match the
354 variable `mail-header-separator'.
355
356 Valid values include `message-send-mail-with-sendmail' (the default),
357 `message-send-mail-with-mh', `message-send-mail-with-qmail' and
358 `smtpmail-send-it'."
359   :type '(radio (function-item message-send-mail-with-sendmail)
360                 (function-item message-send-mail-with-mh)
361                 (function-item message-send-mail-with-qmail)
362                 (function-item smtpmail-send-it)
363                 (function :tag "Other"))
364   :group 'message-sending
365   :group 'message-mail)
366
367 (defcustom message-send-news-function 'message-send-news
368   "Function to call to send the current buffer as news.
369 The headers should be delimited by a line whose contents match the
370 variable `mail-header-separator'."
371   :group 'message-sending
372   :group 'message-news
373   :type 'function)
374
375 (defcustom message-reply-to-function nil
376   "Function that should return a list of headers.
377 This function should pick out addresses from the To, Cc, and From headers
378 and respond with new To and Cc headers."
379   :group 'message-interface
380   :type 'function)
381
382 (defcustom message-wide-reply-to-function nil
383   "Function that should return a list of headers.
384 This function should pick out addresses from the To, Cc, and From headers
385 and respond with new To and Cc headers."
386   :group 'message-interface
387   :type 'function)
388
389 (defcustom message-followup-to-function nil
390   "Function that should return a list of headers.
391 This function should pick out addresses from the To, Cc, and From headers
392 and respond with new To and Cc headers."
393   :group 'message-interface
394   :type 'function)
395
396 (defcustom message-use-followup-to 'ask
397   "*Specifies what to do with Followup-To header.
398 If nil, always ignore the header.  If it is t, use its value, but
399 query before using the \"poster\" value.  If it is the symbol `ask',
400 always query the user whether to use the value.  If it is the symbol
401 `use', always use the value."
402   :group 'message-interface
403   :type '(choice (const :tag "ignore" nil)
404                  (const use)
405                  (const ask)))
406
407 (defcustom message-sendmail-f-is-evil nil
408   "*Non-nil means that \"-f username\" should not be added to the sendmail command line.
409 Doing so would be even more evil than leaving it out."
410   :group 'message-sending
411   :type 'boolean)
412
413 ;; qmail-related stuff
414 (defcustom message-qmail-inject-program "/var/qmail/bin/qmail-inject"
415   "Location of the qmail-inject program."
416   :group 'message-sending
417   :type 'file)
418
419 (defcustom message-qmail-inject-args nil
420   "Arguments passed to qmail-inject programs.
421 This should be a list of strings, one string for each argument.
422
423 For e.g., if you wish to set the envelope sender address so that bounces
424 go to the right place or to deal with listserv's usage of that address, you
425 might set this variable to '(\"-f\" \"you@some.where\")."
426   :group 'message-sending
427   :type '(repeat string))
428
429 (defvar message-cater-to-broken-inn t
430   "Non-nil means Gnus should not fold the `References' header.
431 Folding `References' makes ancient versions of INN create incorrect
432 NOV lines.")
433
434 (eval-when-compile
435   (defvar gnus-post-method)
436   (defvar gnus-select-method))
437 (defcustom message-post-method
438   (cond ((and (boundp 'gnus-post-method)
439               (listp gnus-post-method)
440               gnus-post-method)
441          gnus-post-method)
442         ((boundp 'gnus-select-method)
443          gnus-select-method)
444         (t '(nnspool "")))
445   "*Method used to post news.
446 Note that when posting from inside Gnus, for instance, this
447 variable isn't used."
448   :group 'message-news
449   :group 'message-sending
450   ;; This should be the `gnus-select-method' widget, but that might
451   ;; create a dependence to `gnus.el'.
452   :type 'sexp)
453
454 (defcustom message-generate-headers-first nil
455   "*If non-nil, generate all possible headers before composing."
456   :group 'message-headers
457   :type 'boolean)
458
459 (defcustom message-setup-hook nil
460   "Normal hook, run each time a new outgoing message is initialized.
461 The function `message-setup' runs this hook."
462   :group 'message-various
463   :type 'hook)
464
465 (defcustom message-cancel-hook nil
466   "Hook run when cancelling articles."
467   :group 'message-various
468   :type 'hook)
469
470 (defcustom message-signature-setup-hook nil
471   "Normal hook, run each time a new outgoing message is initialized.
472 It is run after the headers have been inserted and before
473 the signature is inserted."
474   :group 'message-various
475   :type 'hook)
476
477 (defcustom message-mode-hook nil
478   "Hook run in message mode buffers."
479   :group 'message-various
480   :type 'hook)
481
482 (defcustom message-header-hook nil
483   "Hook run in a message mode buffer narrowed to the headers."
484   :group 'message-various
485   :type 'hook)
486
487 (defcustom message-header-setup-hook nil
488   "Hook called narrowed to the headers when setting up a message buffer."
489   :group 'message-various
490   :type 'hook)
491
492 ;;;###autoload
493 (defcustom message-citation-line-function 'message-insert-citation-line
494   "*Function called to insert the \"Whomever writes:\" line."
495   :type 'function
496   :group 'message-insertion)
497
498 ;;;###autoload
499 (defcustom message-yank-prefix "> "
500   "*Prefix inserted on the lines of yanked messages.
501 Fix `message-cite-prefix-regexp' if it is set to an abnormal value."
502   :type 'string
503   :group 'message-insertion)
504
505 (defcustom message-indentation-spaces 3
506   "*Number of spaces to insert at the beginning of each cited line.
507 Used by `message-yank-original' via `message-yank-cite'."
508   :group 'message-insertion
509   :type 'integer)
510
511 ;;;###autoload
512 (defcustom message-cite-function 'message-cite-original
513   "*Function for citing an original message.
514 Predefined functions include `message-cite-original' and
515 `message-cite-original-without-signature'.
516 Note that `message-cite-original' uses `mail-citation-hook' if that is non-nil."
517   :type '(radio (function-item message-cite-original)
518                 (function-item message-cite-original-without-signature)
519                 (function-item sc-cite-original)
520                 (function :tag "Other"))
521   :group 'message-insertion)
522
523 ;;;###autoload
524 (defcustom message-indent-citation-function 'message-indent-citation
525   "*Function for modifying a citation just inserted in the mail buffer.
526 This can also be a list of functions.  Each function can find the
527 citation between (point) and (mark t).  And each function should leave
528 point and mark around the citation text as modified."
529   :type 'function
530   :group 'message-insertion)
531
532 (defvar message-abbrevs-loaded nil)
533
534 ;;;###autoload
535 (defcustom message-signature t
536   "*String to be inserted at the end of the message buffer.
537 If t, the `message-signature-file' file will be inserted instead.
538 If a function, the result from the function will be used instead.
539 If a form, the result from the form will be used instead."
540   :type 'sexp
541   :group 'message-insertion)
542
543 ;;;###autoload
544 (defcustom message-signature-file "~/.signature"
545   "*File containing the text inserted at end of message buffer."
546   :type 'file
547   :group 'message-insertion)
548
549 (defcustom message-distribution-function nil
550   "*Function called to return a Distribution header."
551   :group 'message-news
552   :group 'message-headers
553   :type 'function)
554
555 (defcustom message-expires 14
556   "Number of days before your article expires."
557   :group 'message-news
558   :group 'message-headers
559   :link '(custom-manual "(message)News Headers")
560   :type 'integer)
561
562 (defcustom message-user-path nil
563   "If nil, use the NNTP server name in the Path header.
564 If stringp, use this; if non-nil, use no host name (user name only)."
565   :group 'message-news
566   :group 'message-headers
567   :link '(custom-manual "(message)News Headers")
568   :type '(choice (const :tag "nntp" nil)
569                  (string :tag "name")
570                  (sexp :tag "none" :format "%t" t)))
571
572 (defvar message-reply-buffer nil)
573 (defvar message-reply-headers nil)
574 (defvar message-newsreader nil)
575 (defvar message-mailer nil)
576 (defvar message-sent-message-via nil)
577 (defvar message-checksum nil)
578 (defvar message-send-actions nil
579   "A list of actions to be performed upon successful sending of a message.")
580 (defvar message-exit-actions nil
581   "A list of actions to be performed upon exiting after sending a message.")
582 (defvar message-kill-actions nil
583   "A list of actions to be performed before killing a message buffer.")
584 (defvar message-postpone-actions nil
585   "A list of actions to be performed after postponing a message.")
586
587 (define-widget 'message-header-lines 'text
588   "All header lines must be LFD terminated."
589   :format "%{%t%}:%n%v"
590   :valid-regexp "^\\'"
591   :error "All header lines must be newline terminated")
592
593 (defcustom message-default-headers ""
594   "*A string containing header lines to be inserted in outgoing messages.
595 It is inserted before you edit the message, so you can edit or delete
596 these lines."
597   :group 'message-headers
598   :type 'message-header-lines)
599
600 (defcustom message-default-mail-headers ""
601   "*A string of header lines to be inserted in outgoing mails."
602   :group 'message-headers
603   :group 'message-mail
604   :type 'message-header-lines)
605
606 (defcustom message-default-news-headers ""
607   "*A string of header lines to be inserted in outgoing news articles."
608   :group 'message-headers
609   :group 'message-news
610   :type 'message-header-lines)
611
612 ;; Note: could use /usr/ucb/mail instead of sendmail;
613 ;; options -t, and -v if not interactive.
614 (defcustom message-mailer-swallows-blank-line
615   (if (and (string-match "sparc-sun-sunos\\(\\'\\|[^5]\\)"
616                          system-configuration)
617            (file-readable-p "/etc/sendmail.cf")
618            (let ((buffer (get-buffer-create " *temp*")))
619              (unwind-protect
620                  (save-excursion
621                    (set-buffer buffer)
622                    (insert-file-contents "/etc/sendmail.cf")
623                    (goto-char (point-min))
624                    (let ((case-fold-search nil))
625                      (re-search-forward "^OR\\>" nil t)))
626                (kill-buffer buffer))))
627       ;; According to RFC822, "The field-name must be composed of printable
628       ;; ASCII characters (i. e., characters that have decimal values between
629       ;; 33 and 126, except colon)", i. e., any chars except ctl chars,
630       ;; space, or colon.
631       '(looking-at "[ \t]\\|[][!\"#$%&'()*+,-./0-9;<=>?@A-Z\\\\^_`a-z{|}~]+:"))
632   "*Set this non-nil if the system's mailer runs the header and body together.
633 \(This problem exists on Sunos 4 when sendmail is run in remote mode.)
634 The value should be an expression to test whether the problem will
635 actually occur."
636   :group 'message-sending
637   :type 'sexp)
638
639 ;;;###autoload
640 (define-mail-user-agent 'message-user-agent
641   'message-mail 'message-send-and-exit
642   'message-kill-buffer 'message-send-hook)
643
644 (defvar message-mh-deletable-headers '(Message-ID Date Lines Sender)
645   "If non-nil, delete the deletable headers before feeding to mh.")
646
647 (defvar message-send-method-alist
648   '((news message-news-p message-send-via-news)
649     (mail message-mail-p message-send-via-mail))
650   "Alist of ways to send outgoing messages.
651 Each element has the form
652
653   \(TYPE PREDICATE FUNCTION)
654
655 where TYPE is a symbol that names the method; PREDICATE is a function
656 called without any parameters to determine whether the message is
657 a message of type TYPE; and FUNCTION is a function to be called if
658 PREDICATE returns non-nil.  FUNCTION is called with one parameter --
659 the prefix.")
660
661 (defcustom message-mail-alias-type 'abbrev
662   "*What alias expansion type to use in Message buffers.
663 The default is `abbrev', which uses mailabbrev.  nil switches
664 mail aliases off."
665   :group 'message
666   :link '(custom-manual "(message)Mail Aliases")
667   :type '(choice (const :tag "Use Mailabbrev" abbrev)
668                  (const :tag "No expansion" nil)))
669
670 (defcustom message-auto-save-directory
671   (file-name-as-directory (nnheader-concat message-directory "drafts"))
672   "*Directory where Message auto-saves buffers if Gnus isn't running.
673 If nil, Message won't auto-save."
674   :group 'message-buffers
675   :type 'directory)
676
677 (defcustom message-buffer-naming-style 'unique
678   "*The way new message buffers are named.
679 Valid valued are `unique' and `unsent'."
680   :version "21.1"
681   :group 'message-buffers
682   :type '(choice (const :tag "unique" unique)
683                  (const :tag "unsent" unsent)))
684
685 (defcustom message-default-charset 
686   (and (not (mm-multibyte-p)) 'iso-8859-1)
687   "Default charset used in non-MULE Emacsen.
688 If nil, you might be asked to input the charset."
689   :version "21.1"
690   :group 'message
691   :type 'symbol)
692
693 (defcustom message-dont-reply-to-names 
694   (and (boundp 'rmail-dont-reply-to-names) rmail-dont-reply-to-names)
695   "*A regexp specifying names to prune when doing wide replies.
696 A value of nil means exclude your own name only."
697   :version "21.1"
698   :group 'message
699   :type '(choice (const :tag "Yourself" nil)
700                  regexp))
701
702 (defvar message-shoot-gnksa-feet nil
703   "*A list of GNKSA feet you are allowed to shoot.  
704 Gnus gives you all the opportunity you could possibly want for
705 shooting yourself in the foot.  Also, Gnus allows you to shoot the
706 feet of Good Net-Keeping Seal of Approval. The following are foot
707 candidates:
708 `empty-article'     Allow you to post an empty article;
709 `quoted-text-only'  Allow you to post quoted text only;
710 `multiple-copies'   Allow you to post multiple copies.")
711
712 (defsubst message-gnksa-enable-p (feature)
713   (or (not (listp message-shoot-gnksa-feet))
714       (memq feature message-shoot-gnksa-feet)))
715
716 ;;; Internal variables.
717 ;;; Well, not really internal.
718
719 (defvar message-mode-syntax-table
720   (let ((table (copy-syntax-table text-mode-syntax-table)))
721     (modify-syntax-entry ?% ". " table)
722     (modify-syntax-entry ?> ". " table)
723     (modify-syntax-entry ?< ". " table)
724     table)
725   "Syntax table used while in Message mode.")
726
727 (defvar message-mode-abbrev-table text-mode-abbrev-table
728   "Abbrev table used in Message mode buffers.
729 Defaults to `text-mode-abbrev-table'.")
730
731 (defface message-header-to-face
732   '((((class color)
733       (background dark))
734      (:foreground "green2" :bold t))
735     (((class color)
736       (background light))
737      (:foreground "MidnightBlue" :bold t))
738     (t
739      (:bold t :italic t)))
740   "Face used for displaying From headers."
741   :group 'message-faces)
742
743 (defface message-header-cc-face
744   '((((class color)
745       (background dark))
746      (:foreground "green4" :bold t))
747     (((class color)
748       (background light))
749      (:foreground "MidnightBlue"))
750     (t
751      (:bold t)))
752   "Face used for displaying Cc headers."
753   :group 'message-faces)
754
755 (defface message-header-subject-face
756   '((((class color)
757       (background dark))
758      (:foreground "green3"))
759     (((class color)
760       (background light))
761      (:foreground "navy blue" :bold t))
762     (t
763      (:bold t)))
764   "Face used for displaying subject headers."
765   :group 'message-faces)
766
767 (defface message-header-newsgroups-face
768   '((((class color)
769       (background dark))
770      (:foreground "yellow" :bold t :italic t))
771     (((class color)
772       (background light))
773      (:foreground "blue4" :bold t :italic t))
774     (t
775      (:bold t :italic t)))
776   "Face used for displaying newsgroups headers."
777   :group 'message-faces)
778
779 (defface message-header-other-face
780   '((((class color)
781       (background dark))
782      (:foreground "#b00000"))
783     (((class color)
784       (background light))
785      (:foreground "steel blue"))
786     (t
787      (:bold t :italic t)))
788   "Face used for displaying newsgroups headers."
789   :group 'message-faces)
790
791 (defface message-header-name-face
792   '((((class color)
793       (background dark))
794      (:foreground "DarkGreen"))
795     (((class color)
796       (background light))
797      (:foreground "cornflower blue"))
798     (t
799      (:bold t)))
800   "Face used for displaying header names."
801   :group 'message-faces)
802
803 (defface message-header-xheader-face
804   '((((class color)
805       (background dark))
806      (:foreground "blue"))
807     (((class color)
808       (background light))
809      (:foreground "blue"))
810     (t
811      (:bold t)))
812   "Face used for displaying X-Header headers."
813   :group 'message-faces)
814
815 (defface message-separator-face
816   '((((class color)
817       (background dark))
818      (:foreground "blue3"))
819     (((class color)
820       (background light))
821      (:foreground "brown"))
822     (t
823      (:bold t)))
824   "Face used for displaying the separator."
825   :group 'message-faces)
826
827 (defface message-cited-text-face
828   '((((class color)
829       (background dark))
830      (:foreground "red"))
831     (((class color)
832       (background light))
833      (:foreground "red"))
834     (t
835      (:bold t)))
836   "Face used for displaying cited text names."
837   :group 'message-faces)
838
839 (defface message-mml-face
840   '((((class color)
841       (background dark))
842      (:foreground "ForestGreen"))
843     (((class color)
844       (background light))
845      (:foreground "ForestGreen"))
846     (t
847      (:bold t)))
848   "Face used for displaying MML."
849   :group 'message-faces)
850
851 (defvar message-font-lock-keywords
852   (let ((content "[ \t]*\\(.+\\(\n[ \t].*\\)*\\)\n?"))
853     `((,(concat "^\\([Tt]o:\\)" content)
854        (1 'message-header-name-face)
855        (2 'message-header-to-face nil t))
856       (,(concat "^\\(^[GBF]?[Cc][Cc]:\\|^[Rr]eply-[Tt]o:\\)" content)
857        (1 'message-header-name-face)
858        (2 'message-header-cc-face nil t))
859       (,(concat "^\\([Ss]ubject:\\)" content)
860        (1 'message-header-name-face)
861        (2 'message-header-subject-face nil t))
862       (,(concat "^\\([Nn]ewsgroups:\\|Followup-[Tt]o:\\)" content)
863        (1 'message-header-name-face)
864        (2 'message-header-newsgroups-face nil t))
865       (,(concat "^\\([A-Z][^: \n\t]+:\\)" content)
866        (1 'message-header-name-face)
867        (2 'message-header-other-face nil t))
868       (,(concat "^\\(X-[A-Za-z0-9-]+\\|In-Reply-To\\):" content)
869        (1 'message-header-name-face)
870        (2 'message-header-name-face))
871       ,@(if (and mail-header-separator
872                  (not (equal mail-header-separator "")))
873             `((,(concat "^\\(" (regexp-quote mail-header-separator) "\\)$")
874                1 'message-separator-face))
875           nil)
876       (,(concat "^\\(" message-cite-prefix-regexp "\\).*")
877        (0 'message-cited-text-face))
878       ("<#/?\\(multipart\\|part\\|external\\|mml\\).*>"
879        (0 'message-mml-face))))
880   "Additional expressions to highlight in Message mode.")
881
882 ;; XEmacs does it like this.  For Emacs, we have to set the
883 ;; `font-lock-defaults' buffer-local variable.
884 (put 'message-mode 'font-lock-defaults '(message-font-lock-keywords t))
885
886 (defvar message-face-alist
887   '((bold . bold-region)
888     (underline . underline-region)
889     (default . (lambda (b e)
890                  (unbold-region b e)
891                  (ununderline-region b e))))
892   "Alist of mail and news faces for facemenu.
893 The cdr of ech entry is a function for applying the face to a region.")
894
895 (defcustom message-send-hook nil
896   "Hook run before sending messages."
897   :group 'message-various
898   :options '(ispell-message)
899   :type 'hook)
900
901 (defcustom message-send-mail-hook nil
902   "Hook run before sending mail messages."
903   :group 'message-various
904   :type 'hook)
905
906 (defcustom message-send-news-hook nil
907   "Hook run before sending news messages."
908   :group 'message-various
909   :type 'hook)
910
911 (defcustom message-sent-hook nil
912   "Hook run after sending messages."
913   :group 'message-various
914   :type 'hook)
915
916 (defvar message-send-coding-system 'binary
917   "Coding system to encode outgoing mail.")
918
919 (defvar message-draft-coding-system
920   mm-auto-save-coding-system
921   "Coding system to compose mail.")
922
923 (defcustom message-send-mail-partially-limit 1000000
924   "The limitation of messages sent as message/partial.
925 The lower bound of message size in characters, beyond which the message 
926 should be sent in several parts. If it is nil, the size is unlimited."
927   :version "21.1"
928   :group 'message-buffers
929   :type '(choice (const :tag "unlimited" nil)
930                  (integer 1000000)))
931
932 (defcustom message-alternative-emails nil
933   "A regexp to match the alternative email addresses.
934 The first matched address (not primary one) is used in the From field."
935   :group 'message-headers
936   :type '(choice (const :tag "Always use primary" nil)
937                  regexp))
938
939 (defcustom message-mail-user-agent nil
940   "Like `mail-user-agent'.
941 Except if it is `nil', use Gnus native MUA; if it is t, use
942 `mail-user-agent'."
943   :type '(radio (const :tag "Gnus native"
944                        :format "%t\n"
945                        nil)
946                 (const :tag "`mail-user-agent'"
947                        :format "%t\n"
948                        t)
949                 (function-item :tag "Default Emacs mail"
950                                :format "%t\n"
951                                sendmail-user-agent)
952                 (function-item :tag "Emacs interface to MH"
953                                :format "%t\n"
954                                mh-e-user-agent)
955                 (function :tag "Other"))
956   :version "21.1"
957   :group 'message)
958
959 ;;; Internal variables.
960
961 (defvar message-sending-message "Sending...")
962 (defvar message-buffer-list nil)
963 (defvar message-this-is-news nil)
964 (defvar message-this-is-mail nil)
965 (defvar message-draft-article nil)
966 (defvar message-mime-part nil)
967 (defvar message-posting-charset nil)
968
969 ;; Byte-compiler warning
970 (eval-when-compile
971   (defvar gnus-active-hashtb)
972   (defvar gnus-read-active-file))
973
974 ;;; Regexp matching the delimiter of messages in UNIX mail format
975 ;;; (UNIX From lines), minus the initial ^.  It should be a copy
976 ;;; of rmail.el's rmail-unix-mail-delimiter.
977 (defvar message-unix-mail-delimiter
978   (let ((time-zone-regexp
979          (concat "\\([A-Z]?[A-Z]?[A-Z][A-Z]\\( DST\\)?"
980                  "\\|[-+]?[0-9][0-9][0-9][0-9]"
981                  "\\|"
982                  "\\) *")))
983     (concat
984      "From "
985
986      ;; Many things can happen to an RFC 822 mailbox before it is put into
987      ;; a `From' line.  The leading phrase can be stripped, e.g.
988      ;; `Joe <@w.x:joe@y.z>' -> `<@w.x:joe@y.z>'.  The <> can be stripped, e.g.
989      ;; `<@x.y:joe@y.z>' -> `@x.y:joe@y.z'.  Everything starting with a CRLF
990      ;; can be removed, e.g.
991      ;;         From: joe@y.z (Joe      K
992      ;;                 User)
993      ;; can yield `From joe@y.z (Joe    K Fri Mar 22 08:11:15 1996', and
994      ;;         From: Joe User
995      ;;                 <joe@y.z>
996      ;; can yield `From Joe User Fri Mar 22 08:11:15 1996'.
997      ;; The mailbox can be removed or be replaced by white space, e.g.
998      ;;         From: "Joe User"{space}{tab}
999      ;;                 <joe@y.z>
1000      ;; can yield `From {space}{tab} Fri Mar 22 08:11:15 1996',
1001      ;; where {space} and {tab} represent the Ascii space and tab characters.
1002      ;; We want to match the results of any of these manglings.
1003      ;; The following regexp rejects names whose first characters are
1004      ;; obviously bogus, but after that anything goes.
1005      "\\([^\0-\b\n-\r\^?].*\\)? "
1006
1007      ;; The time the message was sent.
1008      "\\([^\0-\r \^?]+\\) +"            ; day of the week
1009      "\\([^\0-\r \^?]+\\) +"            ; month
1010      "\\([0-3]?[0-9]\\) +"              ; day of month
1011      "\\([0-2][0-9]:[0-5][0-9]\\(:[0-6][0-9]\\)?\\) *" ; time of day
1012
1013      ;; Perhaps a time zone, specified by an abbreviation, or by a
1014      ;; numeric offset.
1015      time-zone-regexp
1016
1017      ;; The year.
1018      " \\([0-9][0-9]+\\) *"
1019
1020      ;; On some systems the time zone can appear after the year, too.
1021      time-zone-regexp
1022
1023      ;; Old uucp cruft.
1024      "\\(remote from .*\\)?"
1025
1026      "\n"))
1027   "Regexp matching the delimiter of messages in UNIX mail format.")
1028
1029 (defvar message-unsent-separator
1030   (concat "^ *---+ +Unsent message follows +---+ *$\\|"
1031           "^ *---+ +Returned message +---+ *$\\|"
1032           "^Start of returned message$\\|"
1033           "^ *---+ +Original message +---+ *$\\|"
1034           "^ *--+ +begin message +--+ *$\\|"
1035           "^ *---+ +Original message follows +---+ *$\\|"
1036           "^ *---+ +Undelivered message follows +---+ *$\\|"
1037           "^|? *---+ +Message text follows: +---+ *|?$")
1038   "A regexp that matches the separator before the text of a failed message.")
1039
1040 (defvar message-header-format-alist
1041   `((Newsgroups)
1042     (To . message-fill-address)
1043     (Cc . message-fill-address)
1044     (Subject)
1045     (In-Reply-To)
1046     (Fcc)
1047     (Bcc)
1048     (Date)
1049     (Organization)
1050     (Distribution)
1051     (Lines)
1052     (Expires)
1053     (Message-ID)
1054     (References . message-shorten-references)
1055     (User-Agent))
1056   "Alist used for formatting headers.")
1057
1058 (defvar message-options nil
1059   "Some saved answers when sending message.")
1060
1061 (eval-and-compile
1062   (autoload 'message-setup-toolbar "messagexmas")
1063   (autoload 'mh-new-draft-name "mh-comp")
1064   (autoload 'mh-send-letter "mh-comp")
1065   (autoload 'gnus-point-at-eol "gnus-util")
1066   (autoload 'gnus-point-at-bol "gnus-util")
1067   (autoload 'gnus-output-to-rmail "gnus-util")
1068   (autoload 'gnus-output-to-mail "gnus-util")
1069   (autoload 'mail-abbrev-in-expansion-header-p "mailabbrev")
1070   (autoload 'nndraft-request-associate-buffer "nndraft")
1071   (autoload 'nndraft-request-expire-articles "nndraft")
1072   (autoload 'gnus-open-server "gnus-int")
1073   (autoload 'gnus-request-post "gnus-int")
1074   (autoload 'gnus-alive-p "gnus-util")
1075   (autoload 'gnus-group-name-charset "gnus-group")
1076   (autoload 'rmail-output "rmail"))
1077
1078 \f
1079
1080 ;;;
1081 ;;; Utility functions.
1082 ;;;
1083
1084 (defmacro message-y-or-n-p (question show &rest text)
1085   "Ask QUESTION, displaying the rest of the arguments in a temp. buffer if SHOW"
1086   `(message-talkative-question 'y-or-n-p ,question ,show ,@text))
1087
1088 ;; Delete the current line (and the next N lines.);
1089 (defmacro message-delete-line (&optional n)
1090   `(delete-region (progn (beginning-of-line) (point))
1091                   (progn (forward-line ,(or n 1)) (point))))
1092
1093 (defun message-unquote-tokens (elems)
1094   "Remove double quotes (\") from strings in list."
1095   (mapcar (lambda (item)
1096             (while (string-match "^\\(.*\\)\"\\(.*\\)$" item)
1097               (setq item (concat (match-string 1 item) 
1098                                  (match-string 2 item))))
1099             item)
1100           elems))
1101
1102 (defun message-tokenize-header (header &optional separator)
1103   "Split HEADER into a list of header elements.
1104 SEPARATOR is a string of characters to be used as separators.  \",\"
1105 is used by default."
1106   (if (not header)
1107       nil
1108     (let ((regexp (format "[%s]+" (or separator ",")))
1109           (beg 1)
1110           (first t)
1111           quoted elems paren)
1112       (save-excursion
1113         (message-set-work-buffer)
1114         (insert header)
1115         (goto-char (point-min))
1116         (while (not (eobp))
1117           (if first
1118               (setq first nil)
1119             (forward-char 1))
1120           (cond ((and (> (point) beg)
1121                       (or (eobp)
1122                           (and (looking-at regexp)
1123                                (not quoted)
1124                                (not paren))))
1125                  (push (buffer-substring beg (point)) elems)
1126                  (setq beg (match-end 0)))
1127                 ((eq (char-after) ?\")
1128                  (setq quoted (not quoted)))
1129                 ((and (eq (char-after) ?\()
1130                       (not quoted))
1131                  (setq paren t))
1132                 ((and (eq (char-after) ?\))
1133                       (not quoted))
1134                  (setq paren nil))))
1135         (nreverse elems)))))
1136
1137 (defun message-mail-file-mbox-p (file)
1138   "Say whether FILE looks like a Unix mbox file."
1139   (when (and (file-exists-p file)
1140              (file-readable-p file)
1141              (file-regular-p file))
1142     (with-temp-buffer
1143       (nnheader-insert-file-contents file)
1144       (goto-char (point-min))
1145       (looking-at message-unix-mail-delimiter))))
1146
1147 (defun message-fetch-field (header &optional not-all)
1148   "The same as `mail-fetch-field', only remove all newlines."
1149   (let* ((inhibit-point-motion-hooks t)
1150          (case-fold-search t)
1151          (value (mail-fetch-field header nil (not not-all))))
1152     (when value
1153       (while (string-match "\n[\t ]+" value)
1154         (setq value (replace-match " " t t value)))
1155       (set-text-properties 0 (length value) nil value)
1156       value)))
1157
1158 (defun message-narrow-to-field ()
1159   "Narrow the buffer to the header on the current line."
1160   (beginning-of-line)
1161   (narrow-to-region
1162    (point)
1163    (progn
1164      (forward-line 1)
1165      (if (re-search-forward "^[^ \n\t]" nil t)
1166          (progn
1167            (beginning-of-line)
1168            (point))
1169        (point-max))))
1170   (goto-char (point-min)))
1171
1172 (defun message-add-header (&rest headers)
1173   "Add the HEADERS to the message header, skipping those already present."
1174   (while headers
1175     (let (hclean)
1176       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1177         (error "Invalid header `%s'" (car headers)))
1178       (setq hclean (match-string 1 (car headers)))
1179       (save-restriction
1180         (message-narrow-to-headers)
1181         (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1182           (insert (car headers) ?\n))))
1183     (setq headers (cdr headers))))
1184
1185
1186 (defun message-fetch-reply-field (header)
1187   "Fetch FIELD from the message we're replying to."
1188   (when (and message-reply-buffer
1189              (buffer-name message-reply-buffer))
1190     (save-excursion
1191       (set-buffer message-reply-buffer)
1192       (message-fetch-field header))))
1193
1194 (defun message-set-work-buffer ()
1195   (if (get-buffer " *message work*")
1196       (progn
1197         (set-buffer " *message work*")
1198         (erase-buffer))
1199     (set-buffer (get-buffer-create " *message work*"))
1200     (kill-all-local-variables)
1201     (mm-enable-multibyte)))
1202
1203 (defun message-functionp (form)
1204   "Return non-nil if FORM is funcallable."
1205   (or (and (symbolp form) (fboundp form))
1206       (and (listp form) (eq (car form) 'lambda))
1207       (byte-code-function-p form)))
1208
1209 (defun message-strip-list-identifiers (subject)
1210   "Remove list identifiers in `gnus-list-identifiers'."
1211   (require 'gnus-sum)                   ; for gnus-list-identifiers
1212   (let ((regexp (if (stringp gnus-list-identifiers)
1213                     gnus-list-identifiers
1214                   (mapconcat 'identity gnus-list-identifiers " *\\|"))))
1215     (if (string-match (concat "\\(\\(\\(Re: +\\)?\\(" regexp 
1216                                 " *\\)\\)+\\(Re: +\\)?\\)") subject)
1217         (concat (substring subject 0 (match-beginning 1))
1218                 (or (match-string 3 subject)
1219                     (match-string 5 subject))
1220                 (substring subject
1221                            (match-end 1)))
1222       subject)))
1223
1224 (defun message-strip-subject-re (subject)
1225   "Remove \"Re:\" from subject lines."
1226   (if (string-match message-subject-re-regexp subject)
1227       (substring subject (match-end 0))
1228     subject))
1229
1230 (defun message-remove-header (header &optional is-regexp first reverse)
1231   "Remove HEADER in the narrowed buffer.
1232 If REGEXP, HEADER is a regular expression.
1233 If FIRST, only remove the first instance of the header.
1234 Return the number of headers removed."
1235   (goto-char (point-min))
1236   (let ((regexp (if is-regexp header (concat "^" (regexp-quote header) ":")))
1237         (number 0)
1238         (case-fold-search t)
1239         last)
1240     (while (and (not (eobp))
1241                 (not last))
1242       (if (if reverse
1243               (not (looking-at regexp))
1244             (looking-at regexp))
1245           (progn
1246             (incf number)
1247             (when first
1248               (setq last t))
1249             (delete-region
1250              (point)
1251              ;; There might be a continuation header, so we have to search
1252              ;; until we find a new non-continuation line.
1253              (progn
1254                (forward-line 1)
1255                (if (re-search-forward "^[^ \t]" nil t)
1256                    (goto-char (match-beginning 0))
1257                  (point-max)))))
1258         (forward-line 1)
1259         (if (re-search-forward "^[^ \t]" nil t)
1260             (goto-char (match-beginning 0))
1261           (goto-char (point-max)))))
1262     number))
1263
1264 (defun message-remove-first-header (header)
1265   "Remove the first instance of HEADER if there is more than one."
1266   (let ((count 0)
1267         (regexp (concat "^" (regexp-quote header) ":")))
1268     (save-excursion
1269       (goto-char (point-min))
1270       (while (re-search-forward regexp nil t)
1271         (incf count)))
1272     (while (> count 1)
1273       (message-remove-header header nil t)
1274       (decf count))))
1275
1276 (defun message-narrow-to-headers ()
1277   "Narrow the buffer to the head of the message."
1278   (widen)
1279   (narrow-to-region
1280    (goto-char (point-min))
1281    (if (re-search-forward
1282         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1283        (match-beginning 0)
1284      (point-max)))
1285   (goto-char (point-min)))
1286
1287 (defun message-narrow-to-head-1 ()
1288   "Like `message-narrow-to-head'.  Don't widen."
1289   (narrow-to-region
1290    (goto-char (point-min))
1291    (if (search-forward "\n\n" nil 1)
1292        (1- (point))
1293      (point-max)))
1294   (goto-char (point-min)))
1295
1296 (defun message-narrow-to-head ()
1297   "Narrow the buffer to the head of the message.
1298 Point is left at the beginning of the narrowed-to region."
1299   (widen)
1300   (message-narrow-to-head-1))
1301
1302 (defun message-narrow-to-headers-or-head ()
1303   "Narrow the buffer to the head of the message."
1304   (widen)
1305   (narrow-to-region
1306    (goto-char (point-min))
1307    (cond
1308     ((re-search-forward
1309       (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1310      (match-beginning 0))
1311     ((search-forward "\n\n" nil t)
1312      (1- (point)))
1313     (t
1314      (point-max))))
1315   (goto-char (point-min)))
1316
1317 (defun message-news-p ()
1318   "Say whether the current buffer contains a news message."
1319   (and (not message-this-is-mail)
1320        (or message-this-is-news
1321            (save-excursion
1322              (save-restriction
1323                (message-narrow-to-headers)
1324                (and (message-fetch-field "newsgroups")
1325                     (not (message-fetch-field "posted-to"))))))))
1326
1327 (defun message-mail-p ()
1328   "Say whether the current buffer contains a mail message."
1329   (and (not message-this-is-news)
1330        (or message-this-is-mail
1331            (save-excursion
1332              (save-restriction
1333                (message-narrow-to-headers)
1334                (or (message-fetch-field "to")
1335                    (message-fetch-field "cc")
1336                    (message-fetch-field "bcc")))))))
1337
1338 (defun message-next-header ()
1339   "Go to the beginning of the next header."
1340   (beginning-of-line)
1341   (or (eobp) (forward-char 1))
1342   (not (if (re-search-forward "^[^ \t]" nil t)
1343            (beginning-of-line)
1344          (goto-char (point-max)))))
1345
1346 (defun message-sort-headers-1 ()
1347   "Sort the buffer as headers using `message-rank' text props."
1348   (goto-char (point-min))
1349   (require 'sort)
1350   (sort-subr
1351    nil 'message-next-header
1352    (lambda ()
1353      (message-next-header)
1354      (unless (bobp)
1355        (forward-char -1)))
1356    (lambda ()
1357      (or (get-text-property (point) 'message-rank)
1358          10000))))
1359
1360 (defun message-sort-headers ()
1361   "Sort the headers of the current message according to `message-header-format-alist'."
1362   (interactive)
1363   (save-excursion
1364     (save-restriction
1365       (let ((max (1+ (length message-header-format-alist)))
1366             rank)
1367         (message-narrow-to-headers)
1368         (while (re-search-forward "^[^ \n]+:" nil t)
1369           (put-text-property
1370            (match-beginning 0) (1+ (match-beginning 0))
1371            'message-rank
1372            (if (setq rank (length (memq (assq (intern (buffer-substring
1373                                                        (match-beginning 0)
1374                                                        (1- (match-end 0))))
1375                                               message-header-format-alist)
1376                                         message-header-format-alist)))
1377                (- max rank)
1378              (1+ max)))))
1379       (message-sort-headers-1))))
1380
1381 \f
1382
1383 ;;;
1384 ;;; Message mode
1385 ;;;
1386
1387 ;;; Set up keymap.
1388
1389 (defvar message-mode-map nil)
1390
1391 (unless message-mode-map
1392   (setq message-mode-map (make-keymap))
1393   (set-keymap-parent message-mode-map text-mode-map)
1394   (define-key message-mode-map "\C-c?" 'describe-mode)
1395
1396   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1397   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1398   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1399   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1400   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1401   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1402   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1403   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1404   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1405   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1406   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1407   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1408   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1409
1410   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1411   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1412
1413   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1414   (define-key message-mode-map "\C-c\M-\C-y" 'message-yank-buffer)
1415   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1416   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1417   (define-key message-mode-map "\C-c\M-h" 'message-insert-headers)
1418   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1419   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1420   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1421
1422   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1423   (define-key message-mode-map "\C-c\C-s" 'message-send)
1424   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1425   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1426
1427   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1428   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1429   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1430   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1431   (define-key message-mode-map "\M-q" 'message-fill-paragraph)
1432
1433   (define-key message-mode-map "\C-c\C-a" 'mml-attach-file)
1434
1435   (define-key message-mode-map "\t" 'message-tab)
1436   (define-key message-mode-map "\M-;" 'comment-region))
1437
1438 (easy-menu-define
1439  message-mode-menu message-mode-map "Message Menu."
1440  `("Message"
1441    ["Sort Headers" message-sort-headers t]
1442    ["Yank Original" message-yank-original t]
1443    ["Fill Yanked Message" message-fill-yanked-message t]
1444    ["Insert Signature" message-insert-signature t]
1445    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1446    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1447    ["Elide Region" message-elide-region (mark t)]
1448    ["Delete Outside Region" message-delete-not-region (mark t)]
1449    ["Kill To Signature" message-kill-to-signature t]
1450    ["Newline and Reformat" message-newline-and-reformat t]
1451    ["Rename buffer" message-rename-buffer t]
1452    ["Spellcheck" ispell-message
1453     ,@(if (featurep 'xemacs) nil
1454         '(:help "Spellcheck this message"))]
1455    ["Attach file as MIME" mml-attach-file
1456     ,@(if (featurep 'xemacs) nil
1457         '(:help "Attach a file at point"))]
1458    "----"
1459    ["Send Message" message-send-and-exit
1460     ,@(if (featurep 'xemacs) nil
1461         '(:help "Send this message"))]
1462    ["Abort Message" message-dont-send
1463     ,@(if (featurep 'xemacs) nil
1464         '(:help "File this draft message and exit"))]
1465    ["Kill Message" message-kill-buffer
1466     ,@(if (featurep 'xemacs) nil
1467         '(:help "Delete this message without sending"))]))
1468
1469 (easy-menu-define
1470  message-mode-field-menu message-mode-map ""
1471  '("Field"
1472    ["Fetch To" message-insert-to t]
1473    ["Fetch Newsgroups" message-insert-newsgroups t]
1474    "----"
1475    ["To" message-goto-to t]
1476    ["Subject" message-goto-subject t]
1477    ["Cc" message-goto-cc t]
1478    ["Reply-To" message-goto-reply-to t]
1479    ["Summary" message-goto-summary t]
1480    ["Keywords" message-goto-keywords t]
1481    ["Newsgroups" message-goto-newsgroups t]
1482    ["Followup-To" message-goto-followup-to t]
1483    ["Distribution" message-goto-distribution t]
1484    ["Body" message-goto-body t]
1485    ["Signature" message-goto-signature t]))
1486
1487 (defvar message-tool-bar-map nil)
1488
1489 (eval-when-compile
1490   (defvar facemenu-add-face-function)
1491   (defvar facemenu-remove-face-function))
1492
1493 ;;;###autoload
1494 (defun message-mode ()
1495   "Major mode for editing mail and news to be sent.
1496 Like Text Mode but with these additional commands:
1497 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1498 C-c C-d  Postpone sending the message        C-c C-k  Kill the message
1499 C-c C-f  move to a header field (and create it if there isn't):
1500          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1501          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1502          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1503          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1504          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1505          C-c C-f C-f  move to Followup-To
1506 C-c C-t  message-insert-to (add a To header to a news followup)
1507 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1508 C-c C-b  message-goto-body (move to beginning of message text).
1509 C-c C-i  message-goto-signature (move to the beginning of the signature).
1510 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1511 C-c C-y  message-yank-original (insert current message, if any).
1512 C-c C-q  message-fill-yanked-message (fill what was yanked).
1513 C-c C-e  message-elide-region (elide the text between point and mark).
1514 C-c C-v  message-delete-not-region (remove the text outside the region).
1515 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1516 C-c C-r  message-caesar-buffer-body (rot13 the message body).
1517 C-c C-a  mml-attach-file (attach a file as MIME).
1518 M-RET    message-newline-and-reformat (break the line and reformat)."
1519   (interactive)
1520   (if (local-variable-p 'mml-buffer-list (current-buffer))
1521       (mml-destroy-buffers))
1522   (kill-all-local-variables)
1523   (set (make-local-variable 'message-reply-buffer) nil)
1524   (make-local-variable 'message-send-actions)
1525   (make-local-variable 'message-exit-actions)
1526   (make-local-variable 'message-kill-actions)
1527   (make-local-variable 'message-postpone-actions)
1528   (make-local-variable 'message-draft-article)
1529   (make-local-hook 'kill-buffer-hook)
1530   (set-syntax-table message-mode-syntax-table)
1531   (use-local-map message-mode-map)
1532   (setq local-abbrev-table message-mode-abbrev-table)
1533   (setq major-mode 'message-mode)
1534   (setq mode-name "Message")
1535   (setq buffer-offer-save t)
1536   (make-local-variable 'facemenu-add-face-function)
1537   (make-local-variable 'facemenu-remove-face-function)
1538   (setq facemenu-add-face-function
1539         (lambda (face end)
1540           (let ((face-fun (cdr (assq face message-face-alist))))
1541             (if face-fun
1542                 (funcall face-fun (point) end)
1543               (error "Face %s not configured for %s mode" face mode-name)))
1544           "")
1545         facemenu-remove-face-function t)
1546   (make-local-variable 'message-reply-headers)
1547   (setq message-reply-headers nil)
1548   (make-local-variable 'message-newsreader)
1549   (make-local-variable 'message-mailer)
1550   (make-local-variable 'message-post-method)
1551   (set (make-local-variable 'message-sent-message-via) nil)
1552   (set (make-local-variable 'message-checksum) nil)
1553   (set (make-local-variable 'message-mime-part) 0)
1554   (message-setup-fill-variables)
1555   ;; Allow using comment commands to add/remove quoting.
1556   (set (make-local-variable 'comment-start) message-yank-prefix)
1557   (if (featurep 'xemacs)
1558       (message-setup-toolbar)
1559     (set (make-local-variable 'font-lock-defaults)
1560          '(message-font-lock-keywords t))
1561     (if (boundp 'tool-bar-map)
1562         (set (make-local-variable 'tool-bar-map) (message-tool-bar-map))))
1563   (easy-menu-add message-mode-menu message-mode-map)
1564   (easy-menu-add message-mode-field-menu message-mode-map)
1565   ;; Allow mail alias things.
1566   (when (eq message-mail-alias-type 'abbrev)
1567     (if (fboundp 'mail-abbrevs-setup)
1568         (mail-abbrevs-setup)
1569       (mail-aliases-setup)))
1570   (message-set-auto-save-file-name)
1571   (mm-enable-multibyte)
1572   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1573   (setq indent-tabs-mode nil)
1574   (mml-mode)
1575   (run-hooks 'text-mode-hook 'message-mode-hook))
1576
1577 (defun message-setup-fill-variables ()
1578   "Setup message fill variables."
1579   (make-local-variable 'paragraph-separate)
1580   (make-local-variable 'paragraph-start)
1581   (make-local-variable 'adaptive-fill-regexp)
1582   (unless (boundp 'adaptive-fill-first-line-regexp)
1583     (setq adaptive-fill-first-line-regexp nil))
1584   (make-local-variable 'adaptive-fill-first-line-regexp)
1585   (make-local-variable 'auto-fill-inhibit-regexp)
1586   (let ((quote-prefix-regexp
1587          ;; User should change message-cite-prefix-regexp if
1588          ;; message-yank-prefix is set to an abnormal value.
1589          (concat "\\(" message-cite-prefix-regexp "\\)[ \t]*")))      
1590     (setq paragraph-start
1591           (concat
1592            (regexp-quote mail-header-separator) "$\\|"
1593            "[ \t]*$\\|"                 ; blank lines
1594            "-- $\\|"                    ; signature delimiter
1595            "---+$\\|"                   ; delimiters for forwarded messages
1596            page-delimiter "$\\|"        ; spoiler warnings
1597            ".*wrote:$\\|"               ; attribution lines
1598            quote-prefix-regexp "$"))    ; empty lines in quoted text
1599     (setq paragraph-separate paragraph-start)
1600     (setq adaptive-fill-regexp
1601           (concat quote-prefix-regexp "\\|" adaptive-fill-regexp))
1602     (setq adaptive-fill-first-line-regexp
1603           (concat quote-prefix-regexp "\\|"
1604                   adaptive-fill-first-line-regexp))
1605     (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")))
1606
1607 \f
1608
1609 ;;;
1610 ;;; Message mode commands
1611 ;;;
1612
1613 ;;; Movement commands
1614
1615 (defun message-goto-to ()
1616   "Move point to the To header."
1617   (interactive)
1618   (message-position-on-field "To"))
1619
1620 (defun message-goto-subject ()
1621   "Move point to the Subject header."
1622   (interactive)
1623   (message-position-on-field "Subject"))
1624
1625 (defun message-goto-cc ()
1626   "Move point to the Cc header."
1627   (interactive)
1628   (message-position-on-field "Cc" "To"))
1629
1630 (defun message-goto-bcc ()
1631   "Move point to the Bcc  header."
1632   (interactive)
1633   (message-position-on-field "Bcc" "Cc" "To"))
1634
1635 (defun message-goto-fcc ()
1636   "Move point to the Fcc header."
1637   (interactive)
1638   (message-position-on-field "Fcc" "To" "Newsgroups"))
1639
1640 (defun message-goto-reply-to ()
1641   "Move point to the Reply-To header."
1642   (interactive)
1643   (message-position-on-field "Reply-To" "Subject"))
1644
1645 (defun message-goto-newsgroups ()
1646   "Move point to the Newsgroups header."
1647   (interactive)
1648   (message-position-on-field "Newsgroups"))
1649
1650 (defun message-goto-distribution ()
1651   "Move point to the Distribution header."
1652   (interactive)
1653   (message-position-on-field "Distribution"))
1654
1655 (defun message-goto-followup-to ()
1656   "Move point to the Followup-To header."
1657   (interactive)
1658   (message-position-on-field "Followup-To" "Newsgroups"))
1659
1660 (defun message-goto-keywords ()
1661   "Move point to the Keywords header."
1662   (interactive)
1663   (message-position-on-field "Keywords" "Subject"))
1664
1665 (defun message-goto-summary ()
1666   "Move point to the Summary header."
1667   (interactive)
1668   (message-position-on-field "Summary" "Subject"))
1669
1670 (defun message-goto-body (&optional interactivep)
1671   "Move point to the beginning of the message body."
1672   (interactive (list t))
1673   (when (and interactivep
1674              (looking-at "[ \t]*\n"))
1675     (expand-abbrev))
1676   (goto-char (point-min))
1677   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1678       (search-forward "\n\n" nil t)))
1679
1680 (defun message-goto-eoh ()
1681   "Move point to the end of the headers."
1682   (interactive)
1683   (message-goto-body)
1684   (forward-line -1))
1685
1686 (defun message-goto-signature ()
1687   "Move point to the beginning of the message signature.
1688 If there is no signature in the article, go to the end and
1689 return nil."
1690   (interactive)
1691   (goto-char (point-min))
1692   (if (re-search-forward message-signature-separator nil t)
1693       (forward-line 1)
1694     (goto-char (point-max))
1695     nil))
1696
1697 \f
1698
1699 (defun message-insert-to (&optional force)
1700   "Insert a To header that points to the author of the article being replied to.
1701 If the original author requested not to be sent mail, the function signals
1702 an error.
1703 With the prefix argument FORCE, insert the header anyway."
1704   (interactive "P")
1705   (let ((co (message-fetch-reply-field "mail-copies-to")))
1706     (when (and (null force)
1707                co
1708                (or (equal (downcase co) "never")
1709                    (equal (downcase co) "nobody")))
1710       (error "The user has requested not to have copies sent via mail")))
1711   (when (and (message-position-on-field "To")
1712              (mail-fetch-field "to")
1713              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1714     (insert ", "))
1715   (insert (or (message-fetch-reply-field "mail-reply-to")
1716               (message-fetch-reply-field "reply-to")
1717               (message-fetch-reply-field "from") "")))
1718
1719 (defun message-widen-reply ()
1720   "Widen the reply to include maximum recipients."
1721   (interactive)
1722   (let ((follow-to
1723          (and message-reply-buffer
1724               (buffer-name message-reply-buffer)
1725               (save-excursion
1726                 (set-buffer message-reply-buffer)
1727                 (message-get-reply-headers t)))))
1728     (save-excursion
1729       (save-restriction
1730         (message-narrow-to-headers)
1731         (dolist (elem follow-to)
1732           (message-remove-header (symbol-name (car elem)))
1733           (goto-char (point-min))
1734           (insert (symbol-name (car elem)) ": "
1735                   (cdr elem) "\n"))))))
1736
1737 (defun message-insert-newsgroups ()
1738   "Insert the Newsgroups header from the article being replied to."
1739   (interactive)
1740   (when (and (message-position-on-field "Newsgroups")
1741              (mail-fetch-field "newsgroups")
1742              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1743     (insert ","))
1744   (insert (or (message-fetch-reply-field "newsgroups") "")))
1745
1746 \f
1747
1748 ;;; Various commands
1749
1750 (defun message-delete-not-region (beg end)
1751   "Delete everything in the body of the current message that is outside of the region."
1752   (interactive "r")
1753   (save-excursion
1754     (goto-char end)
1755     (delete-region (point) (if (not (message-goto-signature))
1756                                (point)
1757                              (forward-line -2)
1758                              (point)))
1759     (insert "\n")
1760     (goto-char beg)
1761     (delete-region beg (progn (message-goto-body)
1762                               (forward-line 2)
1763                               (point))))
1764   (when (message-goto-signature)
1765     (forward-line -2)))
1766
1767 (defun message-kill-to-signature ()
1768   "Deletes all text up to the signature."
1769   (interactive)
1770   (let ((point (point)))
1771     (message-goto-signature)
1772     (unless (eobp)
1773       (forward-line -2))
1774     (kill-region point (point))
1775     (unless (bolp)
1776       (insert "\n"))))
1777
1778 (defun message-newline-and-reformat (&optional not-break)
1779   "Insert four newlines, and then reformat if inside quoted text."
1780   (interactive)
1781   (let (quoted point beg end leading-space)
1782     (setq point (point))
1783     (beginning-of-line)
1784     (setq beg (point))
1785     ;; Find first line of the paragraph.
1786     (if not-break
1787         (while (and (not (eobp)) 
1788                     (not (looking-at message-cite-prefix-regexp))
1789                 (looking-at paragraph-start))
1790           (forward-line 1)))
1791     ;; Find the prefix
1792     (when (looking-at message-cite-prefix-regexp)
1793       (setq quoted (match-string 0))
1794       (goto-char (match-end 0))
1795       (looking-at "[ \t]*")
1796       (setq leading-space (match-string 0)))
1797     (if (and quoted
1798              (not not-break)
1799              (< (- point beg) (length quoted)))
1800         ;; break in the cite prefix.
1801         (setq quoted nil
1802               end nil))
1803     (if quoted
1804         (progn
1805           (forward-line 1)
1806           (while (and (not (eobp))
1807                       (not (looking-at paragraph-separate))
1808                       (looking-at message-cite-prefix-regexp)
1809                       (equal quoted (match-string 0)))
1810             (goto-char (match-end 0))
1811             (looking-at "[ \t]*")
1812             (if (> (length leading-space) (length (match-string 0)))
1813                 (setq leading-space (match-string 0)))
1814             (forward-line 1))
1815           (setq end (point))
1816           (goto-char beg)
1817           (while (and (if (bobp) nil (forward-line -1) t)
1818                       (not (looking-at paragraph-start))
1819                       (looking-at message-cite-prefix-regexp)
1820                       (equal quoted (match-string 0)))
1821             (setq beg (point))
1822             (goto-char (match-end 0))
1823             (looking-at "[ \t]*")
1824             (if (> (length leading-space) (length (match-string 0)))
1825                 (setq leading-space (match-string 0)))))
1826       (while (and (not (eobp))
1827                   (not (looking-at paragraph-separate))
1828                   (not (looking-at message-cite-prefix-regexp)))
1829         (forward-line 1))
1830       (setq end (point))
1831       (goto-char beg)
1832       (while (and (if (bobp) nil (forward-line -1) t)
1833                   (not (looking-at paragraph-start))
1834                   (not (looking-at message-cite-prefix-regexp)))
1835         (setq beg (point))))
1836     (goto-char point)
1837     (save-restriction
1838       (narrow-to-region beg end)
1839       (if not-break
1840           (setq point nil)
1841         (insert "\n\n")
1842         (setq point (point))
1843         (insert "\n\n")
1844         (delete-region (point) (re-search-forward "[ \t]*"))
1845         (when quoted
1846           (insert quoted leading-space)))
1847       (if quoted
1848           (let* ((adaptive-fill-regexp 
1849                  (regexp-quote (concat quoted leading-space)))
1850                  (adaptive-fill-first-line-regexp 
1851                   adaptive-fill-regexp ))
1852             (fill-paragraph nil))
1853         (fill-paragraph nil))
1854       (if point (goto-char point)))))
1855
1856 (defun message-fill-paragraph ()
1857   "Like `fill-paragraph'."
1858   (interactive)
1859   (message-newline-and-reformat t))
1860
1861 (defun message-insert-signature (&optional force)
1862   "Insert a signature.  See documentation for the `message-signature' variable."
1863   (interactive (list 0))
1864   (let* ((signature
1865           (cond
1866            ((and (null message-signature)
1867                  (eq force 0))
1868             (save-excursion
1869               (goto-char (point-max))
1870               (not (re-search-backward message-signature-separator nil t))))
1871            ((and (null message-signature)
1872                  force)
1873             t)
1874            ((message-functionp message-signature)
1875             (funcall message-signature))
1876            ((listp message-signature)
1877             (eval message-signature))
1878            (t message-signature)))
1879          (signature
1880           (cond ((stringp signature)
1881                  signature)
1882                 ((and (eq t signature)
1883                       message-signature-file
1884                       (file-exists-p message-signature-file))
1885                  signature))))
1886     (when signature
1887       (goto-char (point-max))
1888       ;; Insert the signature.
1889       (unless (bolp)
1890         (insert "\n"))
1891       (insert "\n-- \n")
1892       (if (eq signature t)
1893           (insert-file-contents message-signature-file)
1894         (insert signature))
1895       (goto-char (point-max))
1896       (or (bolp) (insert "\n")))))
1897
1898 (defun message-elide-region (b e)
1899   "Elide the text between point and mark.
1900 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1901 text was killed."
1902   (interactive "r")
1903   (kill-region b e)
1904   (insert message-elide-ellipsis))
1905
1906 (defvar message-caesar-translation-table nil)
1907
1908 (defun message-caesar-region (b e &optional n)
1909   "Caesar rotation of region by N, default 13, for decrypting netnews."
1910   (interactive
1911    (list
1912     (min (point) (or (mark t) (point)))
1913     (max (point) (or (mark t) (point)))
1914     (when current-prefix-arg
1915       (prefix-numeric-value current-prefix-arg))))
1916
1917   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1918   (unless (or (zerop n)                 ; no action needed for a rot of 0
1919               (= b e))                  ; no region to rotate
1920     ;; We build the table, if necessary.
1921     (when (or (not message-caesar-translation-table)
1922               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1923       (setq message-caesar-translation-table
1924             (message-make-caesar-translation-table n)))
1925     (translate-region b e message-caesar-translation-table)))
1926
1927 (defun message-make-caesar-translation-table (n)
1928   "Create a rot table with offset N."
1929   (let ((i -1)
1930         (table (make-string 256 0)))
1931     (while (< (incf i) 256)
1932       (aset table i i))
1933     (concat
1934      (substring table 0 ?A)
1935      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1936      (substring table ?A (+ ?A n))
1937      (substring table (+ ?A 26) ?a)
1938      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1939      (substring table ?a (+ ?a n))
1940      (substring table (+ ?a 26) 255))))
1941
1942 (defun message-caesar-buffer-body (&optional rotnum)
1943   "Caesar rotates all letters in the current buffer by 13 places.
1944 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1945 With prefix arg, specifies the number of places to rotate each letter forward.
1946 Mail and USENET news headers are not rotated."
1947   (interactive (if current-prefix-arg
1948                    (list (prefix-numeric-value current-prefix-arg))
1949                  (list nil)))
1950   (save-excursion
1951     (save-restriction
1952       (when (message-goto-body)
1953         (narrow-to-region (point) (point-max)))
1954       (message-caesar-region (point-min) (point-max) rotnum))))
1955
1956 (defun message-pipe-buffer-body (program)
1957   "Pipe the message body in the current buffer through PROGRAM."
1958   (save-excursion
1959     (save-restriction
1960       (when (message-goto-body)
1961         (narrow-to-region (point) (point-max)))
1962       (shell-command-on-region
1963        (point-min) (point-max) program nil t))))
1964
1965 (defun message-rename-buffer (&optional enter-string)
1966   "Rename the *message* buffer to \"*message* RECIPIENT\".
1967 If the function is run with a prefix, it will ask for a new buffer
1968 name, rather than giving an automatic name."
1969   (interactive "Pbuffer name: ")
1970   (save-excursion
1971     (save-restriction
1972       (goto-char (point-min))
1973       (narrow-to-region (point)
1974                         (search-forward mail-header-separator nil 'end))
1975       (let* ((mail-to (or
1976                        (if (message-news-p) (message-fetch-field "Newsgroups")
1977                          (message-fetch-field "To"))
1978                        ""))
1979              (mail-trimmed-to
1980               (if (string-match "," mail-to)
1981                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1982                 mail-to))
1983              (name-default (concat "*message* " mail-trimmed-to))
1984              (name (if enter-string
1985                        (read-string "New buffer name: " name-default)
1986                      name-default)))
1987         (rename-buffer name t)))))
1988
1989 (defun message-fill-yanked-message (&optional justifyp)
1990   "Fill the paragraphs of a message yanked into this one.
1991 Numeric argument means justify as well."
1992   (interactive "P")
1993   (save-excursion
1994     (goto-char (point-min))
1995     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1996     (let ((fill-prefix message-yank-prefix))
1997       (fill-individual-paragraphs (point) (point-max) justifyp))))
1998
1999 (defun message-indent-citation ()
2000   "Modify text just inserted from a message to be cited.
2001 The inserted text should be the region.
2002 When this function returns, the region is again around the modified text.
2003
2004 Normally, indent each nonblank line `message-indentation-spaces' spaces.
2005 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
2006   (let ((start (point)))
2007     ;; Remove unwanted headers.
2008     (when message-ignored-cited-headers
2009       (let (all-removed)
2010         (save-restriction
2011           (narrow-to-region
2012            (goto-char start)
2013            (if (search-forward "\n\n" nil t)
2014                (1- (point))
2015              (point)))
2016           (message-remove-header message-ignored-cited-headers t)
2017           (when (= (point-min) (point-max))
2018             (setq all-removed t))
2019           (goto-char (point-max)))
2020         (if all-removed
2021             (goto-char start)
2022           (forward-line 1))))
2023     ;; Delete blank lines at the start of the buffer.
2024     (while (and (point-min)
2025                 (eolp)
2026                 (not (eobp)))
2027       (message-delete-line))
2028     ;; Delete blank lines at the end of the buffer.
2029     (goto-char (point-max))
2030     (unless (eolp)
2031       (insert "\n"))
2032     (while (and (zerop (forward-line -1))
2033                 (looking-at "$"))
2034       (message-delete-line))
2035     ;; Do the indentation.
2036     (if (null message-yank-prefix)
2037         (indent-rigidly start (mark t) message-indentation-spaces)
2038       (save-excursion
2039         (goto-char start)
2040         (while (< (point) (mark t))
2041           (insert message-yank-prefix)
2042           (forward-line 1))))
2043     (goto-char start)))
2044
2045 (defun message-yank-original (&optional arg)
2046   "Insert the message being replied to, if any.
2047 Puts point before the text and mark after.
2048 Normally indents each nonblank line ARG spaces (default 3).  However,
2049 if `message-yank-prefix' is non-nil, insert that prefix on each line.
2050
2051 This function uses `message-cite-function' to do the actual citing.
2052
2053 Just \\[universal-argument] as argument means don't indent, insert no
2054 prefix, and don't delete any headers."
2055   (interactive "P")
2056   (let ((modified (buffer-modified-p)))
2057     (when (and message-reply-buffer
2058                message-cite-function)
2059       (delete-windows-on message-reply-buffer t)
2060       (insert-buffer message-reply-buffer)
2061       (funcall message-cite-function)
2062       (message-exchange-point-and-mark)
2063       (unless (bolp)
2064         (insert ?\n))
2065       (unless modified
2066         (setq message-checksum (message-checksum))))))
2067
2068 (defun message-yank-buffer (buffer)
2069   "Insert BUFFER into the current buffer and quote it."
2070   (interactive "bYank buffer: ")
2071   (let ((message-reply-buffer buffer))
2072     (save-window-excursion
2073       (message-yank-original))))
2074
2075 (defun message-buffers ()
2076   "Return a list of active message buffers."
2077   (let (buffers)
2078     (save-excursion
2079       (dolist (buffer (buffer-list t))
2080         (set-buffer buffer)
2081         (when (and (eq major-mode 'message-mode)
2082                    (null message-sent-message-via))
2083           (push (buffer-name buffer) buffers))))
2084     (nreverse buffers)))
2085
2086 (defun message-cite-original-without-signature ()
2087   "Cite function in the standard Message manner."
2088   (let ((start (point))
2089         (end (mark t))
2090         (functions
2091          (when message-indent-citation-function
2092            (if (listp message-indent-citation-function)
2093                message-indent-citation-function
2094              (list message-indent-citation-function)))))
2095     (mml-quote-region start end)
2096     ;; Allow undoing.
2097     (undo-boundary)
2098     (goto-char end)
2099     (when (re-search-backward message-signature-separator start t)
2100       ;; Also peel off any blank lines before the signature.
2101       (forward-line -1)
2102       (while (looking-at "^[ \t]*$")
2103         (forward-line -1))
2104       (forward-line 1)
2105       (delete-region (point) end))
2106     (goto-char start)
2107     (while functions
2108       (funcall (pop functions)))
2109     (when message-citation-line-function
2110       (unless (bolp)
2111         (insert "\n"))
2112       (funcall message-citation-line-function))))
2113
2114 (eval-when-compile (defvar mail-citation-hook))         ;Compiler directive
2115 (defun message-cite-original ()
2116   "Cite function in the standard Message manner."
2117   (if (and (boundp 'mail-citation-hook)
2118            mail-citation-hook)
2119       (run-hooks 'mail-citation-hook)
2120     (let ((start (point))
2121           (end (mark t))
2122           (functions
2123            (when message-indent-citation-function
2124              (if (listp message-indent-citation-function)
2125                  message-indent-citation-function
2126                (list message-indent-citation-function)))))
2127       (mml-quote-region start end)
2128       (goto-char start)
2129       (while functions
2130         (funcall (pop functions)))
2131       (when message-citation-line-function
2132         (unless (bolp)
2133           (insert "\n"))
2134         (funcall message-citation-line-function)))))
2135
2136 (defun message-insert-citation-line ()
2137   "Function that inserts a simple citation line."
2138   (when message-reply-headers
2139     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
2140
2141 (defun message-position-on-field (header &rest afters)
2142   (let ((case-fold-search t))
2143     (save-restriction
2144       (narrow-to-region
2145        (goto-char (point-min))
2146        (progn
2147          (re-search-forward
2148           (concat "^" (regexp-quote mail-header-separator) "$"))
2149          (match-beginning 0)))
2150       (goto-char (point-min))
2151       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2152           (progn
2153             (re-search-forward "^[^ \t]" nil 'move)
2154             (beginning-of-line)
2155             (skip-chars-backward "\n")
2156             t)
2157         (while (and afters
2158                     (not (re-search-forward
2159                           (concat "^" (regexp-quote (car afters)) ":")
2160                           nil t)))
2161           (pop afters))
2162         (when afters
2163           (re-search-forward "^[^ \t]" nil 'move)
2164           (beginning-of-line))
2165         (insert header ": \n")
2166         (forward-char -1)
2167         nil))))
2168
2169 (defun message-remove-signature ()
2170   "Remove the signature from the text between point and mark.
2171 The text will also be indented the normal way."
2172   (save-excursion
2173     (let ((start (point))
2174           mark)
2175       (if (not (re-search-forward message-signature-separator (mark t) t))
2176           ;; No signature here, so we just indent the cited text.
2177           (message-indent-citation)
2178         ;; Find the last non-empty line.
2179         (forward-line -1)
2180         (while (looking-at "[ \t]*$")
2181           (forward-line -1))
2182         (forward-line 1)
2183         (setq mark (set-marker (make-marker) (point)))
2184         (goto-char start)
2185         (message-indent-citation)
2186         ;; Enable undoing the deletion.
2187         (undo-boundary)
2188         (delete-region mark (mark t))
2189         (set-marker mark nil)))))
2190
2191 \f
2192
2193 ;;;
2194 ;;; Sending messages
2195 ;;;
2196
2197 (defun message-send-and-exit (&optional arg)
2198   "Send message like `message-send', then, if no errors, exit from mail buffer."
2199   (interactive "P")
2200   (let ((buf (current-buffer))
2201         (actions message-exit-actions))
2202     (when (and (message-send arg)
2203                (buffer-name buf))
2204       (if message-kill-buffer-on-exit
2205           (kill-buffer buf)
2206         (bury-buffer buf)
2207         (when (eq buf (current-buffer))
2208           (message-bury buf)))
2209       (message-do-actions actions)
2210       t)))
2211
2212 (defun message-dont-send ()
2213   "Don't send the message you have been editing."
2214   (interactive)
2215   (set-buffer-modified-p t)
2216   (save-buffer)
2217   (let ((actions message-postpone-actions))
2218     (message-bury (current-buffer))
2219     (message-do-actions actions)))
2220
2221 (defun message-kill-buffer ()
2222   "Kill the current buffer."
2223   (interactive)
2224   (when (or (not (buffer-modified-p))
2225             (yes-or-no-p "Message modified; kill anyway? "))
2226     (let ((actions message-kill-actions))
2227       (setq buffer-file-name nil)
2228       (kill-buffer (current-buffer))
2229       (message-do-actions actions))))
2230
2231 (defun message-bury (buffer)
2232   "Bury this mail buffer."
2233   (let ((newbuf (other-buffer buffer)))
2234     (bury-buffer buffer)
2235     (if (and (fboundp 'frame-parameters)
2236              (cdr (assq 'dedicated (frame-parameters)))
2237              (not (null (delq (selected-frame) (visible-frame-list)))))
2238         (delete-frame (selected-frame))
2239       (switch-to-buffer newbuf))))
2240
2241 (defun message-send (&optional arg)
2242   "Send the message in the current buffer.
2243 If `message-interactive' is non-nil, wait for success indication or
2244 error messages, and inform user.
2245 Otherwise any failure is reported in a message back to the user from
2246 the mailer.
2247 The usage of ARG is defined by the instance that called Message.
2248 It should typically alter the sending method in some way or other."
2249   (interactive "P")
2250   ;; Make it possible to undo the coming changes.
2251   (undo-boundary)
2252   (let ((inhibit-read-only t))
2253     (put-text-property (point-min) (point-max) 'read-only nil))
2254   (message-fix-before-sending)
2255   (run-hooks 'message-send-hook)
2256   (message message-sending-message)
2257   (let ((alist message-send-method-alist)
2258         (success t)
2259         elem sent
2260         (message-options message-options))
2261     (message-options-set-recipient)
2262     (while (and success
2263                 (setq elem (pop alist)))
2264       (when (funcall (cadr elem))
2265         (when (and (or (not (memq (car elem)
2266                                   message-sent-message-via))
2267                        (if (or (message-gnksa-enable-p 'multiple-copies)
2268                                (not (eq (car elem) 'news)))
2269                            (y-or-n-p
2270                             (format
2271                              "Already sent message via %s; resend? "
2272                              (car elem)))
2273                          (error "Denied posting -- multiple copies.")))
2274                    (setq success (funcall (caddr elem) arg)))
2275           (setq sent t))))
2276     (unless (or sent (not success))
2277       (error "No methods specified to send by"))
2278     (when (and success sent)
2279       (message-do-fcc)
2280       (save-excursion
2281         (run-hooks 'message-sent-hook))
2282       (message "Sending...done")
2283       ;; Mark the buffer as unmodified and delete auto-save.
2284       (set-buffer-modified-p nil)
2285       (delete-auto-save-file-if-necessary t)
2286       (message-disassociate-draft)
2287       ;; Delete other mail buffers and stuff.
2288       (message-do-send-housekeeping)
2289       (message-do-actions message-send-actions)
2290       ;; Return success.
2291       t)))
2292
2293 (defun message-send-via-mail (arg)
2294   "Send the current message via mail."
2295   (message-send-mail arg))
2296
2297 (defun message-send-via-news (arg)
2298   "Send the current message via news."
2299   (funcall message-send-news-function arg))
2300
2301 (defmacro message-check (type &rest forms)
2302   "Eval FORMS if TYPE is to be checked."
2303   `(or (message-check-element ,type)
2304        (save-excursion
2305          ,@forms)))
2306
2307 (put 'message-check 'lisp-indent-function 1)
2308 (put 'message-check 'edebug-form-spec '(form body))
2309
2310 (defun message-fix-before-sending ()
2311   "Do various things to make the message nice before sending it."
2312   ;; Make sure there's a newline at the end of the message.
2313   (goto-char (point-max))
2314   (unless (bolp)
2315     (insert "\n"))
2316   ;; Delete all invisible text.
2317   (message-check 'invisible-text
2318     (when (text-property-any (point-min) (point-max) 'invisible t)
2319       (put-text-property (point-min) (point-max) 'invisible nil)
2320       (unless (yes-or-no-p
2321                "Invisible text found and made visible; continue posting? ")
2322         (error "Invisible text found and made visible")))))
2323
2324 (defun message-add-action (action &rest types)
2325   "Add ACTION to be performed when doing an exit of type TYPES."
2326   (let (var)
2327     (while types
2328       (set (setq var (intern (format "message-%s-actions" (pop types))))
2329            (nconc (symbol-value var) (list action))))))
2330
2331 (defun message-do-actions (actions)
2332   "Perform all actions in ACTIONS."
2333   ;; Now perform actions on successful sending.
2334   (while actions
2335     (ignore-errors
2336       (cond
2337        ;; A simple function.
2338        ((message-functionp (car actions))
2339         (funcall (car actions)))
2340        ;; Something to be evaled.
2341        (t
2342         (eval (car actions)))))
2343     (pop actions)))
2344
2345 (defun message-send-mail-partially ()
2346   "Sendmail as message/partial."
2347   ;; replace the header delimiter with a blank line
2348   (goto-char (point-min))
2349   (re-search-forward
2350    (concat "^" (regexp-quote mail-header-separator) "\n"))
2351   (replace-match "\n")
2352   (run-hooks 'message-send-mail-hook)
2353   (let ((p (goto-char (point-min)))
2354         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2355         (curbuf (current-buffer))
2356         (id (message-make-message-id)) (n 1)
2357         plist total  header required-mail-headers)
2358     (while (not (eobp))
2359       (if (< (point-max) (+ p message-send-mail-partially-limit))
2360           (goto-char (point-max))
2361         (goto-char (+ p message-send-mail-partially-limit))
2362         (beginning-of-line)
2363         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2364       (push p plist)
2365       (setq p (point)))
2366     (setq total (length plist))
2367     (push (point-max) plist)
2368     (setq plist (nreverse plist))
2369     (unwind-protect
2370         (save-excursion
2371           (setq p (pop plist))
2372           (while plist
2373             (set-buffer curbuf)
2374             (copy-to-buffer tembuf p (car plist))
2375             (set-buffer tembuf)
2376             (goto-char (point-min))
2377             (if header
2378                 (progn
2379                   (goto-char (point-min))
2380                   (narrow-to-region (point) (point))
2381                   (insert header))
2382               (message-goto-eoh)
2383               (setq header (buffer-substring (point-min) (point)))
2384               (goto-char (point-min))
2385               (narrow-to-region (point) (point))
2386               (insert header)
2387               (message-remove-header "Mime-Version")
2388               (message-remove-header "Content-Type")
2389               (message-remove-header "Content-Transfer-Encoding")
2390               (message-remove-header "Message-ID")
2391               (message-remove-header "Lines")
2392               (goto-char (point-max))
2393               (insert "Mime-Version: 1.0\n")
2394               (setq header (buffer-substring (point-min) (point-max))))
2395             (goto-char (point-max))
2396             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2397                             id n total))
2398             (let ((mail-header-separator ""))
2399               (when (memq 'Message-ID message-required-mail-headers)
2400                 (insert "Message-ID: " (message-make-message-id) "\n"))
2401               (when (memq 'Lines message-required-mail-headers)
2402                 (let ((mail-header-separator ""))
2403                   (insert "Lines: " (message-make-lines) "\n")))
2404               (message-goto-subject)
2405               (end-of-line)
2406               (insert (format " (%d/%d)" n total))
2407               (goto-char (point-max))
2408               (insert "\n")
2409               (widen)
2410               (mm-with-unibyte-current-buffer
2411                 (funcall message-send-mail-function)))
2412             (setq n (+ n 1))
2413             (setq p (pop plist))
2414             (erase-buffer)))
2415       (kill-buffer tembuf))))
2416
2417 (defun message-send-mail (&optional arg)
2418   (require 'mail-utils)
2419   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2420          (case-fold-search nil)
2421          (news (message-news-p))
2422          (mailbuf (current-buffer))
2423          (message-this-is-mail t)
2424          (message-posting-charset
2425           (if (fboundp 'gnus-setup-posting-charset)
2426               (gnus-setup-posting-charset nil)
2427             message-posting-charset)))
2428     (save-restriction
2429       (message-narrow-to-headers)
2430       ;; Insert some headers.
2431       (let ((message-deletable-headers
2432              (if news nil message-deletable-headers)))
2433         (message-generate-headers message-required-mail-headers))
2434       ;; Let the user do all of the above.
2435       (run-hooks 'message-header-hook))
2436     (unwind-protect
2437         (save-excursion
2438           (set-buffer tembuf)
2439           (erase-buffer)
2440           ;; Avoid copying text props.
2441           (insert (with-current-buffer mailbuf
2442                     (buffer-substring-no-properties (point-min) (point-max))))
2443           ;; Remove some headers.
2444           (message-encode-message-body)
2445           (save-restriction
2446             (message-narrow-to-headers)
2447             ;; We (re)generate the Lines header.
2448             (when (memq 'Lines message-required-mail-headers)
2449               (message-generate-headers '(Lines)))
2450             ;; Remove some headers.
2451             (message-remove-header message-ignored-mail-headers t)
2452             (let ((mail-parse-charset message-default-charset))
2453               (mail-encode-encoded-word-buffer)))
2454           (goto-char (point-max))
2455           ;; require one newline at the end.
2456           (or (= (preceding-char) ?\n)
2457               (insert ?\n))
2458           (when 
2459               (save-restriction
2460                 (message-narrow-to-headers)
2461                 (and news
2462                      (or (message-fetch-field "cc")
2463                          (message-fetch-field "to"))
2464                      (string= "text/plain"
2465                               (car
2466                                (mail-header-parse-content-type
2467                                 (message-fetch-field "content-type"))))))
2468             (message-insert-courtesy-copy))
2469           (if (or (not message-send-mail-partially-limit)
2470                   (< (point-max) message-send-mail-partially-limit)
2471                   (not (y-or-n-p "The message size is too large, should it be sent partially?")))
2472               (mm-with-unibyte-current-buffer
2473                 (funcall message-send-mail-function))
2474             (message-send-mail-partially)))
2475       (kill-buffer tembuf))
2476     (set-buffer mailbuf)
2477     (push 'mail message-sent-message-via)))
2478
2479 (defun message-send-mail-with-sendmail ()
2480   "Send off the prepared buffer with sendmail."
2481   (let ((errbuf (if message-interactive
2482                     (message-generate-new-buffer-clone-locals
2483                      " sendmail errors")
2484                   0))
2485         resend-to-addresses delimline)
2486     (let ((case-fold-search t))
2487       (save-restriction
2488         (message-narrow-to-headers)
2489         (setq resend-to-addresses (message-fetch-field "resent-to")))
2490       ;; Change header-delimiter to be what sendmail expects.
2491       (goto-char (point-min))
2492       (re-search-forward
2493        (concat "^" (regexp-quote mail-header-separator) "\n"))
2494       (replace-match "\n")
2495       (backward-char 1)
2496       (setq delimline (point-marker))
2497       (run-hooks 'message-send-mail-hook)
2498       ;; Insert an extra newline if we need it to work around
2499       ;; Sun's bug that swallows newlines.
2500       (goto-char (1+ delimline))
2501       (when (eval message-mailer-swallows-blank-line)
2502         (newline))
2503       (when message-interactive
2504         (save-excursion
2505           (set-buffer errbuf)
2506           (erase-buffer))))
2507     (let ((default-directory "/")
2508           (coding-system-for-write message-send-coding-system))
2509       (apply 'call-process-region
2510              (append (list (point-min) (point-max)
2511                            (if (boundp 'sendmail-program)
2512                                sendmail-program
2513                              "/usr/lib/sendmail")
2514                            nil errbuf nil "-oi")
2515                      ;; Always specify who from,
2516                      ;; since some systems have broken sendmails.
2517                      ;; But some systems are more broken with -f, so
2518                      ;; we'll let users override this.
2519                      (if (null message-sendmail-f-is-evil)
2520                          (list "-f" (message-make-address)))
2521                      ;; These mean "report errors by mail"
2522                      ;; and "deliver in background".
2523                      (if (null message-interactive) '("-oem" "-odb"))
2524                      ;; Get the addresses from the message
2525                      ;; unless this is a resend.
2526                      ;; We must not do that for a resend
2527                      ;; because we would find the original addresses.
2528                      ;; For a resend, include the specific addresses.
2529                      (if resend-to-addresses
2530                          (list resend-to-addresses)
2531                        '("-t")))))
2532     (when message-interactive
2533       (save-excursion
2534         (set-buffer errbuf)
2535         (goto-char (point-min))
2536         (while (re-search-forward "\n\n* *" nil t)
2537           (replace-match "; "))
2538         (if (not (zerop (buffer-size)))
2539             (error "Sending...failed to %s"
2540                    (buffer-substring (point-min) (point-max)))))
2541       (when (bufferp errbuf)
2542         (kill-buffer errbuf)))))
2543
2544 (defun message-send-mail-with-qmail ()
2545   "Pass the prepared message buffer to qmail-inject.
2546 Refer to the documentation for the variable `message-send-mail-function'
2547 to find out how to use this."
2548   ;; replace the header delimiter with a blank line
2549   (goto-char (point-min))
2550   (re-search-forward
2551    (concat "^" (regexp-quote mail-header-separator) "\n"))
2552   (replace-match "\n")
2553   (run-hooks 'message-send-mail-hook)
2554   ;; send the message
2555   (case
2556       (let ((coding-system-for-write message-send-coding-system))
2557         (apply
2558          'call-process-region 1 (point-max) message-qmail-inject-program
2559          nil nil nil
2560          ;; qmail-inject's default behaviour is to look for addresses on the
2561          ;; command line; if there're none, it scans the headers.
2562          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2563          ;;
2564          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2565          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2566          ;; message from stdin.
2567          ;;
2568          ;; qmail also has the advantage of not having been raped by
2569          ;; various vendors, so we don't have to allow for that, either --
2570          ;; compare this with message-send-mail-with-sendmail and weep
2571          ;; for sendmail's lost innocence.
2572          ;;
2573          ;; all this is way cool coz it lets us keep the arguments entirely
2574          ;; free for -inject-arguments -- a big win for the user and for us
2575          ;; since we don't have to play that double-guessing game and the user
2576          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2577          message-qmail-inject-args))
2578     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2579     ;; we have to look at the retval instead
2580     (0 nil)
2581     (1   (error "qmail-inject reported permanent failure"))
2582     (111 (error "qmail-inject reported transient failure"))
2583     ;; should never happen
2584     (t   (error "qmail-inject reported unknown failure"))))
2585
2586 (defun message-send-mail-with-mh ()
2587   "Send the prepared message buffer with mh."
2588   (let ((mh-previous-window-config nil)
2589         (name (mh-new-draft-name)))
2590     (setq buffer-file-name name)
2591     ;; MH wants to generate these headers itself.
2592     (when message-mh-deletable-headers
2593       (let ((headers message-mh-deletable-headers))
2594         (while headers
2595           (goto-char (point-min))
2596           (and (re-search-forward
2597                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2598                (message-delete-line))
2599           (pop headers))))
2600     (run-hooks 'message-send-mail-hook)
2601     ;; Pass it on to mh.
2602     (mh-send-letter)))
2603
2604 (defun message-send-news (&optional arg)
2605   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2606          (case-fold-search nil)
2607          (method (if (message-functionp message-post-method)
2608                      (funcall message-post-method arg)
2609                    message-post-method))
2610          (group-name-charset (gnus-group-name-charset method ""))
2611          (rfc2047-header-encoding-alist
2612           (if group-name-charset
2613               (cons (cons "Newsgroups" group-name-charset)
2614                     rfc2047-header-encoding-alist)
2615             rfc2047-header-encoding-alist))
2616          (messbuf (current-buffer))
2617          (message-syntax-checks
2618           (if arg
2619               (cons '(existing-newsgroups . disabled)
2620                     message-syntax-checks)
2621             message-syntax-checks))
2622          (message-this-is-news t)
2623          (message-posting-charset (gnus-setup-posting-charset 
2624                                    (save-restriction
2625                                      (message-narrow-to-headers-or-head)
2626                                      (message-fetch-field "Newsgroups"))))
2627          result)
2628     (if (not (message-check-news-body-syntax))
2629         nil
2630       (save-restriction
2631         (message-narrow-to-headers)
2632         ;; Insert some headers.
2633         (message-generate-headers message-required-news-headers)
2634         ;; Let the user do all of the above.
2635         (run-hooks 'message-header-hook))
2636       (if group-name-charset
2637           (setq message-syntax-checks
2638               (cons '(valid-newsgroups . disabled)
2639                     message-syntax-checks)))
2640       (message-cleanup-headers)
2641       (if (not (message-check-news-syntax))
2642           nil
2643         (unwind-protect
2644             (save-excursion
2645               (set-buffer tembuf)
2646               (buffer-disable-undo)
2647               (erase-buffer)
2648               ;; Avoid copying text props.
2649               (insert (with-current-buffer messbuf
2650                         (buffer-substring-no-properties 
2651                          (point-min) (point-max))))
2652               (message-encode-message-body)
2653               ;; Remove some headers.
2654               (save-restriction
2655                 (message-narrow-to-headers)
2656                 ;; We (re)generate the Lines header.
2657                 (when (memq 'Lines message-required-mail-headers)
2658                   (message-generate-headers '(Lines)))
2659                 ;; Remove some headers.
2660                 (message-remove-header message-ignored-news-headers t)
2661                 (let ((mail-parse-charset message-default-charset))
2662                   (mail-encode-encoded-word-buffer)))
2663               (goto-char (point-max))
2664               ;; require one newline at the end.
2665               (or (= (preceding-char) ?\n)
2666                   (insert ?\n))
2667               (let ((case-fold-search t))
2668                 ;; Remove the delimiter.
2669                 (goto-char (point-min))
2670                 (re-search-forward
2671                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2672                 (replace-match "\n")
2673                 (backward-char 1))
2674               (run-hooks 'message-send-news-hook)
2675               (gnus-open-server method)
2676               (setq result (let ((mail-header-separator ""))
2677                              (gnus-request-post method))))
2678           (kill-buffer tembuf))
2679         (set-buffer messbuf)
2680         (if result
2681             (push 'news message-sent-message-via)
2682           (message "Couldn't send message via news: %s"
2683                    (nnheader-get-report (car method)))
2684           nil)))))
2685
2686 ;;;
2687 ;;; Header generation & syntax checking.
2688 ;;;
2689
2690 (defun message-check-element (type)
2691   "Returns non-nil if this type is not to be checked."
2692   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2693       t
2694     (let ((able (assq type message-syntax-checks)))
2695       (and (consp able)
2696            (eq (cdr able) 'disabled)))))
2697
2698 (defun message-check-news-syntax ()
2699   "Check the syntax of the message."
2700   (save-excursion
2701     (save-restriction
2702       (widen)
2703       ;; We narrow to the headers and check them first.
2704       (save-excursion
2705         (save-restriction
2706           (message-narrow-to-headers)
2707           (message-check-news-header-syntax))))))
2708
2709 (defun message-check-news-header-syntax ()
2710   (and
2711    ;; Check Newsgroups header.
2712    (message-check 'newsgroups
2713      (let ((group (message-fetch-field "newsgroups")))
2714        (or
2715         (and group
2716              (not (string-match "\\`[ \t]*\\'" group)))
2717         (ignore
2718          (message
2719           "The newsgroups field is empty or missing.  Posting is denied.")))))
2720    ;; Check the Subject header.
2721    (message-check 'subject
2722      (let* ((case-fold-search t)
2723             (subject (message-fetch-field "subject")))
2724        (or
2725         (and subject
2726              (not (string-match "\\`[ \t]*\\'" subject)))
2727         (ignore
2728          (message
2729           "The subject field is empty or missing.  Posting is denied.")))))
2730    ;; Check for commands in Subject.
2731    (message-check 'subject-cmsg
2732      (if (string-match "^cmsg " (message-fetch-field "subject"))
2733          (y-or-n-p
2734           "The control code \"cmsg\" is in the subject.  Really post? ")
2735        t))
2736    ;; Check for multiple identical headers.
2737    (message-check 'multiple-headers
2738      (let (found)
2739        (while (and (not found)
2740                    (re-search-forward "^[^ \t:]+: " nil t))
2741          (save-excursion
2742            (or (re-search-forward
2743                 (concat "^"
2744                         (regexp-quote
2745                          (setq found
2746                                (buffer-substring
2747                                 (match-beginning 0) (- (match-end 0) 2))))
2748                         ":")
2749                 nil t)
2750                (setq found nil))))
2751        (if found
2752            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2753          t)))
2754    ;; Check for Version and Sendsys.
2755    (message-check 'sendsys
2756      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2757          (y-or-n-p
2758           (format "The article contains a %s command.  Really post? "
2759                   (buffer-substring (match-beginning 0)
2760                                     (1- (match-end 0)))))
2761        t))
2762    ;; See whether we can shorten Followup-To.
2763    (message-check 'shorten-followup-to
2764      (let ((newsgroups (message-fetch-field "newsgroups"))
2765            (followup-to (message-fetch-field "followup-to"))
2766            to)
2767        (when (and newsgroups
2768                   (string-match "," newsgroups)
2769                   (not followup-to)
2770                   (not
2771                    (zerop
2772                     (length
2773                      (setq to (completing-read
2774                                "Followups to: (default all groups) "
2775                                (mapcar (lambda (g) (list g))
2776                                        (cons "poster"
2777                                              (message-tokenize-header
2778                                               newsgroups)))))))))
2779          (goto-char (point-min))
2780          (insert "Followup-To: " to "\n"))
2781        t))
2782    ;; Check "Shoot me".
2783    (message-check 'shoot
2784      (if (re-search-forward
2785           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2786          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2787        t))
2788    ;; Check for Approved.
2789    (message-check 'approved
2790      (if (re-search-forward "^Approved:" nil t)
2791          (y-or-n-p "The article contains an Approved header.  Really post? ")
2792        t))
2793    ;; Check the Message-ID header.
2794    (message-check 'message-id
2795      (let* ((case-fold-search t)
2796             (message-id (message-fetch-field "message-id" t)))
2797        (or (not message-id)
2798            ;; Is there an @ in the ID?
2799            (and (string-match "@" message-id)
2800                 ;; Is there a dot in the ID?
2801                 (string-match "@[^.]*\\." message-id)
2802                 ;; Does the ID end with a dot?
2803                 (not (string-match "\\.>" message-id)))
2804            (y-or-n-p
2805             (format "The Message-ID looks strange: \"%s\".  Really post? "
2806                     message-id)))))
2807    ;; Check the Newsgroups & Followup-To headers.
2808    (message-check 'existing-newsgroups
2809      (let* ((case-fold-search t)
2810             (newsgroups (message-fetch-field "newsgroups"))
2811             (followup-to (message-fetch-field "followup-to"))
2812             (groups (message-tokenize-header
2813                      (if followup-to
2814                          (concat newsgroups "," followup-to)
2815                        newsgroups)))
2816             (hashtb (and (boundp 'gnus-active-hashtb)
2817                          gnus-active-hashtb))
2818             errors)
2819        (if (or (not hashtb)
2820                (not (boundp 'gnus-read-active-file))
2821                (not gnus-read-active-file)
2822                (eq gnus-read-active-file 'some))
2823            t
2824          (while groups
2825            (when (and (not (boundp (intern (car groups) hashtb)))
2826                       (not (equal (car groups) "poster")))
2827              (push (car groups) errors))
2828            (pop groups))
2829          (if (not errors)
2830              t
2831            (y-or-n-p
2832             (format
2833              "Really post to %s unknown group%s: %s "
2834              (if (= (length errors) 1) "this" "these")
2835              (if (= (length errors) 1) "" "s")
2836              (mapconcat 'identity errors ", ")))))))
2837    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2838    (message-check 'valid-newsgroups
2839      (let ((case-fold-search t)
2840            (headers '("Newsgroups" "Followup-To"))
2841            header error)
2842        (while (and headers (not error))
2843          (when (setq header (mail-fetch-field (car headers)))
2844            (if (or
2845                 (not
2846                  (string-match
2847                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2848                   header))
2849                 (memq
2850                  nil (mapcar
2851                       (lambda (g)
2852                         (not (string-match "\\.\\'\\|\\.\\." g)))
2853                       (message-tokenize-header header ","))))
2854                (setq error t)))
2855          (unless error
2856            (pop headers)))
2857        (if (not error)
2858            t
2859          (y-or-n-p
2860           (format "The %s header looks odd: \"%s\".  Really post? "
2861                   (car headers) header)))))
2862    (message-check 'repeated-newsgroups
2863      (let ((case-fold-search t)
2864            (headers '("Newsgroups" "Followup-To"))
2865            header error groups group)
2866        (while (and headers
2867                    (not error))
2868          (when (setq header (mail-fetch-field (pop headers)))
2869            (setq groups (message-tokenize-header header ","))
2870            (while (setq group (pop groups))
2871              (when (member group groups)
2872                (setq error group
2873                      groups nil)))))
2874        (if (not error)
2875            t
2876          (y-or-n-p
2877           (format "Group %s is repeated in headers.  Really post? " error)))))
2878    ;; Check the From header.
2879    (message-check 'from
2880      (let* ((case-fold-search t)
2881             (from (message-fetch-field "from"))
2882             ad)
2883        (cond
2884         ((not from)
2885          (message "There is no From line.  Posting is denied.")
2886          nil)
2887         ((or (not (string-match
2888                    "@[^\\.]*\\."
2889                    (setq ad (nth 1 (mail-extract-address-components
2890                                     from))))) ;larsi@ifi
2891              (string-match "\\.\\." ad) ;larsi@ifi..uio
2892              (string-match "@\\." ad)   ;larsi@.ifi.uio
2893              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2894              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2895              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2896          (message
2897           "Denied posting -- the From looks strange: \"%s\"." from)
2898          nil)
2899         (t t))))))
2900
2901 (defun message-check-news-body-syntax ()
2902   (and
2903    ;; Check for long lines.
2904    (message-check 'long-lines
2905      (goto-char (point-min))
2906      (re-search-forward
2907       (concat "^" (regexp-quote mail-header-separator) "$"))
2908      (while (and
2909              (progn
2910                (end-of-line)
2911                (< (current-column) 80))
2912              (zerop (forward-line 1))))
2913      (or (bolp)
2914          (eobp)
2915          (y-or-n-p
2916           "You have lines longer than 79 characters.  Really post? ")))
2917    ;; Check whether the article is empty.
2918    (message-check 'empty
2919      (goto-char (point-min))
2920      (re-search-forward
2921       (concat "^" (regexp-quote mail-header-separator) "$"))
2922      (forward-line 1)
2923      (let ((b (point)))
2924        (goto-char (point-max))
2925        (re-search-backward message-signature-separator nil t)
2926        (beginning-of-line)
2927        (or (re-search-backward "[^ \n\t]" b t)
2928            (if (message-gnksa-enable-p 'empty-article)
2929                (y-or-n-p "Empty article.  Really post? ")
2930              (message "Denied posting -- Empty article.")
2931              nil))))
2932    ;; Check for control characters.
2933    (message-check 'control-chars
2934      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2935          (y-or-n-p
2936           "The article contains control characters.  Really post? ")
2937        t))
2938    ;; Check excessive size.
2939    (message-check 'size
2940      (if (> (buffer-size) 60000)
2941          (y-or-n-p
2942           (format "The article is %d octets long.  Really post? "
2943                   (buffer-size)))
2944        t))
2945    ;; Check whether any new text has been added.
2946    (message-check 'new-text
2947      (or
2948       (not message-checksum)
2949       (not (eq (message-checksum) message-checksum))
2950       (if (message-gnksa-enable-p 'quoted-text-only)
2951           (y-or-n-p
2952            "It looks like no new text has been added.  Really post? ")
2953         (message "Denied posting -- no new text has been added.")
2954         nil)))
2955    ;; Check the length of the signature.
2956    (message-check 'signature
2957      (goto-char (point-max))
2958      (if (> (count-lines (point) (point-max)) 5)
2959          (y-or-n-p
2960           (format
2961            "Your .sig is %d lines; it should be max 4.  Really post? "
2962            (1- (count-lines (point) (point-max)))))
2963        t))
2964    ;; Ensure that text follows last quoted portion.
2965    (message-check 'quoting-style
2966      (goto-char (point-max))
2967      (let ((no-problem t))
2968        (when (search-backward-regexp "^>[^\n]*\n" nil t)
2969          (setq no-problem (search-forward-regexp "^[ \t]*[^>\n]" nil t)))
2970        (if no-problem
2971            t
2972          (if (message-gnksa-enable-p 'quoted-text-only)
2973              (y-or-n-p "Your text should follow quoted text.  Really post? ")
2974            ;; Ensure that
2975            (goto-char (point-min))
2976            (re-search-forward
2977             (concat "^" (regexp-quote mail-header-separator) "$"))
2978            (if (search-forward-regexp "^[ \t]*[^>\n]" nil t)
2979                (y-or-n-p "Your text should follow quoted text.  Really post? ")
2980              (message "Denied posting -- only quoted text.")
2981              nil)))))))
2982
2983 (defun message-checksum ()
2984   "Return a \"checksum\" for the current buffer."
2985   (let ((sum 0))
2986     (save-excursion
2987       (goto-char (point-min))
2988       (re-search-forward
2989        (concat "^" (regexp-quote mail-header-separator) "$"))
2990       (while (not (eobp))
2991         (when (not (looking-at "[ \t\n]"))
2992           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2993                             (char-after))))
2994         (forward-char 1)))
2995     sum))
2996
2997 (defun message-do-fcc ()
2998   "Process Fcc headers in the current buffer."
2999   (let ((case-fold-search t)
3000         (buf (current-buffer))
3001         list file)
3002     (save-excursion
3003       (set-buffer (get-buffer-create " *message temp*"))
3004       (erase-buffer)
3005       (insert-buffer-substring buf)
3006       (save-restriction
3007         (message-narrow-to-headers)
3008         (while (setq file (message-fetch-field "fcc"))
3009           (push file list)
3010           (message-remove-header "fcc" nil t)))
3011       (message-encode-message-body)
3012       (save-restriction
3013         (message-narrow-to-headers)
3014         (let ((mail-parse-charset message-default-charset)
3015               (rfc2047-header-encoding-alist
3016                (cons '("Newsgroups" . default)
3017                      rfc2047-header-encoding-alist)))
3018           (mail-encode-encoded-word-buffer)))
3019       (goto-char (point-min))
3020       (when (re-search-forward
3021              (concat "^" (regexp-quote mail-header-separator) "$")
3022              nil t)
3023         (replace-match "" t t ))
3024       ;; Process FCC operations.
3025       (while list
3026         (setq file (pop list))
3027         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
3028             ;; Pipe the article to the program in question.
3029             (call-process-region (point-min) (point-max) shell-file-name
3030                                  nil nil nil shell-command-switch
3031                                  (match-string 1 file))
3032           ;; Save the article.
3033           (setq file (expand-file-name file))
3034           (unless (file-exists-p (file-name-directory file))
3035             (make-directory (file-name-directory file) t))
3036           (if (and message-fcc-handler-function
3037                    (not (eq message-fcc-handler-function 'rmail-output)))
3038               (funcall message-fcc-handler-function file)
3039             (if (and (file-readable-p file) (mail-file-babyl-p file))
3040                 (rmail-output file 1 nil t)
3041               (let ((mail-use-rfc822 t))
3042                 (rmail-output file 1 t t))))))
3043       (kill-buffer (current-buffer)))))
3044
3045 (defun message-output (filename)
3046   "Append this article to Unix/babyl mail file.."
3047   (if (and (file-readable-p filename)
3048            (mail-file-babyl-p filename))
3049       (gnus-output-to-rmail filename t)
3050     (gnus-output-to-mail filename t)))
3051
3052 (defun message-cleanup-headers ()
3053   "Do various automatic cleanups of the headers."
3054   ;; Remove empty lines in the header.
3055   (save-restriction
3056     (message-narrow-to-headers)
3057     ;; Remove blank lines.
3058     (while (re-search-forward "^[ \t]*\n" nil t)
3059       (replace-match "" t t))
3060
3061     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
3062     ;; spaces to comma and eliminate spaces around commas.  Eliminate
3063     ;; embedded line breaks.
3064     (goto-char (point-min))
3065     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
3066       (save-restriction
3067         (narrow-to-region
3068          (point)
3069          (if (re-search-forward "^[^ \t]" nil t)
3070              (match-beginning 0)
3071            (forward-line 1)
3072            (point)))
3073         (goto-char (point-min))
3074         (while (re-search-forward "\n[ \t]+" nil t)
3075           (replace-match " " t t))      ;No line breaks (too confusing)
3076         (goto-char (point-min))
3077         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
3078           (replace-match "," t t))
3079         (goto-char (point-min))
3080         ;; Remove trailing commas.
3081         (when (re-search-forward ",+$" nil t)
3082           (replace-match "" t t))))))
3083
3084 (defun message-make-date (&optional now)
3085   "Make a valid data header.
3086 If NOW, use that time instead."
3087   (let* ((now (or now (current-time)))
3088          (zone (nth 8 (decode-time now)))
3089          (sign "+"))
3090     (when (< zone 0)
3091       (setq sign "-")
3092       (setq zone (- zone)))
3093     (concat
3094      (format-time-string "%d" now)
3095      ;; The month name of the %b spec is locale-specific.  Pfff.
3096      (format " %s "
3097              (capitalize (car (rassoc (nth 4 (decode-time now))
3098                                       parse-time-months))))
3099      (format-time-string "%Y %H:%M:%S " now)
3100      ;; We do all of this because XEmacs doesn't have the %z spec.
3101      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
3102
3103 (defun message-make-message-id ()
3104   "Make a unique Message-ID."
3105   (concat "<" (message-unique-id)
3106           (let ((psubject (save-excursion (message-fetch-field "subject")))
3107                 (psupersedes
3108                  (save-excursion (message-fetch-field "supersedes"))))
3109             (if (or
3110                  (and message-reply-headers
3111                       (mail-header-references message-reply-headers)
3112                       (mail-header-subject message-reply-headers)
3113                       psubject
3114                       (not (string=
3115                             (message-strip-subject-re
3116                              (mail-header-subject message-reply-headers))
3117                             (message-strip-subject-re psubject))))
3118                  (and psupersedes
3119                       (string-match "_-_@" psupersedes)))
3120                 "_-_" ""))
3121           "@" (message-make-fqdn) ">"))
3122
3123 (defvar message-unique-id-char nil)
3124
3125 ;; If you ever change this function, make sure the new version
3126 ;; cannot generate IDs that the old version could.
3127 ;; You might for example insert a "." somewhere (not next to another dot
3128 ;; or string boundary), or modify the "fsf" string.
3129 (defun message-unique-id ()
3130   ;; Don't use microseconds from (current-time), they may be unsupported.
3131   ;; Instead we use this randomly inited counter.
3132   (setq message-unique-id-char
3133         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
3134            ;; (current-time) returns 16-bit ints,
3135            ;; and 2^16*25 just fits into 4 digits i base 36.
3136            (* 25 25)))
3137   (let ((tm (current-time)))
3138     (concat
3139      (if (memq system-type '(ms-dos emx vax-vms))
3140          (let ((user (downcase (user-login-name))))
3141            (while (string-match "[^a-z0-9_]" user)
3142              (aset user (match-beginning 0) ?_))
3143            user)
3144        (message-number-base36 (user-uid) -1))
3145      (message-number-base36 (+ (car   tm)
3146                                (lsh (% message-unique-id-char 25) 16)) 4)
3147      (message-number-base36 (+ (nth 1 tm)
3148                                (lsh (/ message-unique-id-char 25) 16)) 4)
3149      ;; Append the newsreader name, because while the generated
3150      ;; ID is unique to this newsreader, other newsreaders might
3151      ;; otherwise generate the same ID via another algorithm.
3152      ".fsf")))
3153
3154 (defun message-number-base36 (num len)
3155   (if (if (< len 0)
3156           (<= num 0)
3157         (= len 0))
3158       ""
3159     (concat (message-number-base36 (/ num 36) (1- len))
3160             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
3161                                   (% num 36))))))
3162
3163 (defun message-make-organization ()
3164   "Make an Organization header."
3165   (let* ((organization
3166           (when message-user-organization
3167             (if (message-functionp message-user-organization)
3168                 (funcall message-user-organization)
3169               message-user-organization))))
3170     (save-excursion
3171       (message-set-work-buffer)
3172       (cond ((stringp organization)
3173              (insert organization))
3174             ((and (eq t organization)
3175                   message-user-organization-file
3176                   (file-exists-p message-user-organization-file))
3177              (insert-file-contents message-user-organization-file)))
3178       (goto-char (point-min))
3179       (while (re-search-forward "[\t\n]+" nil t)
3180         (replace-match "" t t))
3181       (unless (zerop (buffer-size))
3182         (buffer-string)))))
3183
3184 (defun message-make-lines ()
3185   "Count the number of lines and return numeric string."
3186   (save-excursion
3187     (save-restriction
3188       (widen)
3189       (message-goto-body)
3190       (int-to-string (count-lines (point) (point-max))))))
3191
3192 (defun message-make-in-reply-to ()
3193   "Return the In-Reply-To header for this message."
3194   (when message-reply-headers
3195     (mail-header-message-id message-reply-headers)))
3196
3197 (defun message-make-distribution ()
3198   "Make a Distribution header."
3199   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3200     (cond ((message-functionp message-distribution-function)
3201            (funcall message-distribution-function))
3202           (t orig-distribution))))
3203
3204 (defun message-make-expires ()
3205   "Return an Expires header based on `message-expires'."
3206   (let ((current (current-time))
3207         (future (* 1.0 message-expires 60 60 24)))
3208     ;; Add the future to current.
3209     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3210     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3211     (message-make-date current)))
3212
3213 (defun message-make-path ()
3214   "Return uucp path."
3215   (let ((login-name (user-login-name)))
3216     (cond ((null message-user-path)
3217            (concat (system-name) "!" login-name))
3218           ((stringp message-user-path)
3219            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3220            (concat message-user-path "!" login-name))
3221           (t login-name))))
3222
3223 (defun message-make-from ()
3224   "Make a From header."
3225   (let* ((style message-from-style)
3226          (login (message-make-address))
3227          (fullname
3228           (or (and (boundp 'user-full-name)
3229                    user-full-name)
3230               (user-full-name))))
3231     (when (string= fullname "&")
3232       (setq fullname (user-login-name)))
3233     (save-excursion
3234       (message-set-work-buffer)
3235       (cond
3236        ((or (null style)
3237             (equal fullname ""))
3238         (insert login))
3239        ((or (eq style 'angles)
3240             (and (not (eq style 'parens))
3241                  ;; Use angles if no quoting is needed, or if parens would
3242                  ;; need quoting too.
3243                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3244                      (let ((tmp (concat fullname nil)))
3245                        (while (string-match "([^()]*)" tmp)
3246                          (aset tmp (match-beginning 0) ?-)
3247                          (aset tmp (1- (match-end 0)) ?-))
3248                        (string-match "[\\()]" tmp)))))
3249         (insert fullname)
3250         (goto-char (point-min))
3251         ;; Look for a character that cannot appear unquoted
3252         ;; according to RFC 822.
3253         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3254           ;; Quote fullname, escaping specials.
3255           (goto-char (point-min))
3256           (insert "\"")
3257           (while (re-search-forward "[\"\\]" nil 1)
3258             (replace-match "\\\\\\&" t))
3259           (insert "\""))
3260         (insert " <" login ">"))
3261        (t                               ; 'parens or default
3262         (insert login " (")
3263         (let ((fullname-start (point)))
3264           (insert fullname)
3265           (goto-char fullname-start)
3266           ;; RFC 822 says \ and nonmatching parentheses
3267           ;; must be escaped in comments.
3268           ;; Escape every instance of ()\ ...
3269           (while (re-search-forward "[()\\]" nil 1)
3270             (replace-match "\\\\\\&" t))
3271           ;; ... then undo escaping of matching parentheses,
3272           ;; including matching nested parentheses.
3273           (goto-char fullname-start)
3274           (while (re-search-forward
3275                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3276                   nil 1)
3277             (replace-match "\\1(\\3)" t)
3278             (goto-char fullname-start)))
3279         (insert ")")))
3280       (buffer-string))))
3281
3282 (defun message-make-sender ()
3283   "Return the \"real\" user address.
3284 This function tries to ignore all user modifications, and
3285 give as trustworthy answer as possible."
3286   (concat (user-login-name) "@" (system-name)))
3287
3288 (defun message-make-address ()
3289   "Make the address of the user."
3290   (or (message-user-mail-address)
3291       (concat (user-login-name) "@" (message-make-domain))))
3292
3293 (defun message-user-mail-address ()
3294   "Return the pertinent part of `user-mail-address'."
3295   (when user-mail-address
3296     (if (string-match " " user-mail-address)
3297         (nth 1 (mail-extract-address-components user-mail-address))
3298       user-mail-address)))
3299
3300 (defun message-make-fqdn ()
3301   "Return user's fully qualified domain name."
3302   (let ((system-name (system-name))
3303         (user-mail (message-user-mail-address)))
3304     (cond
3305      ((string-match "[^.]\\.[^.]" system-name)
3306       ;; `system-name' returned the right result.
3307       system-name)
3308      ;; Try `mail-host-address'.
3309      ((and (boundp 'mail-host-address)
3310            (stringp mail-host-address)
3311            (string-match "\\." mail-host-address))
3312       mail-host-address)
3313      ;; We try `user-mail-address' as a backup.
3314      ((and user-mail
3315            (string-match "\\." user-mail)
3316            (string-match "@\\(.*\\)\\'" user-mail))
3317       (match-string 1 user-mail))
3318      ;; Default to this bogus thing.
3319      (t
3320       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3321
3322 (defun message-make-host-name ()
3323   "Return the name of the host."
3324   (let ((fqdn (message-make-fqdn)))
3325     (string-match "^[^.]+\\." fqdn)
3326     (substring fqdn 0 (1- (match-end 0)))))
3327
3328 (defun message-make-domain ()
3329   "Return the domain name."
3330   (or mail-host-address
3331       (message-make-fqdn)))
3332
3333 (defun message-generate-headers (headers)
3334   "Prepare article HEADERS.
3335 Headers already prepared in the buffer are not modified."
3336   (save-restriction
3337     (message-narrow-to-headers)
3338     (let* ((Date (message-make-date))
3339            (Message-ID (message-make-message-id))
3340            (Organization (message-make-organization))
3341            (From (message-make-from))
3342            (Path (message-make-path))
3343            (Subject nil)
3344            (Newsgroups nil)
3345            (In-Reply-To (message-make-in-reply-to))
3346            (To nil)
3347            (Distribution (message-make-distribution))
3348            (Lines (message-make-lines))
3349            (User-Agent message-newsreader)
3350            (Expires (message-make-expires))
3351            (case-fold-search t)
3352            header value elem)
3353       ;; First we remove any old generated headers.
3354       (let ((headers message-deletable-headers))
3355         (unless (buffer-modified-p)
3356           (setq headers (delq 'Message-ID (copy-sequence headers))))
3357         (while headers
3358           (goto-char (point-min))
3359           (and (re-search-forward
3360                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3361                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3362                (message-delete-line))
3363           (pop headers)))
3364       ;; Go through all the required headers and see if they are in the
3365       ;; articles already.  If they are not, or are empty, they are
3366       ;; inserted automatically - except for Subject, Newsgroups and
3367       ;; Distribution.
3368       (while headers
3369         (goto-char (point-min))
3370         (setq elem (pop headers))
3371         (if (consp elem)
3372             (if (eq (car elem) 'optional)
3373                 (setq header (cdr elem))
3374               (setq header (car elem)))
3375           (setq header elem))
3376         (when (or (not (re-search-forward
3377                         (concat "^"
3378                                 (regexp-quote
3379                                  (downcase
3380                                   (if (stringp header)
3381                                       header
3382                                     (symbol-name header))))
3383                                 ":")
3384                         nil t))
3385                   (progn
3386                     ;; The header was found.  We insert a space after the
3387                     ;; colon, if there is none.
3388                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3389                     ;; Find out whether the header is empty...
3390                     (looking-at "[ \t]*\n[^ \t]")))
3391           ;; So we find out what value we should insert.
3392           (setq value
3393                 (cond
3394                  ((and (consp elem) (eq (car elem) 'optional))
3395                   ;; This is an optional header.  If the cdr of this
3396                   ;; is something that is nil, then we do not insert
3397                   ;; this header.
3398                   (setq header (cdr elem))
3399                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3400                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3401                  ((consp elem)
3402                   ;; The element is a cons.  Either the cdr is a
3403                   ;; string to be inserted verbatim, or it is a
3404                   ;; function, and we insert the value returned from
3405                   ;; this function.
3406                   (or (and (stringp (cdr elem)) (cdr elem))
3407                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3408                  ((and (boundp header) (symbol-value header))
3409                   ;; The element is a symbol.  We insert the value
3410                   ;; of this symbol, if any.
3411                   (symbol-value header))
3412                  ((not (message-check-element header))
3413                   ;; We couldn't generate a value for this header,
3414                   ;; so we just ask the user.
3415                   (read-from-minibuffer
3416                    (format "Empty header for %s; enter value: " header)))))
3417           ;; Finally insert the header.
3418           (when (and value
3419                      (not (equal value "")))
3420             (save-excursion
3421               (if (bolp)
3422                   (progn
3423                     ;; This header didn't exist, so we insert it.
3424                     (goto-char (point-max))
3425                     (insert (if (stringp header) header (symbol-name header))
3426                             ": " value "\n")
3427                     (forward-line -1))
3428                 ;; The value of this header was empty, so we clear
3429                 ;; totally and insert the new value.
3430                 (delete-region (point) (gnus-point-at-eol))
3431                 (insert value))
3432               ;; Add the deletable property to the headers that require it.
3433               (and (memq header message-deletable-headers)
3434                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3435                    (add-text-properties
3436                     (point) (match-end 0)
3437                     '(message-deletable t face italic) (current-buffer)))))))
3438       ;; Insert new Sender if the From is strange.
3439       (let ((from (message-fetch-field "from"))
3440             (sender (message-fetch-field "sender"))
3441             (secure-sender (message-make-sender)))
3442         (when (and from
3443                    (not (message-check-element 'sender))
3444                    (not (string=
3445                          (downcase
3446                           (cadr (mail-extract-address-components from)))
3447                          (downcase secure-sender)))
3448                    (or (null sender)
3449                        (not
3450                         (string=
3451                          (downcase
3452                           (cadr (mail-extract-address-components sender)))
3453                          (downcase secure-sender)))))
3454           (goto-char (point-min))
3455           ;; Rename any old Sender headers to Original-Sender.
3456           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3457             (beginning-of-line)
3458             (insert "Original-")
3459             (beginning-of-line))
3460           (when (or (message-news-p)
3461                     (string-match "@.+\\.." secure-sender))
3462             (insert "Sender: " secure-sender "\n")))))))
3463
3464 (defun message-insert-courtesy-copy ()
3465   "Insert a courtesy message in mail copies of combined messages."
3466   (let (newsgroups)
3467     (save-excursion
3468       (save-restriction
3469         (message-narrow-to-headers)
3470         (when (setq newsgroups (message-fetch-field "newsgroups"))
3471           (goto-char (point-max))
3472           (insert "Posted-To: " newsgroups "\n")))
3473       (forward-line 1)
3474       (when message-courtesy-message
3475         (cond
3476          ((string-match "%s" message-courtesy-message)
3477           (insert (format message-courtesy-message newsgroups)))
3478          (t
3479           (insert message-courtesy-message)))))))
3480
3481 ;;;
3482 ;;; Setting up a message buffer
3483 ;;;
3484
3485 (defun message-fill-address (header value)
3486   (save-restriction
3487     (narrow-to-region (point) (point))
3488     (insert (capitalize (symbol-name header))
3489             ": "
3490             (if (consp value) (car value) value)
3491             "\n")
3492     (narrow-to-region (point-min) (1- (point-max)))
3493     (let (quoted last)
3494       (goto-char (point-min))
3495       (while (not (eobp))
3496         (skip-chars-forward "^,\"" (point-max))
3497         (if (or (eq (char-after) ?,)
3498                 (eobp))
3499             (when (not quoted)
3500               (if (and (> (current-column) 78)
3501                        last)
3502                   (progn
3503                     (save-excursion
3504                       (goto-char last)
3505                       (insert "\n\t"))
3506                     (setq last (1+ (point))))
3507                 (setq last (1+ (point)))))
3508           (setq quoted (not quoted)))
3509         (unless (eobp)
3510           (forward-char 1))))
3511     (goto-char (point-max))
3512     (widen)
3513     (forward-line 1)))
3514
3515 (defun message-fill-header (header value)
3516   (let ((begin (point))
3517         (fill-column 78)
3518         (fill-prefix "\t"))
3519     (insert (capitalize (symbol-name header))
3520             ": "
3521             (if (consp value) (car value) value)
3522             "\n")
3523     (save-restriction
3524       (narrow-to-region begin (point))
3525       (fill-region-as-paragraph begin (point))
3526       ;; Tapdance around looong Message-IDs.
3527       (forward-line -1)
3528       (when (looking-at "[ \t]*$")
3529         (message-delete-line))
3530       (goto-char begin)
3531       (re-search-forward ":" nil t)
3532       (when (looking-at "\n[ \t]+")
3533         (replace-match " " t t))
3534       (goto-char (point-max)))))
3535
3536 (defun message-shorten-1 (list cut surplus)
3537   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3538   (setcdr (nthcdr (- cut 2) list)
3539           (nthcdr (+ (- cut 2) surplus 1) list)))
3540
3541 (defun message-shorten-references (header references)
3542   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3543 If folding is disallowed, also check that the REFERENCES are less
3544 than 988 characters long, and if they are not, trim them until they are."
3545   (let ((maxcount 31)
3546         (count 0)
3547         (cut 6)
3548         refs)
3549     (with-temp-buffer
3550       (insert references)
3551       (goto-char (point-min))
3552       ;; Cons a list of valid references.
3553       (while (re-search-forward "<[^>]+>" nil t)
3554         (push (match-string 0) refs))
3555       (setq refs (nreverse refs)
3556             count (length refs)))
3557
3558     ;; If the list has more than MAXCOUNT elements, trim it by
3559     ;; removing the CUTth element and the required number of
3560     ;; elements that follow.
3561     (when (> count maxcount)
3562       (let ((surplus (- count maxcount)))
3563         (message-shorten-1 refs cut surplus)
3564         (decf count surplus)))
3565
3566     ;; If folding is disallowed, make sure the total length (including
3567     ;; the spaces between) will be less than MAXSIZE characters.
3568     ;;
3569     ;; Only disallow folding for News messages. At this point the headers
3570     ;; have not been generated, thus we use message-this-is-news directly.
3571     (when (and message-this-is-news message-cater-to-broken-inn)
3572       (let ((maxsize 988)
3573             (totalsize (+ (apply #'+ (mapcar #'length refs))
3574                           (1- count)))
3575             (surplus 0)
3576             (ptr (nthcdr (1- cut) refs)))
3577         ;; Decide how many elements to cut off...
3578         (while (> totalsize maxsize)
3579           (decf totalsize (1+ (length (car ptr))))
3580           (incf surplus)
3581           (setq ptr (cdr ptr)))
3582         ;; ...and do it.
3583         (when (> surplus 0)
3584           (message-shorten-1 refs cut surplus))))
3585
3586     ;; Finally, collect the references back into a string and insert
3587     ;; it into the buffer.
3588     (let ((refstring (mapconcat #'identity refs " ")))
3589       (if (and message-this-is-news message-cater-to-broken-inn)
3590           (insert (capitalize (symbol-name header)) ": "
3591                   refstring "\n")
3592         (message-fill-header header refstring)))))
3593
3594 (defun message-position-point ()
3595   "Move point to where the user probably wants to find it."
3596   (message-narrow-to-headers)
3597   (cond
3598    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3599     (search-backward ":" )
3600     (widen)
3601     (forward-char 1)
3602     (if (eq (char-after) ? )
3603         (forward-char 1)
3604       (insert " ")))
3605    (t
3606     (goto-char (point-max))
3607     (widen)
3608     (forward-line 1)
3609     (unless (looking-at "$")
3610       (forward-line 2)))
3611    (sit-for 0)))
3612
3613 (defun message-buffer-name (type &optional to group)
3614   "Return a new (unique) buffer name based on TYPE and TO."
3615   (cond
3616    ;; Generate a new buffer name The Message Way.
3617    ((eq message-generate-new-buffers 'unique)
3618     (generate-new-buffer-name
3619      (concat "*" type
3620              (if to
3621                  (concat " to "
3622                          (or (car (mail-extract-address-components to))
3623                              to) "")
3624                "")
3625              (if (and group (not (string= group ""))) (concat " on " group) "")
3626              "*")))
3627    ;; Check whether `message-generate-new-buffers' is a function,
3628    ;; and if so, call it.
3629    ((message-functionp message-generate-new-buffers)
3630     (funcall message-generate-new-buffers type to group))
3631    ((eq message-generate-new-buffers 'unsent)
3632     (generate-new-buffer-name
3633      (concat "*unsent " type
3634              (if to
3635                  (concat " to "
3636                          (or (car (mail-extract-address-components to))
3637                              to) "")
3638                "")
3639              (if (and group (not (string= group ""))) (concat " on " group) "")
3640              "*")))
3641    ;; Use standard name.
3642    (t
3643     (format "*%s message*" type))))
3644
3645 (defun message-pop-to-buffer (name)
3646   "Pop to buffer NAME, and warn if it already exists and is modified."
3647   (let ((buffer (get-buffer name)))
3648     (if (and buffer
3649              (buffer-name buffer))
3650         (progn
3651           (set-buffer (pop-to-buffer buffer))
3652           (when (and (buffer-modified-p)
3653                      (not (y-or-n-p
3654                            "Message already being composed; erase? ")))
3655             (error "Message being composed")))
3656       (set-buffer (pop-to-buffer name)))
3657     (erase-buffer)
3658     (message-mode)))
3659
3660 (defun message-do-send-housekeeping ()
3661   "Kill old message buffers."
3662   ;; We might have sent this buffer already.  Delete it from the
3663   ;; list of buffers.
3664   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3665   (while (and message-max-buffers
3666               message-buffer-list
3667               (>= (length message-buffer-list) message-max-buffers))
3668     ;; Kill the oldest buffer -- unless it has been changed.
3669     (let ((buffer (pop message-buffer-list)))
3670       (when (and (buffer-name buffer)
3671                  (not (buffer-modified-p buffer)))
3672         (kill-buffer buffer))))
3673   ;; Rename the buffer.
3674   (if message-send-rename-function
3675       (funcall message-send-rename-function)
3676     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3677       (rename-buffer
3678        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3679   ;; Push the current buffer onto the list.
3680   (when message-max-buffers
3681     (setq message-buffer-list
3682           (nconc message-buffer-list (list (current-buffer))))))
3683
3684 (defun message-mail-user-agent ()
3685   (let ((mua (cond
3686               ((not message-mail-user-agent) nil)
3687               ((eq message-mail-user-agent t) mail-user-agent)
3688               (t message-mail-user-agent))))
3689     (if (memq mua '(message-user-agent gnus-user-agent))
3690         nil
3691       mua)))
3692
3693 (defun message-setup (headers &optional replybuffer actions switch-function)
3694   (let ((mua (message-mail-user-agent))
3695         subject to field yank-action)
3696     (if (not (and message-this-is-mail mua))
3697         (message-setup-1 headers replybuffer actions)
3698       (if replybuffer
3699           (setq yank-action (list 'insert-buffer replybuffer)))
3700       (setq headers (copy-sequence headers))
3701       (setq field (assq 'Subject headers))
3702       (when field
3703         (setq subject (cdr field))
3704         (setq headers (delq field headers)))
3705       (setq field (assq 'To headers))
3706       (when field
3707         (setq to (cdr field))
3708         (setq headers (delq field headers)))
3709       (let ((mail-user-agent mua))
3710         (compose-mail to subject 
3711                       (mapcar (lambda (item)
3712                                 (cons
3713                                  (format "%s" (car item))
3714                                  (cdr item)))
3715                               headers)
3716                       nil switch-function yank-action actions))))) 
3717
3718 ;;;(defvar mc-modes-alist)
3719 (defun message-setup-1 (headers &optional replybuffer actions)
3720 ;;;   (when (and (boundp 'mc-modes-alist)
3721 ;;;          (not (assq 'message-mode mc-modes-alist)))
3722 ;;;     (push '(message-mode (encrypt . mc-encrypt-message)
3723 ;;;                      (sign . mc-sign-message))
3724 ;;;       mc-modes-alist))
3725   (when actions
3726     (setq message-send-actions actions))
3727   (setq message-reply-buffer replybuffer)
3728   (goto-char (point-min))
3729   ;; Insert all the headers.
3730   (mail-header-format
3731    (let ((h headers)
3732          (alist message-header-format-alist))
3733      (while h
3734        (unless (assq (caar h) message-header-format-alist)
3735          (push (list (caar h)) alist))
3736        (pop h))
3737      alist)
3738    headers)
3739   (delete-region (point) (progn (forward-line -1) (point)))
3740   (when message-default-headers
3741     (insert message-default-headers)
3742     (or (bolp) (insert ?\n)))
3743   (put-text-property
3744    (point)
3745    (progn
3746      (insert mail-header-separator "\n")
3747      (1- (point)))
3748    'read-only nil)
3749   (forward-line -1)
3750   (when (message-news-p)
3751     (when message-default-news-headers
3752       (insert message-default-news-headers)
3753       (or (bolp) (insert ?\n)))
3754     (when message-generate-headers-first
3755       (message-generate-headers
3756        (delq 'Lines
3757              (delq 'Subject
3758                    (copy-sequence message-required-news-headers))))))
3759   (when (message-mail-p)
3760     (when message-default-mail-headers
3761       (insert message-default-mail-headers)
3762       (or (bolp) (insert ?\n)))
3763     (when message-generate-headers-first
3764       (message-generate-headers
3765        (delq 'Lines
3766              (delq 'Subject
3767                    (copy-sequence message-required-mail-headers))))))
3768   (run-hooks 'message-signature-setup-hook)
3769   (message-insert-signature)
3770   (save-restriction
3771     (message-narrow-to-headers)
3772     (if message-alternative-emails
3773         (message-use-alternative-email-as-from))
3774     (run-hooks 'message-header-setup-hook))
3775   (set-buffer-modified-p nil)
3776   (setq buffer-undo-list nil)
3777   (run-hooks 'message-setup-hook)
3778   (message-position-point)
3779   (undo-boundary))
3780
3781 (defun message-set-auto-save-file-name ()
3782   "Associate the message buffer with a file in the drafts directory."
3783   (when message-auto-save-directory
3784     (unless (file-directory-p
3785              (directory-file-name message-auto-save-directory))
3786       (gnus-make-directory message-auto-save-directory))
3787     (if (gnus-alive-p)
3788         (setq message-draft-article
3789               (nndraft-request-associate-buffer "drafts"))
3790       (setq buffer-file-name (expand-file-name "*message*"
3791                                                message-auto-save-directory))
3792       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3793     (clear-visited-file-modtime)
3794     (setq buffer-file-coding-system message-draft-coding-system)))
3795
3796 (defun message-disassociate-draft ()
3797   "Disassociate the message buffer from the drafts directory."
3798   (when message-draft-article
3799     (nndraft-request-expire-articles
3800      (list message-draft-article) "drafts" nil t)))
3801
3802 (defun message-insert-headers ()
3803   "Generate the headers for the article."
3804   (interactive)
3805   (save-excursion
3806     (save-restriction
3807       (message-narrow-to-headers)
3808       (when (message-news-p)
3809         (message-generate-headers
3810          (delq 'Lines
3811                (delq 'Subject
3812                      (copy-sequence message-required-news-headers)))))
3813       (when (message-mail-p)
3814         (message-generate-headers
3815          (delq 'Lines
3816                (delq 'Subject
3817                      (copy-sequence message-required-mail-headers))))))))
3818
3819 \f
3820
3821 ;;;
3822 ;;; Commands for interfacing with message
3823 ;;;
3824
3825 ;;;###autoload
3826 (defun message-mail (&optional to subject
3827                                other-headers continue switch-function
3828                                yank-action send-actions)
3829   "Start editing a mail message to be sent.
3830 OTHER-HEADERS is an alist of header/value pairs."
3831   (interactive)
3832   (let ((message-this-is-mail t) replybuffer)
3833     (unless (message-mail-user-agent)
3834       (message-pop-to-buffer (message-buffer-name "mail" to)))
3835     ;; FIXME: message-mail should do something if YANK-ACTION is not
3836     ;; insert-buffer.
3837     (and (consp yank-action) (eq (car yank-action) 'insert-buffer)
3838          (setq replybuffer (nth 1 yank-action)))
3839     (message-setup
3840      (nconc
3841       `((To . ,(or to "")) (Subject . ,(or subject "")))
3842       (when other-headers other-headers))
3843      replybuffer)
3844     ;; FIXME: Should return nil if failure.
3845     t))
3846
3847 ;;;###autoload
3848 (defun message-news (&optional newsgroups subject)
3849   "Start editing a news article to be sent."
3850   (interactive)
3851   (let ((message-this-is-news t))
3852     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3853     (message-setup `((Newsgroups . ,(or newsgroups ""))
3854                      (Subject . ,(or subject ""))))))
3855
3856 (defun message-get-reply-headers (wide &optional to-address)
3857   (let (follow-to mct never-mct from to cc reply-to mrt mft ccalist)
3858     ;; Find all relevant headers we need.
3859     (setq from (message-fetch-field "from")
3860           to (message-fetch-field "to")
3861           cc (message-fetch-field "cc")
3862           mct (message-fetch-field "mail-copies-to")
3863           reply-to (message-fetch-field "reply-to")
3864           mrt (message-fetch-field "mail-reply-to")
3865           mft (message-fetch-field "mail-followup-to"))
3866
3867     ;; Handle special values of Mail-Copies-To.
3868     (when mct
3869       (cond ((or (equal (downcase mct) "never")
3870                  (equal (downcase mct) "nobody"))
3871              (setq never-mct t)
3872              (setq mct nil))
3873             ((or (equal (downcase mct) "always")
3874                  (equal (downcase mct) "poster"))
3875              (setq mct (or mrt reply-to from)))))
3876
3877     (if (or (not wide)
3878             to-address)
3879         (progn
3880           (setq follow-to (list (cons 'To (or to-address mrt reply-to from))))
3881           (when (and wide (or mft mct))
3882             (push (cons 'Cc (or mft mct)) follow-to)))
3883       (let (ccalist)
3884         (save-excursion
3885           (message-set-work-buffer)
3886           (if (and mft
3887                    message-use-followup-to
3888                    (or (not (eq message-use-followup-to 'ask))
3889                        (message-y-or-n-p
3890                         (concat "Obey Mail-Followup-To? ") t "\
3891 You should normally obey the Mail-Followup-To: header.  In this
3892 article, it has the value of
3893
3894 " mft "
3895
3896 which directs your response to " (if (string-match "," mft)
3897                                "the specified addresses"
3898                              "that address only") ".
3899
3900 If a message is posted to several mailing lists, Mail-Followup-To is
3901 often used to direct the following discussion to one list only,
3902 because discussions that are spread over several lists tend to be
3903 fragmented and very difficult to follow.
3904
3905 Also, some source/announcement lists are not indented for discussion;
3906 responses here are directed to other addresses.")))
3907               (insert mft)
3908             (unless never-mct
3909               (insert (or mrt reply-to from "")))
3910             (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3911             (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3912             (insert (if cc (concat (if (bolp) "" ", ") cc) "")))
3913           (goto-char (point-min))
3914           (while (re-search-forward "[ \t]+" nil t)
3915             (replace-match " " t t))
3916           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3917           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3918             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3919                       (erase-buffer))))
3920           (goto-char (point-min))
3921           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3922           (when (eobp)
3923             (insert (or mrt reply-to from "")))
3924           (setq ccalist
3925                 (mapcar
3926                  (lambda (addr)
3927                    (cons (mail-strip-quoted-names addr) addr))
3928                  (message-tokenize-header (buffer-string))))
3929           (let ((s ccalist))
3930             (while s
3931               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3932         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3933         (when ccalist
3934           (let ((ccs (cons 'Cc (mapconcat
3935                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3936             (when (string-match "^ +" (cdr ccs))
3937               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3938             (push ccs follow-to)))))
3939     follow-to))
3940
3941
3942 ;;;###autoload
3943 (defun message-reply (&optional to-address wide)
3944   "Start editing a reply to the article in the current buffer."
3945   (interactive)
3946   (require 'gnus-sum)                   ; for gnus-list-identifiers
3947   (let ((cur (current-buffer))
3948         from subject date reply-to to cc
3949         references message-id follow-to
3950         (inhibit-point-motion-hooks t)
3951         (message-this-is-mail t)
3952         gnus-warning)
3953     (save-restriction
3954       (message-narrow-to-head-1)
3955       ;; Allow customizations to have their say.
3956       (if (not wide)
3957           ;; This is a regular reply.
3958           (when (message-functionp message-reply-to-function)
3959             (save-excursion
3960               (setq follow-to (funcall message-reply-to-function))))
3961         ;; This is a followup.
3962         (when (message-functionp message-wide-reply-to-function)
3963           (save-excursion
3964             (setq follow-to
3965                   (funcall message-wide-reply-to-function)))))
3966       (setq message-id (message-fetch-field "message-id" t)
3967             references (message-fetch-field "references")
3968             date (message-fetch-field "date")
3969             from (message-fetch-field "from")
3970             subject (or (message-fetch-field "subject") "none"))
3971     (when gnus-list-identifiers
3972       (setq subject (message-strip-list-identifiers subject)))
3973     (setq subject (concat "Re: " (message-strip-subject-re subject)))
3974
3975     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3976                (string-match "<[^>]+>" gnus-warning))
3977       (setq message-id (match-string 0 gnus-warning)))
3978
3979     (unless follow-to
3980       (setq follow-to (message-get-reply-headers wide to-address))))
3981
3982     (unless (message-mail-user-agent)
3983       (message-pop-to-buffer
3984        (message-buffer-name
3985         (if wide "wide reply" "reply") from
3986         (if wide to-address nil))))
3987
3988     (setq message-reply-headers
3989           (vector 0 subject from date message-id references 0 0 ""))
3990
3991     (message-setup
3992      `((Subject . ,subject)
3993        ,@follow-to
3994        ,@(if (or references message-id)
3995              `((References . ,(concat (or references "") (and references " ")
3996                                       (or message-id ""))))
3997            nil))
3998      cur)))
3999
4000 ;;;###autoload
4001 (defun message-wide-reply (&optional to-address)
4002   "Make a \"wide\" reply to the message in the current buffer."
4003   (interactive)
4004   (message-reply to-address t))
4005
4006 ;;;###autoload
4007 (defun message-followup (&optional to-newsgroups)
4008   "Follow up to the message in the current buffer.
4009 If TO-NEWSGROUPS, use that as the new Newsgroups line."
4010   (interactive)
4011   (require 'gnus-sum)                   ; for gnus-list-identifiers
4012   (let ((cur (current-buffer))
4013         from subject date reply-to mrt mct
4014         references message-id follow-to
4015         (inhibit-point-motion-hooks t)
4016         (message-this-is-news t)
4017         followup-to distribution newsgroups gnus-warning posted-to)
4018     (save-restriction
4019       (narrow-to-region
4020        (goto-char (point-min))
4021        (if (search-forward "\n\n" nil t)
4022            (1- (point))
4023          (point-max)))
4024       (when (message-functionp message-followup-to-function)
4025         (setq follow-to
4026               (funcall message-followup-to-function)))
4027       (setq from (message-fetch-field "from")
4028             date (message-fetch-field "date")
4029             subject (or (message-fetch-field "subject") "none")
4030             references (message-fetch-field "references")
4031             message-id (message-fetch-field "message-id" t)
4032             followup-to (message-fetch-field "followup-to")
4033             newsgroups (message-fetch-field "newsgroups")
4034             posted-to (message-fetch-field "posted-to")
4035             reply-to (message-fetch-field "reply-to")
4036             mrt (message-fetch-field "mail-reply-to")
4037             distribution (message-fetch-field "distribution")
4038             mct (message-fetch-field "mail-copies-to"))
4039       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
4040                  (string-match "<[^>]+>" gnus-warning))
4041         (setq message-id (match-string 0 gnus-warning)))
4042       ;; Remove bogus distribution.
4043       (when (and (stringp distribution)
4044                  (let ((case-fold-search t))
4045                    (string-match "world" distribution)))
4046         (setq distribution nil))
4047       (if gnus-list-identifiers
4048           (setq subject (message-strip-list-identifiers subject)))
4049       (setq subject (concat "Re: " (message-strip-subject-re subject)))
4050       (widen))
4051
4052     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
4053
4054     (message-setup
4055      `((Subject . ,subject)
4056        ,@(cond
4057           (to-newsgroups
4058            (list (cons 'Newsgroups to-newsgroups)))
4059           (follow-to follow-to)
4060           ((and followup-to message-use-followup-to)
4061            (list
4062             (cond
4063              ((equal (downcase followup-to) "poster")
4064               (if (or (eq message-use-followup-to 'use)
4065                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
4066 You should normally obey the Followup-To: header.
4067
4068 `Followup-To: poster' sends your response via e-mail instead of news.
4069
4070 A typical situation where `Followup-To: poster' is used is when the poster
4071 does not read the newsgroup, so he wouldn't see any replies sent to it."))
4072                   (progn
4073                     (setq message-this-is-news nil)
4074                     (cons 'To (or mrt reply-to from "")))
4075                 (cons 'Newsgroups newsgroups)))
4076              (t
4077               (if (or (equal followup-to newsgroups)
4078                       (not (eq message-use-followup-to 'ask))
4079                       (message-y-or-n-p
4080                        (concat "Obey Followup-To: " followup-to "? ") t "\
4081 You should normally obey the Followup-To: header.
4082
4083         `Followup-To: " followup-to "'
4084 directs your response to " (if (string-match "," followup-to)
4085                                "the specified newsgroups"
4086                              "that newsgroup only") ".
4087
4088 If a message is posted to several newsgroups, Followup-To is often
4089 used to direct the following discussion to one newsgroup only,
4090 because discussions that are spread over several newsgroup tend to
4091 be fragmented and very difficult to follow.
4092
4093 Also, some source/announcement newsgroups are not indented for discussion;
4094 responses here are directed to other newsgroups."))
4095                   (cons 'Newsgroups followup-to)
4096                 (cons 'Newsgroups newsgroups))))))
4097           (posted-to
4098            `((Newsgroups . ,posted-to)))
4099           (t
4100            `((Newsgroups . ,newsgroups))))
4101        ,@(and distribution (list (cons 'Distribution distribution)))
4102        ,@(if (or references message-id)
4103              `((References . ,(concat (or references "") (and references " ")
4104                                       (or message-id "")))))
4105        ,@(when (and mct
4106                     (not (or (equal (downcase mct) "never")
4107                              (equal (downcase mct) "nobody"))))
4108            (list (cons 'Cc (if (or (equal (downcase mct) "always")
4109                                    (equal (downcase mct) "poster"))
4110                                (or mrt reply-to from "")
4111                              mct)))))
4112
4113      cur)
4114
4115     (setq message-reply-headers
4116           (vector 0 subject from date message-id references 0 0 ""))))
4117
4118
4119 ;;;###autoload
4120 (defun message-cancel-news (&optional arg)
4121   "Cancel an article you posted.
4122 If ARG, allow editing of the cancellation message."
4123   (interactive "P")
4124   (unless (message-news-p)
4125     (error "This is not a news article; canceling is impossible"))
4126   (when (yes-or-no-p "Do you really want to cancel this article? ")
4127     (let (from newsgroups message-id distribution buf sender)
4128       (save-excursion
4129         ;; Get header info from original article.
4130         (save-restriction
4131           (message-narrow-to-head-1)
4132           (setq from (message-fetch-field "from")
4133                 sender (message-fetch-field "sender")
4134                 newsgroups (message-fetch-field "newsgroups")
4135                 message-id (message-fetch-field "message-id" t)
4136                 distribution (message-fetch-field "distribution")))
4137         ;; Make sure that this article was written by the user.
4138         (unless (or (and sender
4139                          (string-equal
4140                           (downcase sender)
4141                           (downcase (message-make-sender))))
4142                     (string-equal
4143                      (downcase (cadr (mail-extract-address-components from)))
4144                      (downcase (cadr (mail-extract-address-components
4145                                       (message-make-from))))))
4146           (error "This article is not yours"))
4147         ;; Make control message.
4148         (if arg
4149             (message-news)
4150           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
4151         (erase-buffer)
4152         (insert "Newsgroups: " newsgroups "\n"
4153                "From: " from "\n"
4154                 "Subject: cmsg cancel " message-id "\n"
4155                 "Control: cancel " message-id "\n"
4156                 (if distribution
4157                     (concat "Distribution: " distribution "\n")
4158                   "")
4159                 mail-header-separator "\n"
4160                 message-cancel-message)
4161         (run-hooks 'message-cancel-hook)
4162         (unless arg
4163           (message "Canceling your article...")
4164           (if (let ((message-syntax-checks
4165                      'dont-check-for-anything-just-trust-me))
4166                 (funcall message-send-news-function))
4167               (message "Canceling your article...done"))
4168           (kill-buffer buf))))))
4169
4170 ;;;###autoload
4171 (defun message-supersede ()
4172   "Start composing a message to supersede the current message.
4173 This is done simply by taking the old article and adding a Supersedes
4174 header line with the old Message-ID."
4175   (interactive)
4176   (let ((cur (current-buffer))
4177         (sender (message-fetch-field "sender"))
4178         (from (message-fetch-field "from")))
4179     ;; Check whether the user owns the article that is to be superseded.
4180     (unless (or (and sender
4181                      (string-equal
4182                       (downcase sender)
4183                       (downcase (message-make-sender))))
4184                 (string-equal
4185                  (downcase (cadr (mail-extract-address-components from)))
4186                  (downcase (cadr (mail-extract-address-components
4187                                   (message-make-from))))))
4188       (error "This article is not yours"))
4189     ;; Get a normal message buffer.
4190     (message-pop-to-buffer (message-buffer-name "supersede"))
4191     (insert-buffer-substring cur)
4192     (mime-to-mml)
4193     (message-narrow-to-head-1)
4194     ;; Remove unwanted headers.
4195     (when message-ignored-supersedes-headers
4196       (message-remove-header message-ignored-supersedes-headers t))
4197     (goto-char (point-min))
4198     (if (not (re-search-forward "^Message-ID: " nil t))
4199         (error "No Message-ID in this article")
4200       (replace-match "Supersedes: " t t))
4201     (goto-char (point-max))
4202     (insert mail-header-separator)
4203     (widen)
4204     (forward-line 1)))
4205
4206 ;;;###autoload
4207 (defun message-recover ()
4208   "Reread contents of current buffer from its last auto-save file."
4209   (interactive)
4210   (let ((file-name (make-auto-save-file-name)))
4211     (cond ((save-window-excursion
4212              (if (not (eq system-type 'vax-vms))
4213                  (with-output-to-temp-buffer "*Directory*"
4214                    (with-current-buffer standard-output
4215                      (fundamental-mode)) ; for Emacs 20.4+
4216                    (buffer-disable-undo standard-output)
4217                    (let ((default-directory "/"))
4218                      (call-process
4219                       "ls" nil standard-output nil "-l" file-name))))
4220              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
4221            (let ((buffer-read-only nil))
4222              (erase-buffer)
4223              (insert-file-contents file-name nil)))
4224           (t (error "message-recover cancelled")))))
4225
4226 ;;; Washing Subject:
4227
4228 (defun message-wash-subject (subject)
4229   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
4230   (with-temp-buffer
4231     (insert-string subject)
4232     (goto-char (point-min))
4233     ;; strip Re/Fwd stuff off the beginning
4234     (while (re-search-forward
4235             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
4236       (replace-match ""))
4237
4238     ;; and gnus-style forwards [foo@bar.com] subject
4239     (goto-char (point-min))
4240     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4241       (replace-match ""))
4242
4243     ;; and off the end
4244     (goto-char (point-max))
4245     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4246       (replace-match ""))
4247
4248     ;; and finally, any whitespace that was left-over
4249     (goto-char (point-min))
4250     (while (re-search-forward "^[ \t]+" nil t)
4251       (replace-match ""))
4252     (goto-char (point-max))
4253     (while (re-search-backward "[ \t]+$" nil t)
4254       (replace-match ""))
4255
4256     (buffer-string)))
4257
4258 ;;; Forwarding messages.
4259
4260 (defun message-forward-subject-author-subject (subject)
4261   "Generate a subject for a forwarded message.
4262 The form is: [Source] Subject, where if the original message was mail,
4263 Source is the sender, and if the original message was news, Source is
4264 the list of newsgroups is was posted to."
4265   (concat "["
4266           (or (message-fetch-field
4267                (if (message-news-p) "newsgroups" "from"))
4268               "(nowhere)")
4269           "] " subject))
4270
4271 (defun message-forward-subject-fwd (subject)
4272   "Generate a subject for a forwarded message.
4273 The form is: Fwd: Subject, where Subject is the original subject of
4274 the message."
4275   (concat "Fwd: " subject))
4276
4277 (defun message-make-forward-subject ()
4278   "Return a Subject header suitable for the message in the current buffer."
4279   (save-excursion
4280     (save-restriction
4281       (message-narrow-to-head-1)
4282       (let ((funcs message-make-forward-subject-function)
4283             (subject (message-fetch-field "Subject")))
4284         (setq subject
4285               (if subject
4286                   (mail-decode-encoded-word-string subject)
4287                 ""))
4288         (if message-wash-forwarded-subjects
4289             (setq subject (message-wash-subject subject)))
4290         ;; Make sure funcs is a list.
4291         (and funcs
4292              (not (listp funcs))
4293              (setq funcs (list funcs)))
4294         ;; Apply funcs in order, passing subject generated by previous
4295         ;; func to the next one.
4296         (while funcs
4297           (when (message-functionp (car funcs))
4298             (setq subject (funcall (car funcs) subject)))
4299           (setq funcs (cdr funcs)))
4300         subject))))
4301
4302 ;;;###autoload
4303 (defun message-forward (&optional news digest)
4304   "Forward the current message via mail.
4305 Optional NEWS will use news to forward instead of mail.
4306 Optional DIGEST will use digest to forward."
4307   (interactive "P")
4308   (let* ((cur (current-buffer))
4309          (subject (message-make-forward-subject))
4310          art-beg)
4311     (if news
4312         (message-news nil subject)
4313       (message-mail nil subject))
4314     ;; Put point where we want it before inserting the forwarded
4315     ;; message.
4316     (if message-forward-before-signature
4317         (message-goto-body)
4318       (goto-char (point-max)))
4319     (if message-forward-as-mime
4320         (if digest
4321             (insert "\n<#multipart type=digest>\n")
4322           (if message-forward-show-mml
4323               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4324             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4325       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4326     (let ((b (point)) e)
4327       (if digest
4328           (if message-forward-as-mime
4329               (insert-buffer-substring cur)
4330             (mml-insert-buffer cur))
4331         (if message-forward-show-mml
4332             (let ((target (current-buffer)) tmp)
4333               (with-temp-buffer
4334                 (mm-disable-multibyte) ;; Must copy buffer in unibyte mode
4335                 (setq tmp (current-buffer))
4336                 (set-buffer cur)
4337                 (mm-with-unibyte-current-buffer
4338                   (set-buffer tmp)
4339                   (insert-buffer-substring cur)
4340                   (set-buffer cur))
4341                 (set-buffer tmp)
4342                 (mm-enable-multibyte)
4343                 (mime-to-mml)
4344                 (goto-char (point-min))
4345                 (when (looking-at "From ")
4346                   (replace-match "X-From-Line: "))
4347                 (set-buffer target)
4348                 (insert-buffer-substring tmp)
4349                 (set-buffer tmp)))
4350           (save-restriction
4351             (narrow-to-region (point) (point))
4352             (mml-insert-buffer cur)
4353             (goto-char (point-min))
4354             (when (looking-at "From ")
4355               (replace-match "X-From-Line: "))
4356             (goto-char (point-max)))))
4357       (setq e (point))
4358       (if message-forward-as-mime
4359           (if digest
4360               (insert "<#/multipart>\n")
4361             (if message-forward-show-mml
4362                 (insert "<#/mml>\n")
4363               (insert "<#/part>\n")))
4364         (insert "\n-------------------- End of forwarded message --------------------\n"))
4365       (if (and digest message-forward-as-mime)
4366           (save-restriction
4367             (narrow-to-region b e)
4368             (goto-char b)
4369             (narrow-to-region (point) 
4370                               (or (search-forward "\n\n" nil t) (point)))
4371             (delete-region (point-min) (point-max)))
4372         (when (and (not current-prefix-arg)
4373                    message-forward-ignored-headers)
4374           (save-restriction
4375             (narrow-to-region b e)
4376             (goto-char b)
4377             (narrow-to-region (point) 
4378                               (or (search-forward "\n\n" nil t) (point)))
4379             (message-remove-header message-forward-ignored-headers t)))))
4380     (message-position-point)))
4381
4382 ;;;###autoload
4383 (defun message-resend (address)
4384   "Resend the current article to ADDRESS."
4385   (interactive
4386    (list (message-read-from-minibuffer "Resend message to: ")))
4387   (message "Resending message to %s..." address)
4388   (save-excursion
4389     (let ((cur (current-buffer))
4390           beg)
4391       ;; We first set up a normal mail buffer.
4392       (unless (message-mail-user-agent)
4393         (set-buffer (get-buffer-create " *message resend*"))
4394         (erase-buffer))
4395       (let ((message-this-is-mail t))
4396         (message-setup `((To . ,address))))
4397       ;; Insert our usual headers.
4398       (message-generate-headers '(From Date To))
4399       (message-narrow-to-headers)
4400       ;; Rename them all to "Resent-*".
4401       (while (re-search-forward "^[A-Za-z]" nil t)
4402         (forward-char -1)
4403         (insert "Resent-"))
4404       (widen)
4405       (forward-line)
4406       (delete-region (point) (point-max))
4407       (setq beg (point))
4408       ;; Insert the message to be resent.
4409       (insert-buffer-substring cur)
4410       (goto-char (point-min))
4411       (search-forward "\n\n")
4412       (forward-char -1)
4413       (save-restriction
4414         (narrow-to-region beg (point))
4415         (message-remove-header message-ignored-resent-headers t)
4416         (goto-char (point-max)))
4417       (insert mail-header-separator)
4418       ;; Rename all old ("Also-")Resent headers.
4419       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4420         (beginning-of-line)
4421         (insert "Also-"))
4422       ;; Quote any "From " lines at the beginning.
4423       (goto-char beg)
4424       (when (looking-at "From ")
4425         (replace-match "X-From-Line: "))
4426       ;; Send it.
4427       (let ((message-inhibit-body-encoding t)
4428             message-required-mail-headers)
4429         (message-send-mail))
4430       (kill-buffer (current-buffer)))
4431     (message "Resending message to %s...done" address)))
4432
4433 ;;;###autoload
4434 (defun message-bounce ()
4435   "Re-mail the current message.
4436 This only makes sense if the current message is a bounce message that
4437 contains some mail you have written which has been bounced back to
4438 you."
4439   (interactive)
4440   (let ((handles (mm-dissect-buffer t))
4441         boundary)
4442     (message-pop-to-buffer (message-buffer-name "bounce"))
4443     (if (stringp (car handles))
4444         ;; This is a MIME bounce.
4445         (mm-insert-part (car (last handles)))
4446       ;; This is a non-MIME bounce, so we try to remove things
4447       ;; manually.
4448       (mm-insert-part handles)
4449       (undo-boundary)
4450       (goto-char (point-min))
4451       (search-forward "\n\n" nil t)
4452       (or (and (re-search-forward message-unsent-separator nil t)
4453                (forward-line 1))
4454           (re-search-forward "^Return-Path:.*\n" nil t))
4455       ;; We remove everything before the bounced mail.
4456       (delete-region
4457        (point-min)
4458        (if (re-search-forward "^[^ \n\t]+:" nil t)
4459            (match-beginning 0)
4460          (point))))
4461     (mm-enable-multibyte)
4462     (mime-to-mml)
4463     (save-restriction
4464       (message-narrow-to-head-1)
4465       (message-remove-header message-ignored-bounced-headers t)
4466       (goto-char (point-max))
4467       (insert mail-header-separator))
4468     (message-position-point)))
4469
4470 ;;;
4471 ;;; Interactive entry points for new message buffers.
4472 ;;;
4473
4474 ;;;###autoload
4475 (defun message-mail-other-window (&optional to subject)
4476   "Like `message-mail' command, but display mail buffer in another window."
4477   (interactive)
4478   (unless (message-mail-user-agent)
4479     (let ((pop-up-windows t)
4480           (special-display-buffer-names nil)
4481           (special-display-regexps nil)
4482           (same-window-buffer-names nil)
4483           (same-window-regexps nil))
4484       (message-pop-to-buffer (message-buffer-name "mail" to))))
4485   (let ((message-this-is-mail t))
4486     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4487                    nil nil 'switch-to-buffer-other-window)))
4488
4489 ;;;###autoload
4490 (defun message-mail-other-frame (&optional to subject)
4491   "Like `message-mail' command, but display mail buffer in another frame."
4492   (interactive)
4493   (unless (message-mail-user-agent)
4494     (let ((pop-up-frames t)
4495           (special-display-buffer-names nil)
4496           (special-display-regexps nil)
4497           (same-window-buffer-names nil)
4498           (same-window-regexps nil))
4499       (message-pop-to-buffer (message-buffer-name "mail" to))))
4500   (let ((message-this-is-mail t))
4501     (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))
4502                    nil nil 'switch-to-buffer-other-frame)))
4503
4504 ;;;###autoload
4505 (defun message-news-other-window (&optional newsgroups subject)
4506   "Start editing a news article to be sent."
4507   (interactive)
4508   (let ((pop-up-windows t)
4509         (special-display-buffer-names nil)
4510         (special-display-regexps nil)
4511         (same-window-buffer-names nil)
4512         (same-window-regexps nil))
4513     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4514   (let ((message-this-is-news t))
4515     (message-setup `((Newsgroups . ,(or newsgroups ""))
4516                      (Subject . ,(or subject ""))))))
4517
4518 ;;;###autoload
4519 (defun message-news-other-frame (&optional newsgroups subject)
4520   "Start editing a news article to be sent."
4521   (interactive)
4522   (let ((pop-up-frames t)
4523         (special-display-buffer-names nil)
4524         (special-display-regexps nil)
4525         (same-window-buffer-names nil)
4526         (same-window-regexps nil))
4527     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4528   (let ((message-this-is-news t))
4529     (message-setup `((Newsgroups . ,(or newsgroups ""))
4530                      (Subject . ,(or subject ""))))))
4531
4532 ;;; underline.el
4533
4534 ;; This code should be moved to underline.el (from which it is stolen).
4535
4536 ;;;###autoload
4537 (defun bold-region (start end)
4538   "Bold all nonblank characters in the region.
4539 Works by overstriking characters.
4540 Called from program, takes two arguments START and END
4541 which specify the range to operate on."
4542   (interactive "r")
4543   (save-excursion
4544     (let ((end1 (make-marker)))
4545       (move-marker end1 (max start end))
4546       (goto-char (min start end))
4547       (while (< (point) end1)
4548         (or (looking-at "[_\^@- ]")
4549             (insert (char-after) "\b"))
4550         (forward-char 1)))))
4551
4552 ;;;###autoload
4553 (defun unbold-region (start end)
4554   "Remove all boldness (overstruck characters) in the region.
4555 Called from program, takes two arguments START and END
4556 which specify the range to operate on."
4557   (interactive "r")
4558   (save-excursion
4559     (let ((end1 (make-marker)))
4560       (move-marker end1 (max start end))
4561       (goto-char (min start end))
4562       (while (re-search-forward "\b" end1 t)
4563         (if (eq (char-after) (char-after (- (point) 2)))
4564             (delete-char -2))))))
4565
4566 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4567
4568 ;; Support for toolbar
4569 (eval-when-compile 
4570   (defvar tool-bar-map)
4571   (defvar tool-bar-mode))
4572
4573 (defun message-tool-bar-map ()
4574   (or message-tool-bar-map
4575       (setq message-tool-bar-map
4576             (and (fboundp 'tool-bar-add-item-from-menu)
4577                  tool-bar-mode
4578                  (let ((tool-bar-map (copy-keymap tool-bar-map))
4579                        (load-path (mm-image-load-path)))
4580                    ;; Zap some items which aren't so relevant and take
4581                    ;; up space.
4582                    (dolist (key '(print-buffer kill-buffer save-buffer 
4583                                                write-file dired open-file))
4584                      (define-key tool-bar-map (vector key) nil))
4585                    (tool-bar-add-item-from-menu
4586                     'message-send-and-exit "mail_send" message-mode-map)
4587                    (tool-bar-add-item-from-menu
4588                     'message-kill-buffer "close" message-mode-map)
4589                    (tool-bar-add-item-from-menu
4590                     'message-dont-send "cancel" message-mode-map)
4591                    (tool-bar-add-item-from-menu
4592                     'mml-attach-file "attach" message-mode-map)
4593                    (tool-bar-add-item-from-menu
4594                     'ispell-message "spell" message-mode-map)
4595                    tool-bar-map)))))
4596
4597 ;;; Group name completion.
4598
4599 (defvar message-newgroups-header-regexp
4600   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4601   "Regexp that match headers that lists groups.")
4602
4603 (defun message-tab ()
4604   "Expand group names in Newsgroups and Followup-To headers.
4605 Do a `tab-to-tab-stop' if not in those headers."
4606   (interactive)
4607   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4608         (mail-abbrev-in-expansion-header-p))
4609       (message-expand-group)
4610     (tab-to-tab-stop)))
4611
4612 (defun message-expand-group ()
4613   "Expand the group name under point."
4614   (let* ((b (save-excursion
4615               (save-restriction
4616                 (narrow-to-region
4617                  (save-excursion
4618                    (beginning-of-line)
4619                    (skip-chars-forward "^:")
4620                    (1+ (point)))
4621                  (point))
4622                 (skip-chars-backward "^, \t\n") (point))))
4623          (completion-ignore-case t)
4624          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4625                                             (point))))
4626          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4627          (completions (all-completions string hashtb))
4628          comp)
4629     (delete-region b (point))
4630     (cond
4631      ((= (length completions) 1)
4632       (if (string= (car completions) string)
4633           (progn
4634             (insert string)
4635             (message "Only matching group"))
4636         (insert (car completions))))
4637      ((and (setq comp (try-completion string hashtb))
4638            (not (string= comp string)))
4639       (insert comp))
4640      (t
4641       (insert string)
4642       (if (not comp)
4643           (message "No matching groups")
4644         (save-selected-window
4645           (pop-to-buffer "*Completions*")
4646           (buffer-disable-undo)
4647           (let ((buffer-read-only nil))
4648             (erase-buffer)
4649             (let ((standard-output (current-buffer)))
4650               (display-completion-list (sort completions 'string<)))
4651             (goto-char (point-min))
4652             (delete-region (point) (progn (forward-line 3) (point))))))))))
4653
4654 ;;; Help stuff.
4655
4656 (defun message-talkative-question (ask question show &rest text)
4657   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4658 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4659 The following arguments may contain lists of values."
4660   (if (and show
4661            (setq text (message-flatten-list text)))
4662       (save-window-excursion
4663         (save-excursion
4664           (with-output-to-temp-buffer " *MESSAGE information message*"
4665             (set-buffer " *MESSAGE information message*")
4666             (fundamental-mode)          ; for Emacs 20.4+
4667             (mapcar 'princ text)
4668             (goto-char (point-min))))
4669         (funcall ask question))
4670     (funcall ask question)))
4671
4672 (defun message-flatten-list (list)
4673   "Return a new, flat list that contains all elements of LIST.
4674
4675 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4676 => (1 2 3 4 5 6 7)"
4677   (cond ((consp list)
4678          (apply 'append (mapcar 'message-flatten-list list)))
4679         (list
4680          (list list))))
4681
4682 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4683   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4684 Then clone the local variables and values from the old buffer to the
4685 new one, cloning only the locals having a substring matching the
4686 regexp varstr."
4687   (let ((oldbuf (current-buffer)))
4688     (save-excursion
4689       (set-buffer (generate-new-buffer name))
4690       (message-clone-locals oldbuf varstr)
4691       (current-buffer))))
4692
4693 (defun message-clone-locals (buffer &optional varstr)
4694   "Clone the local variables from BUFFER to the current buffer."
4695   (let ((locals (save-excursion
4696                   (set-buffer buffer)
4697                   (buffer-local-variables)))
4698         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4699     (mapcar
4700      (lambda (local)
4701        (when (and (consp local)
4702                   (car local)
4703                   (string-match regexp (symbol-name (car local)))
4704                   (or (null varstr)
4705                       (string-match varstr (symbol-name (car local)))))
4706          (ignore-errors
4707            (set (make-local-variable (car local))
4708                 (cdr local)))))
4709      locals)))
4710
4711 ;;; Miscellaneous functions
4712
4713 (defsubst message-replace-chars-in-string (string from to)
4714   (mm-subst-char-in-string from to string))
4715
4716 ;;;
4717 ;;; MIME functions
4718 ;;;
4719
4720 (defvar message-inhibit-body-encoding nil)
4721
4722 (defun message-encode-message-body ()
4723   (unless message-inhibit-body-encoding 
4724     (let ((mail-parse-charset (or mail-parse-charset
4725                                   message-default-charset))
4726           (case-fold-search t)
4727           lines content-type-p)
4728       (message-goto-body)
4729       (save-restriction
4730         (narrow-to-region (point) (point-max))
4731         (let ((new (mml-generate-mime)))
4732           (when new
4733             (delete-region (point-min) (point-max))
4734             (insert new)
4735             (goto-char (point-min))
4736             (if (eq (aref new 0) ?\n)
4737                 (delete-char 1)
4738               (search-forward "\n\n")
4739               (setq lines (buffer-substring (point-min) (1- (point))))
4740               (delete-region (point-min) (point))))))
4741       (save-restriction
4742         (message-narrow-to-headers-or-head)
4743         (message-remove-header "Mime-Version")
4744         (goto-char (point-max))
4745         (insert "MIME-Version: 1.0\n")
4746         (when lines
4747           (insert lines))
4748         (setq content-type-p
4749               (re-search-backward "^Content-Type:" nil t)))
4750       (save-restriction
4751         (message-narrow-to-headers-or-head)
4752         (message-remove-first-header "Content-Type")
4753         (message-remove-first-header "Content-Transfer-Encoding"))
4754       ;; We always make sure that the message has a Content-Type header.
4755       ;; This is because some broken MTAs and MUAs get awfully confused
4756       ;; when confronted with a message with a MIME-Version header and
4757       ;; without a Content-Type header.  For instance, Solaris'
4758       ;; /usr/bin/mail.
4759       (unless content-type-p
4760         (goto-char (point-min))
4761         (re-search-forward "^MIME-Version:")
4762         (forward-line 1)
4763         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4764
4765 (defun message-read-from-minibuffer (prompt)
4766   "Read from the minibuffer while providing abbrev expansion."
4767   (if (fboundp 'mail-abbrevs-setup)
4768       (let ((mail-abbrev-mode-regexp "")
4769             (minibuffer-setup-hook 'mail-abbrevs-setup))
4770         (read-from-minibuffer prompt))
4771     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4772       (read-string prompt))))
4773
4774 (defun message-use-alternative-email-as-from ()
4775   (require 'mail-utils)
4776   (let* ((fields '("To" "Cc")) 
4777          (emails
4778           (split-string
4779            (mail-strip-quoted-names
4780             (mapconcat 'message-fetch-reply-field fields ","))
4781            "[ \f\t\n\r\v,]+"))
4782          email)
4783     (while emails
4784       (if (string-match message-alternative-emails (car emails))
4785           (setq email (car emails)
4786                 emails nil))
4787       (pop emails))
4788     (unless (or (not email) (equal email user-mail-address))
4789       (goto-char (point-max))
4790       (insert "From: " email "\n"))))
4791
4792 (defun message-options-get (symbol)
4793   (cdr (assq symbol message-options)))
4794
4795 (defun message-options-set (symbol value)
4796   (let ((the-cons (assq symbol message-options)))
4797     (if the-cons
4798         (if value 
4799             (setcdr the-cons value)
4800           (setq message-options (delq the-cons message-options)))
4801       (and value
4802            (push (cons symbol value) message-options))))
4803   value)
4804
4805 (defun message-options-set-recipient ()
4806   (save-restriction
4807     (message-narrow-to-headers-or-head)
4808     (message-options-set 'message-sender
4809                          (mail-strip-quoted-names 
4810                           (message-fetch-field "from")))
4811     (message-options-set 'message-recipients
4812                           (mail-strip-quoted-names 
4813                            (message-fetch-field "to")))))
4814
4815 (when (featurep 'xemacs)
4816   (require 'messagexmas)
4817   (message-xmas-redefine))
4818
4819 (provide 'message)
4820
4821 (run-hooks 'message-load-hook)
4822
4823 ;; Local Variables:
4824 ;; coding: iso-8859-1
4825 ;; End:
4826
4827 ;;; message.el ends here