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