2000-10-03 Katsumi Yamaoka <yamaoka@jpl.org>
[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 'paragraph-separate)
1468   (make-local-variable 'paragraph-start)
1469   ;; `-- ' precedes the signature.  `-----' appears at the start of the
1470   ;; lines that delimit forwarded messages.
1471   ;; Lines containing just >= 3 dashes, perhaps after whitespace,
1472   ;; are also sometimes used and should be separators.
1473   (setq paragraph-start
1474         (concat (regexp-quote mail-header-separator)
1475                 "$\\|[ \t]*[a-z0-9A-Z]*>+[ \t]*$\\|[ \t]*$\\|"
1476                 "-- $\\|---+$\\|"
1477                 page-delimiter
1478                 ;;!!! Uhm... shurely this can't be right?
1479                 "[> " (regexp-quote message-yank-prefix) "]+$"))
1480   (setq paragraph-separate paragraph-start)
1481   (make-local-variable 'message-reply-headers)
1482   (setq message-reply-headers nil)
1483   (make-local-variable 'message-newsreader)
1484   (make-local-variable 'message-mailer)
1485   (make-local-variable 'message-post-method)
1486   (set (make-local-variable 'message-sent-message-via) nil)
1487   (set (make-local-variable 'message-checksum) nil)
1488   (set (make-local-variable 'message-mime-part) 0)
1489   ;;(when (fboundp 'mail-hist-define-keys)
1490   ;;  (mail-hist-define-keys))
1491   (if (featurep 'xemacs)
1492       (message-setup-toolbar)
1493     (set (make-local-variable 'font-lock-defaults)
1494          '(message-font-lock-keywords t)))
1495   (easy-menu-add message-mode-menu message-mode-map)
1496   (easy-menu-add message-mode-field-menu message-mode-map)
1497   ;; Allow mail alias things.
1498   (when (eq message-mail-alias-type 'abbrev)
1499     (if (fboundp 'mail-abbrevs-setup)
1500         (mail-abbrevs-setup)
1501       (mail-aliases-setup)))
1502   (message-set-auto-save-file-name)
1503   (make-local-variable 'adaptive-fill-regexp)
1504   (setq adaptive-fill-regexp
1505         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|" adaptive-fill-regexp))
1506   (unless (boundp 'adaptive-fill-first-line-regexp)
1507     (setq adaptive-fill-first-line-regexp nil))
1508   (make-local-variable 'adaptive-fill-first-line-regexp)
1509   (setq adaptive-fill-first-line-regexp
1510         (concat "[ \t]*[-a-z0-9A-Z]*\\(>[ \t]*\\)+[ \t]*\\|"
1511                 adaptive-fill-first-line-regexp))
1512   (make-local-variable 'auto-fill-inhibit-regexp)
1513   (setq auto-fill-inhibit-regexp "^[A-Z][^: \n\t]+:")
1514   (mm-enable-multibyte)
1515   (make-local-variable 'indent-tabs-mode) ;Turn off tabs for indentation.
1516   (setq indent-tabs-mode nil)
1517   (mml-mode)
1518   (run-hooks 'text-mode-hook 'message-mode-hook))
1519
1520 \f
1521
1522 ;;;
1523 ;;; Message mode commands
1524 ;;;
1525
1526 ;;; Movement commands
1527
1528 (defun message-goto-to ()
1529   "Move point to the To header."
1530   (interactive)
1531   (message-position-on-field "To"))
1532
1533 (defun message-goto-subject ()
1534   "Move point to the Subject header."
1535   (interactive)
1536   (message-position-on-field "Subject"))
1537
1538 (defun message-goto-cc ()
1539   "Move point to the Cc header."
1540   (interactive)
1541   (message-position-on-field "Cc" "To"))
1542
1543 (defun message-goto-bcc ()
1544   "Move point to the Bcc  header."
1545   (interactive)
1546   (message-position-on-field "Bcc" "Cc" "To"))
1547
1548 (defun message-goto-fcc ()
1549   "Move point to the Fcc header."
1550   (interactive)
1551   (message-position-on-field "Fcc" "To" "Newsgroups"))
1552
1553 (defun message-goto-reply-to ()
1554   "Move point to the Reply-To header."
1555   (interactive)
1556   (message-position-on-field "Reply-To" "Subject"))
1557
1558 (defun message-goto-newsgroups ()
1559   "Move point to the Newsgroups header."
1560   (interactive)
1561   (message-position-on-field "Newsgroups"))
1562
1563 (defun message-goto-distribution ()
1564   "Move point to the Distribution header."
1565   (interactive)
1566   (message-position-on-field "Distribution"))
1567
1568 (defun message-goto-followup-to ()
1569   "Move point to the Followup-To header."
1570   (interactive)
1571   (message-position-on-field "Followup-To" "Newsgroups"))
1572
1573 (defun message-goto-keywords ()
1574   "Move point to the Keywords header."
1575   (interactive)
1576   (message-position-on-field "Keywords" "Subject"))
1577
1578 (defun message-goto-summary ()
1579   "Move point to the Summary header."
1580   (interactive)
1581   (message-position-on-field "Summary" "Subject"))
1582
1583 (defun message-goto-body ()
1584   "Move point to the beginning of the message body."
1585   (interactive)
1586   (if (looking-at "[ \t]*\n") (expand-abbrev))
1587   (goto-char (point-min))
1588   (or (search-forward (concat "\n" mail-header-separator "\n") nil t)
1589       (search-forward "\n\n" nil t)))
1590
1591 (defun message-goto-eoh ()
1592   "Move point to the end of the headers."
1593   (interactive)
1594   (message-goto-body)
1595   (forward-line -1))
1596
1597 (defun message-goto-signature ()
1598   "Move point to the beginning of the message signature.
1599 If there is no signature in the article, go to the end and
1600 return nil."
1601   (interactive)
1602   (goto-char (point-min))
1603   (if (re-search-forward message-signature-separator nil t)
1604       (forward-line 1)
1605     (goto-char (point-max))
1606     nil))
1607
1608 \f
1609
1610 (defun message-insert-to (&optional force)
1611   "Insert a To header that points to the author of the article being replied to.
1612 If the original author requested not to be sent mail, the function signals
1613 an error.
1614 With the prefix argument FORCE, insert the header anyway."
1615   (interactive "P")
1616   (let ((co (message-fetch-reply-field "mail-copies-to")))
1617     (when (and (null force)
1618                co
1619                (or (equal (downcase co) "never")
1620                    (equal (downcase co) "nobody")))
1621       (error "The user has requested not to have copies sent via mail")))
1622   (when (and (message-position-on-field "To")
1623              (mail-fetch-field "to")
1624              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1625     (insert ", "))
1626   (insert (or (message-fetch-reply-field "reply-to")
1627               (message-fetch-reply-field "from") "")))
1628
1629 (defun message-widen-reply ()
1630   "Widen the reply to include maximum recipients."
1631   (interactive)
1632   (let ((follow-to
1633          (and message-reply-buffer
1634               (buffer-name message-reply-buffer)
1635               (save-excursion
1636                 (set-buffer message-reply-buffer)
1637                 (message-get-reply-headers t)))))
1638     (save-excursion
1639       (save-restriction
1640         (message-narrow-to-headers)
1641         (dolist (elem follow-to)
1642           (message-remove-header (symbol-name (car elem)))
1643           (goto-char (point-min))
1644           (insert (symbol-name (car elem)) ": "
1645                   (cdr elem) "\n"))))))
1646
1647 (defun message-insert-newsgroups ()
1648   "Insert the Newsgroups header from the article being replied to."
1649   (interactive)
1650   (when (and (message-position-on-field "Newsgroups")
1651              (mail-fetch-field "newsgroups")
1652              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1653     (insert ","))
1654   (insert (or (message-fetch-reply-field "newsgroups") "")))
1655
1656 \f
1657
1658 ;;; Various commands
1659
1660 (defun message-delete-not-region (beg end)
1661   "Delete everything in the body of the current message that is outside of the region."
1662   (interactive "r")
1663   (save-excursion
1664     (goto-char end)
1665     (delete-region (point) (if (not (message-goto-signature))
1666                                (point)
1667                              (forward-line -2)
1668                              (point)))
1669     (insert "\n")
1670     (goto-char beg)
1671     (delete-region beg (progn (message-goto-body)
1672                               (forward-line 2)
1673                               (point))))
1674   (when (message-goto-signature)
1675     (forward-line -2)))
1676
1677 (defun message-kill-to-signature ()
1678   "Deletes all text up to the signature."
1679   (interactive)
1680   (let ((point (point)))
1681     (message-goto-signature)
1682     (unless (eobp)
1683       (forward-line -2))
1684     (kill-region point (point))
1685     (unless (bolp)
1686       (insert "\n"))))
1687
1688 (defun message-newline-and-reformat ()
1689   "Insert four newlines, and then reformat if inside quoted text."
1690   (interactive)
1691   (let ((prefix "[]>»|:}+ \t]*")
1692         (supercite-thing "[-._a-zA-Z0-9]*[>]+[ \t]*")
1693         quoted point)
1694     (unless (bolp)
1695       (save-excursion
1696         (beginning-of-line)
1697         (when (looking-at (concat prefix
1698                                   supercite-thing))
1699           (setq quoted (match-string 0))))
1700       (insert "\n"))
1701     (setq point (point))
1702     (insert "\n\n\n")
1703     (delete-region (point) (re-search-forward "[ \t]*"))
1704     (when quoted
1705       (insert quoted))
1706     (fill-paragraph nil)
1707     (goto-char point)
1708     (forward-line 1)))
1709
1710 (defun message-insert-signature (&optional force)
1711   "Insert a signature.  See documentation for the `message-signature' variable."
1712   (interactive (list 0))
1713   (let* ((signature
1714           (cond
1715            ((and (null message-signature)
1716                  (eq force 0))
1717             (save-excursion
1718               (goto-char (point-max))
1719               (not (re-search-backward message-signature-separator nil t))))
1720            ((and (null message-signature)
1721                  force)
1722             t)
1723            ((message-functionp message-signature)
1724             (funcall message-signature))
1725            ((listp message-signature)
1726             (eval message-signature))
1727            (t message-signature)))
1728          (signature
1729           (cond ((stringp signature)
1730                  signature)
1731                 ((and (eq t signature)
1732                       message-signature-file
1733                       (file-exists-p message-signature-file))
1734                  signature))))
1735     (when signature
1736       (goto-char (point-max))
1737       ;; Insert the signature.
1738       (unless (bolp)
1739         (insert "\n"))
1740       (insert "\n-- \n")
1741       (if (eq signature t)
1742           (insert-file-contents message-signature-file)
1743         (insert signature))
1744       (goto-char (point-max))
1745       (or (bolp) (insert "\n")))))
1746
1747 (defun message-elide-region (b e)
1748   "Elide the text between point and mark.
1749 An ellipsis (from `message-elide-ellipsis') will be inserted where the
1750 text was killed."
1751   (interactive "r")
1752   (kill-region b e)
1753   (insert message-elide-ellipsis))
1754
1755 (defvar message-caesar-translation-table nil)
1756
1757 (defun message-caesar-region (b e &optional n)
1758   "Caesar rotation of region by N, default 13, for decrypting netnews."
1759   (interactive
1760    (list
1761     (min (point) (or (mark t) (point)))
1762     (max (point) (or (mark t) (point)))
1763     (when current-prefix-arg
1764       (prefix-numeric-value current-prefix-arg))))
1765
1766   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1767   (unless (or (zerop n)                 ; no action needed for a rot of 0
1768               (= b e))                  ; no region to rotate
1769     ;; We build the table, if necessary.
1770     (when (or (not message-caesar-translation-table)
1771               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1772       (setq message-caesar-translation-table
1773             (message-make-caesar-translation-table n)))
1774     (translate-region b e message-caesar-translation-table)))
1775
1776 (defun message-make-caesar-translation-table (n)
1777   "Create a rot table with offset N."
1778   (let ((i -1)
1779         (table (make-string 256 0)))
1780     (while (< (incf i) 256)
1781       (aset table i i))
1782     (concat
1783      (substring table 0 ?A)
1784      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1785      (substring table ?A (+ ?A n))
1786      (substring table (+ ?A 26) ?a)
1787      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1788      (substring table ?a (+ ?a n))
1789      (substring table (+ ?a 26) 255))))
1790
1791 (defun message-caesar-buffer-body (&optional rotnum)
1792   "Caesar rotates all letters in the current buffer by 13 places.
1793 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1794 With prefix arg, specifies the number of places to rotate each letter forward.
1795 Mail and USENET news headers are not rotated."
1796   (interactive (if current-prefix-arg
1797                    (list (prefix-numeric-value current-prefix-arg))
1798                  (list nil)))
1799   (save-excursion
1800     (save-restriction
1801       (when (message-goto-body)
1802         (narrow-to-region (point) (point-max)))
1803       (message-caesar-region (point-min) (point-max) rotnum))))
1804
1805 (defun message-pipe-buffer-body (program)
1806   "Pipe the message body in the current buffer through PROGRAM."
1807   (save-excursion
1808     (save-restriction
1809       (when (message-goto-body)
1810         (narrow-to-region (point) (point-max)))
1811       (shell-command-on-region
1812        (point-min) (point-max) program nil t))))
1813
1814 (defun message-rename-buffer (&optional enter-string)
1815   "Rename the *message* buffer to \"*message* RECIPIENT\".
1816 If the function is run with a prefix, it will ask for a new buffer
1817 name, rather than giving an automatic name."
1818   (interactive "Pbuffer name: ")
1819   (save-excursion
1820     (save-restriction
1821       (goto-char (point-min))
1822       (narrow-to-region (point)
1823                         (search-forward mail-header-separator nil 'end))
1824       (let* ((mail-to (or
1825                        (if (message-news-p) (message-fetch-field "Newsgroups")
1826                          (message-fetch-field "To"))
1827                        ""))
1828              (mail-trimmed-to
1829               (if (string-match "," mail-to)
1830                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1831                 mail-to))
1832              (name-default (concat "*message* " mail-trimmed-to))
1833              (name (if enter-string
1834                        (read-string "New buffer name: " name-default)
1835                      name-default)))
1836         (rename-buffer name t)))))
1837
1838 (defun message-fill-yanked-message (&optional justifyp)
1839   "Fill the paragraphs of a message yanked into this one.
1840 Numeric argument means justify as well."
1841   (interactive "P")
1842   (save-excursion
1843     (goto-char (point-min))
1844     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1845     (let ((fill-prefix message-yank-prefix))
1846       (fill-individual-paragraphs (point) (point-max) justifyp))))
1847
1848 (defun message-indent-citation ()
1849   "Modify text just inserted from a message to be cited.
1850 The inserted text should be the region.
1851 When this function returns, the region is again around the modified text.
1852
1853 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1854 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1855   (let ((start (point)))
1856     ;; Remove unwanted headers.
1857     (when message-ignored-cited-headers
1858       (let (all-removed)
1859         (save-restriction
1860           (narrow-to-region
1861            (goto-char start)
1862            (if (search-forward "\n\n" nil t)
1863                (1- (point))
1864              (point)))
1865           (message-remove-header message-ignored-cited-headers t)
1866           (when (= (point-min) (point-max))
1867             (setq all-removed t))
1868           (goto-char (point-max)))
1869         (if all-removed
1870             (goto-char start)
1871           (forward-line 1))))
1872     ;; Delete blank lines at the start of the buffer.
1873     (while (and (point-min)
1874                 (eolp)
1875                 (not (eobp)))
1876       (message-delete-line))
1877     ;; Delete blank lines at the end of the buffer.
1878     (goto-char (point-max))
1879     (unless (eolp)
1880       (insert "\n"))
1881     (while (and (zerop (forward-line -1))
1882                 (looking-at "$"))
1883       (message-delete-line))
1884     ;; Do the indentation.
1885     (if (null message-yank-prefix)
1886         (indent-rigidly start (mark t) message-indentation-spaces)
1887       (save-excursion
1888         (goto-char start)
1889         (while (< (point) (mark t))
1890           (insert message-yank-prefix)
1891           (forward-line 1))))
1892     (goto-char start)))
1893
1894 (defun message-yank-original (&optional arg)
1895   "Insert the message being replied to, if any.
1896 Puts point before the text and mark after.
1897 Normally indents each nonblank line ARG spaces (default 3).  However,
1898 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1899
1900 This function uses `message-cite-function' to do the actual citing.
1901
1902 Just \\[universal-argument] as argument means don't indent, insert no
1903 prefix, and don't delete any headers."
1904   (interactive "P")
1905   (let ((modified (buffer-modified-p)))
1906     (when (and message-reply-buffer
1907                message-cite-function)
1908       (delete-windows-on message-reply-buffer t)
1909       (insert-buffer message-reply-buffer)
1910       (funcall message-cite-function)
1911       (message-exchange-point-and-mark)
1912       (unless (bolp)
1913         (insert ?\n))
1914       (unless modified
1915         (setq message-checksum (message-checksum))))))
1916
1917 (defun message-yank-buffer (buffer)
1918   "Insert BUFFER into the current buffer and quote it."
1919   (interactive "bYank buffer: ")
1920   (let ((message-reply-buffer buffer))
1921     (save-window-excursion
1922       (message-yank-original))))
1923
1924 (defun message-buffers ()
1925   "Return a list of active message buffers."
1926   (let (buffers)
1927     (save-excursion
1928       (dolist (buffer (buffer-list t))
1929         (set-buffer buffer)
1930         (when (and (eq major-mode 'message-mode)
1931                    (null message-sent-message-via))
1932           (push (buffer-name buffer) buffers))))
1933     (nreverse buffers)))
1934
1935 (defun message-cite-original-without-signature ()
1936   "Cite function in the standard Message manner."
1937   (let ((start (point))
1938         (end (mark t))
1939         (functions
1940          (when message-indent-citation-function
1941            (if (listp message-indent-citation-function)
1942                message-indent-citation-function
1943              (list message-indent-citation-function)))))
1944     (mml-quote-region start end)
1945     ;; Allow undoing.
1946     (undo-boundary)
1947     (goto-char end)
1948     (when (re-search-backward message-signature-separator start t)
1949       ;; Also peel off any blank lines before the signature.
1950       (forward-line -1)
1951       (while (looking-at "^[ \t]*$")
1952         (forward-line -1))
1953       (forward-line 1)
1954       (delete-region (point) end))
1955     (goto-char start)
1956     (while functions
1957       (funcall (pop functions)))
1958     (when message-citation-line-function
1959       (unless (bolp)
1960         (insert "\n"))
1961       (funcall message-citation-line-function))))
1962
1963 (defvar mail-citation-hook)             ;Compiler directive
1964 (defun message-cite-original ()
1965   "Cite function in the standard Message manner."
1966   (if (and (boundp 'mail-citation-hook)
1967            mail-citation-hook)
1968       (run-hooks 'mail-citation-hook)
1969     (let ((start (point))
1970           (end (mark t))
1971           (functions
1972            (when message-indent-citation-function
1973              (if (listp message-indent-citation-function)
1974                  message-indent-citation-function
1975                (list message-indent-citation-function)))))
1976       (mml-quote-region start end)
1977       (goto-char start)
1978       (while functions
1979         (funcall (pop functions)))
1980       (when message-citation-line-function
1981         (unless (bolp)
1982           (insert "\n"))
1983         (funcall message-citation-line-function)))))
1984
1985 (defun message-insert-citation-line ()
1986   "Function that inserts a simple citation line."
1987   (when message-reply-headers
1988     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1989
1990 (defun message-position-on-field (header &rest afters)
1991   (let ((case-fold-search t))
1992     (save-restriction
1993       (narrow-to-region
1994        (goto-char (point-min))
1995        (progn
1996          (re-search-forward
1997           (concat "^" (regexp-quote mail-header-separator) "$"))
1998          (match-beginning 0)))
1999       (goto-char (point-min))
2000       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
2001           (progn
2002             (re-search-forward "^[^ \t]" nil 'move)
2003             (beginning-of-line)
2004             (skip-chars-backward "\n")
2005             t)
2006         (while (and afters
2007                     (not (re-search-forward
2008                           (concat "^" (regexp-quote (car afters)) ":")
2009                           nil t)))
2010           (pop afters))
2011         (when afters
2012           (re-search-forward "^[^ \t]" nil 'move)
2013           (beginning-of-line))
2014         (insert header ": \n")
2015         (forward-char -1)
2016         nil))))
2017
2018 (defun message-remove-signature ()
2019   "Remove the signature from the text between point and mark.
2020 The text will also be indented the normal way."
2021   (save-excursion
2022     (let ((start (point))
2023           mark)
2024       (if (not (re-search-forward message-signature-separator (mark t) t))
2025           ;; No signature here, so we just indent the cited text.
2026           (message-indent-citation)
2027         ;; Find the last non-empty line.
2028         (forward-line -1)
2029         (while (looking-at "[ \t]*$")
2030           (forward-line -1))
2031         (forward-line 1)
2032         (setq mark (set-marker (make-marker) (point)))
2033         (goto-char start)
2034         (message-indent-citation)
2035         ;; Enable undoing the deletion.
2036         (undo-boundary)
2037         (delete-region mark (mark t))
2038         (set-marker mark nil)))))
2039
2040 \f
2041
2042 ;;;
2043 ;;; Sending messages
2044 ;;;
2045
2046 (defun message-send-and-exit (&optional arg)
2047   "Send message like `message-send', then, if no errors, exit from mail buffer."
2048   (interactive "P")
2049   (let ((buf (current-buffer))
2050         (actions message-exit-actions))
2051     (when (and (message-send arg)
2052                (buffer-name buf))
2053       (if message-kill-buffer-on-exit
2054           (kill-buffer buf)
2055         (bury-buffer buf)
2056         (when (eq buf (current-buffer))
2057           (message-bury buf)))
2058       (message-do-actions actions)
2059       t)))
2060
2061 (defun message-dont-send ()
2062   "Don't send the message you have been editing."
2063   (interactive)
2064   (set-buffer-modified-p t)
2065   (save-buffer)
2066   (let ((actions message-postpone-actions))
2067     (message-bury (current-buffer))
2068     (message-do-actions actions)))
2069
2070 (defun message-kill-buffer ()
2071   "Kill the current buffer."
2072   (interactive)
2073   (when (or (not (buffer-modified-p))
2074             (yes-or-no-p "Message modified; kill anyway? "))
2075     (let ((actions message-kill-actions))
2076       (setq buffer-file-name nil)
2077       (kill-buffer (current-buffer))
2078       (message-do-actions actions))))
2079
2080 (defun message-bury (buffer)
2081   "Bury this mail buffer."
2082   (let ((newbuf (other-buffer buffer)))
2083     (bury-buffer buffer)
2084     (if (and (fboundp 'frame-parameters)
2085              (cdr (assq 'dedicated (frame-parameters)))
2086              (not (null (delq (selected-frame) (visible-frame-list)))))
2087         (delete-frame (selected-frame))
2088       (switch-to-buffer newbuf))))
2089
2090 (defun message-send (&optional arg)
2091   "Send the message in the current buffer.
2092 If `message-interactive' is non-nil, wait for success indication or
2093 error messages, and inform user.
2094 Otherwise any failure is reported in a message back to the user from
2095 the mailer.
2096 The usage of ARG is defined by the instance that called Message.
2097 It should typically alter the sending method in some way or other."
2098   (interactive "P")
2099   ;; Make it possible to undo the coming changes.
2100   (undo-boundary)
2101   (let ((inhibit-read-only t))
2102     (put-text-property (point-min) (point-max) 'read-only nil))
2103   (message-fix-before-sending)
2104   (run-hooks 'message-send-hook)
2105   (message "Sending...")
2106   (let ((alist message-send-method-alist)
2107         (success t)
2108         elem sent)
2109     (while (and success
2110                 (setq elem (pop alist)))
2111       (when (funcall (cadr elem))
2112         (when (and (or (not (memq (car elem)
2113                                   message-sent-message-via))
2114                        (y-or-n-p
2115                         (format
2116                          "Already sent message via %s; resend? "
2117                          (car elem))))
2118                    (setq success (funcall (caddr elem) arg)))
2119           (setq sent t))))
2120     (unless (or sent (not success))
2121       (error "No methods specified to send by"))
2122     (when (and success sent)
2123       (message-do-fcc)
2124       (save-excursion
2125         (run-hooks 'message-sent-hook))
2126       (message "Sending...done")
2127       ;; Mark the buffer as unmodified and delete auto-save.
2128       (set-buffer-modified-p nil)
2129       (delete-auto-save-file-if-necessary t)
2130       (message-disassociate-draft)
2131       ;; Delete other mail buffers and stuff.
2132       (message-do-send-housekeeping)
2133       (message-do-actions message-send-actions)
2134       ;; Return success.
2135       t)))
2136
2137 (defun message-send-via-mail (arg)
2138   "Send the current message via mail."
2139   (message-send-mail arg))
2140
2141 (defun message-send-via-news (arg)
2142   "Send the current message via news."
2143   (funcall message-send-news-function arg))
2144
2145 (defmacro message-check (type &rest forms)
2146   "Eval FORMS if TYPE is to be checked."
2147   `(or (message-check-element ,type)
2148        (save-excursion
2149          ,@forms)))
2150
2151 (put 'message-check 'lisp-indent-function 1)
2152 (put 'message-check 'edebug-form-spec '(form body))
2153
2154 (defun message-fix-before-sending ()
2155   "Do various things to make the message nice before sending it."
2156   ;; Make sure there's a newline at the end of the message.
2157   (goto-char (point-max))
2158   (unless (bolp)
2159     (insert "\n"))
2160   ;; Delete all invisible text.
2161   (message-check 'invisible-text
2162     (when (text-property-any (point-min) (point-max) 'invisible t)
2163       (put-text-property (point-min) (point-max) 'invisible nil)
2164       (unless (yes-or-no-p
2165                "Invisible text found and made visible; continue posting? ")
2166         (error "Invisible text found and made visible")))))
2167
2168 (defun message-add-action (action &rest types)
2169   "Add ACTION to be performed when doing an exit of type TYPES."
2170   (let (var)
2171     (while types
2172       (set (setq var (intern (format "message-%s-actions" (pop types))))
2173            (nconc (symbol-value var) (list action))))))
2174
2175 (defun message-do-actions (actions)
2176   "Perform all actions in ACTIONS."
2177   ;; Now perform actions on successful sending.
2178   (while actions
2179     (ignore-errors
2180       (cond
2181        ;; A simple function.
2182        ((message-functionp (car actions))
2183         (funcall (car actions)))
2184        ;; Something to be evaled.
2185        (t
2186         (eval (car actions)))))
2187     (pop actions)))
2188
2189 (defun message-send-mail-partially ()
2190   "Sendmail as message/partial."
2191   (let ((p (goto-char (point-min)))
2192         (tembuf (message-generate-new-buffer-clone-locals " message temp"))
2193         (curbuf (current-buffer))
2194         (id (message-make-message-id)) (n 1)
2195         plist total  header required-mail-headers)
2196     (while (not (eobp))
2197       (if (< (point-max) (+ p message-send-mail-partially-limit))
2198           (goto-char (point-max))
2199         (goto-char (+ p message-send-mail-partially-limit))
2200         (beginning-of-line)
2201         (if (<= (point) p) (forward-line 1))) ;; In case of bad message.
2202       (push p plist)
2203       (setq p (point)))
2204     (setq total (length plist))
2205     (push (point-max) plist)
2206     (setq plist (nreverse plist))
2207     (unwind-protect
2208         (save-excursion
2209           (setq p (pop plist))
2210           (while plist
2211             (set-buffer curbuf)
2212             (copy-to-buffer tembuf p (car plist))
2213             (set-buffer tembuf)
2214             (goto-char (point-min))
2215             (if header
2216                 (progn
2217                   (goto-char (point-min))
2218                   (narrow-to-region (point) (point))
2219                   (insert header))
2220               (message-goto-eoh)
2221               (setq header (buffer-substring (point-min) (point)))
2222               (goto-char (point-min))
2223               (narrow-to-region (point) (point))
2224               (insert header)
2225               (message-remove-header "Mime-Version")
2226               (message-remove-header "Content-Type")
2227               (message-remove-header "Content-Transfer-Encoding")
2228               (message-remove-header "Message-ID")
2229               (message-remove-header "Lines")
2230               (goto-char (point-max))
2231               (insert "Mime-Version: 1.0\n")
2232               (setq header (buffer-substring (point-min) (point-max))))
2233             (goto-char (point-max))
2234             (insert (format "Content-Type: message/partial; id=\"%s\"; number=%d; total=%d\n"
2235                             id n total))
2236             (let ((mail-header-separator ""))
2237               (when (memq 'Message-ID message-required-mail-headers)
2238                 (insert "Message-ID: " (message-make-message-id) "\n"))
2239               (when (memq 'Lines message-required-mail-headers)
2240                 (let ((mail-header-separator ""))
2241                   (insert "Lines: " (message-make-lines) "\n")))
2242               (message-goto-subject)
2243               (end-of-line)
2244               (insert (format " (%d/%d)" n total))
2245               (goto-char (point-max))
2246               (insert "\n")
2247               (widen)
2248               (mm-with-unibyte-current-buffer
2249                 (funcall message-send-mail-function)))
2250             (setq n (+ n 1))
2251             (setq p (pop plist))
2252             (erase-buffer)))
2253       (kill-buffer tembuf))))
2254
2255 (defun message-send-mail (&optional arg)
2256   (require 'mail-utils)
2257   (let* ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
2258          (case-fold-search nil)
2259          (news (message-news-p))
2260          (mailbuf (current-buffer))
2261          (message-this-is-mail t)
2262          (message-posting-charset
2263           (if (fboundp 'gnus-setup-posting-charset)
2264               (gnus-setup-posting-charset nil)
2265             message-posting-charset)))
2266     (save-restriction
2267       (message-narrow-to-headers)
2268       ;; Insert some headers.
2269       (let ((message-deletable-headers
2270              (if news nil message-deletable-headers)))
2271         (message-generate-headers message-required-mail-headers))
2272       ;; Let the user do all of the above.
2273       (run-hooks 'message-header-hook))
2274     (unwind-protect
2275         (save-excursion
2276           (set-buffer tembuf)
2277           (erase-buffer)
2278           ;; Avoid copying text props.
2279           (insert (format
2280                    "%s" (save-excursion
2281                           (set-buffer mailbuf)
2282                           (buffer-string))))
2283           ;; Remove some headers.
2284           (message-encode-message-body)
2285           (save-restriction
2286             (message-narrow-to-headers)
2287             ;; We (re)generate the Lines header.
2288             (when (memq 'Lines message-required-mail-headers)
2289               (message-generate-headers '(Lines)))
2290             ;; Remove some headers.
2291             (message-remove-header message-ignored-mail-headers t)
2292             (let ((mail-parse-charset message-default-charset))
2293               (mail-encode-encoded-word-buffer)))
2294           (goto-char (point-max))
2295           ;; require one newline at the end.
2296           (or (= (preceding-char) ?\n)
2297               (insert ?\n))
2298           (when 
2299               (save-restriction
2300                 (message-narrow-to-headers)
2301                 (and news
2302                      (or (message-fetch-field "cc")
2303                          (message-fetch-field "to"))
2304                      (string= "text/plain"
2305                               (car
2306                                (mail-header-parse-content-type
2307                                 (message-fetch-field "content-type"))))))
2308             (message-insert-courtesy-copy))
2309           (if (or (not message-send-mail-partially-limit)
2310                   (< (point-max) message-send-mail-partially-limit)
2311                   (not (y-or-n-p "The message size is too large, should it be sent partially?")))
2312               (mm-with-unibyte-current-buffer
2313                 (funcall message-send-mail-function))
2314             (message-send-mail-partially)))
2315       (kill-buffer tembuf))
2316     (set-buffer mailbuf)
2317     (push 'mail message-sent-message-via)))
2318
2319 (defun message-send-mail-with-sendmail ()
2320   "Send off the prepared buffer with sendmail."
2321   (let ((errbuf (if message-interactive
2322                     (message-generate-new-buffer-clone-locals
2323                      " sendmail errors")
2324                   0))
2325         resend-to-addresses delimline)
2326     (let ((case-fold-search t))
2327       (save-restriction
2328         (message-narrow-to-headers)
2329         (setq resend-to-addresses (message-fetch-field "resent-to")))
2330       ;; Change header-delimiter to be what sendmail expects.
2331       (goto-char (point-min))
2332       (re-search-forward
2333        (concat "^" (regexp-quote mail-header-separator) "\n"))
2334       (replace-match "\n")
2335       (backward-char 1)
2336       (setq delimline (point-marker))
2337       (run-hooks 'message-send-mail-hook)
2338       ;; Insert an extra newline if we need it to work around
2339       ;; Sun's bug that swallows newlines.
2340       (goto-char (1+ delimline))
2341       (when (eval message-mailer-swallows-blank-line)
2342         (newline))
2343       (when message-interactive
2344         (save-excursion
2345           (set-buffer errbuf)
2346           (erase-buffer))))
2347     (let ((default-directory "/")
2348           (coding-system-for-write message-send-coding-system))
2349       (apply 'call-process-region
2350              (append (list (point-min) (point-max)
2351                            (if (boundp 'sendmail-program)
2352                                sendmail-program
2353                              "/usr/lib/sendmail")
2354                            nil errbuf nil "-oi")
2355                      ;; Always specify who from,
2356                      ;; since some systems have broken sendmails.
2357                      ;; But some systems are more broken with -f, so
2358                      ;; we'll let users override this.
2359                      (if (null message-sendmail-f-is-evil)
2360                          (list "-f" (message-make-address)))
2361                      ;; These mean "report errors by mail"
2362                      ;; and "deliver in background".
2363                      (if (null message-interactive) '("-oem" "-odb"))
2364                      ;; Get the addresses from the message
2365                      ;; unless this is a resend.
2366                      ;; We must not do that for a resend
2367                      ;; because we would find the original addresses.
2368                      ;; For a resend, include the specific addresses.
2369                      (if resend-to-addresses
2370                          (list resend-to-addresses)
2371                        '("-t")))))
2372     (when message-interactive
2373       (save-excursion
2374         (set-buffer errbuf)
2375         (goto-char (point-min))
2376         (while (re-search-forward "\n\n* *" nil t)
2377           (replace-match "; "))
2378         (if (not (zerop (buffer-size)))
2379             (error "Sending...failed to %s"
2380                    (buffer-substring (point-min) (point-max)))))
2381       (when (bufferp errbuf)
2382         (kill-buffer errbuf)))))
2383
2384 (defun message-send-mail-with-qmail ()
2385   "Pass the prepared message buffer to qmail-inject.
2386 Refer to the documentation for the variable `message-send-mail-function'
2387 to find out how to use this."
2388   ;; replace the header delimiter with a blank line
2389   (goto-char (point-min))
2390   (re-search-forward
2391    (concat "^" (regexp-quote mail-header-separator) "\n"))
2392   (replace-match "\n")
2393   (run-hooks 'message-send-mail-hook)
2394   ;; send the message
2395   (case
2396       (let ((coding-system-for-write message-send-coding-system))
2397         (apply
2398          'call-process-region 1 (point-max) message-qmail-inject-program
2399          nil nil nil
2400          ;; qmail-inject's default behaviour is to look for addresses on the
2401          ;; command line; if there're none, it scans the headers.
2402          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2403          ;;
2404          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2405          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2406          ;; message from stdin.
2407          ;;
2408          ;; qmail also has the advantage of not having been raped by
2409          ;; various vendors, so we don't have to allow for that, either --
2410          ;; compare this with message-send-mail-with-sendmail and weep
2411          ;; for sendmail's lost innocence.
2412          ;;
2413          ;; all this is way cool coz it lets us keep the arguments entirely
2414          ;; free for -inject-arguments -- a big win for the user and for us
2415          ;; since we don't have to play that double-guessing game and the user
2416          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2417          message-qmail-inject-args))
2418     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2419     ;; we have to look at the retval instead
2420     (0 nil)
2421     (1   (error "qmail-inject reported permanent failure"))
2422     (111 (error "qmail-inject reported transient failure"))
2423     ;; should never happen
2424     (t   (error "qmail-inject reported unknown failure"))))
2425
2426 (defun message-send-mail-with-mh ()
2427   "Send the prepared message buffer with mh."
2428   (let ((mh-previous-window-config nil)
2429         (name (mh-new-draft-name)))
2430     (setq buffer-file-name name)
2431     ;; MH wants to generate these headers itself.
2432     (when message-mh-deletable-headers
2433       (let ((headers message-mh-deletable-headers))
2434         (while headers
2435           (goto-char (point-min))
2436           (and (re-search-forward
2437                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2438                (message-delete-line))
2439           (pop headers))))
2440     (run-hooks 'message-send-mail-hook)
2441     ;; Pass it on to mh.
2442     (mh-send-letter)))
2443
2444 (defun message-send-news (&optional arg)
2445   (let* ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2446          (case-fold-search nil)
2447          (method (if (message-functionp message-post-method)
2448                      (funcall message-post-method arg)
2449                    message-post-method))
2450          (group-name-charset (gnus-group-name-charset method ""))
2451          (rfc2047-header-encoding-alist
2452           (if group-name-charset
2453               (cons (cons "Newsgroups" group-name-charset)
2454                     rfc2047-header-encoding-alist)
2455             rfc2047-header-encoding-alist))
2456          (messbuf (current-buffer))
2457          (message-syntax-checks
2458           (if arg
2459               (cons '(existing-newsgroups . disabled)
2460                     message-syntax-checks)
2461             message-syntax-checks))
2462          (message-this-is-news t)
2463          (message-posting-charset (gnus-setup-posting-charset 
2464                                    (save-restriction
2465                                      (message-narrow-to-headers-or-head)
2466                                      (message-fetch-field "Newsgroups"))))
2467          result)
2468     (if (not (message-check-news-body-syntax))
2469         nil
2470       (save-restriction
2471         (message-narrow-to-headers)
2472         ;; Insert some headers.
2473         (message-generate-headers message-required-news-headers)
2474         ;; Let the user do all of the above.
2475         (run-hooks 'message-header-hook))
2476       (if group-name-charset
2477           (setq message-syntax-checks
2478               (cons '(valid-newsgroups . disabled)
2479                     message-syntax-checks)))
2480       (message-cleanup-headers)
2481       (if (not (message-check-news-syntax))
2482           nil
2483         (unwind-protect
2484             (save-excursion
2485               (set-buffer tembuf)
2486               (buffer-disable-undo)
2487               (erase-buffer)
2488               ;; Avoid copying text props.
2489               (insert (format
2490                        "%s" (save-excursion
2491                               (set-buffer messbuf)
2492                               (buffer-string))))
2493               (message-encode-message-body)
2494               ;; Remove some headers.
2495               (save-restriction
2496                 (message-narrow-to-headers)
2497                 ;; We (re)generate the Lines header.
2498                 (when (memq 'Lines message-required-mail-headers)
2499                   (message-generate-headers '(Lines)))
2500                 ;; Remove some headers.
2501                 (message-remove-header message-ignored-news-headers t)
2502                 (let ((mail-parse-charset message-default-charset))
2503                   (mail-encode-encoded-word-buffer)))
2504               (goto-char (point-max))
2505               ;; require one newline at the end.
2506               (or (= (preceding-char) ?\n)
2507                   (insert ?\n))
2508               (let ((case-fold-search t))
2509                 ;; Remove the delimiter.
2510                 (goto-char (point-min))
2511                 (re-search-forward
2512                  (concat "^" (regexp-quote mail-header-separator) "\n"))
2513                 (replace-match "\n")
2514                 (backward-char 1))
2515               (run-hooks 'message-send-news-hook)
2516               (gnus-open-server method)
2517               (setq result (let ((mail-header-separator ""))
2518                              (gnus-request-post method))))
2519           (kill-buffer tembuf))
2520         (set-buffer messbuf)
2521         (if result
2522             (push 'news message-sent-message-via)
2523           (message "Couldn't send message via news: %s"
2524                    (nnheader-get-report (car method)))
2525           nil)))))
2526
2527 ;;;
2528 ;;; Header generation & syntax checking.
2529 ;;;
2530
2531 (defun message-check-element (type)
2532   "Returns non-nil if this type is not to be checked."
2533   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2534       t
2535     (let ((able (assq type message-syntax-checks)))
2536       (and (consp able)
2537            (eq (cdr able) 'disabled)))))
2538
2539 (defun message-check-news-syntax ()
2540   "Check the syntax of the message."
2541   (save-excursion
2542     (save-restriction
2543       (widen)
2544       ;; We narrow to the headers and check them first.
2545       (save-excursion
2546         (save-restriction
2547           (message-narrow-to-headers)
2548           (message-check-news-header-syntax))))))
2549
2550 (defun message-check-news-header-syntax ()
2551   (and
2552    ;; Check Newsgroups header.
2553    (message-check 'newsgroups
2554      (let ((group (message-fetch-field "newsgroups")))
2555        (or
2556         (and group
2557              (not (string-match "\\`[ \t]*\\'" group)))
2558         (ignore
2559          (message
2560           "The newsgroups field is empty or missing.  Posting is denied.")))))
2561    ;; Check the Subject header.
2562    (message-check 'subject
2563      (let* ((case-fold-search t)
2564             (subject (message-fetch-field "subject")))
2565        (or
2566         (and subject
2567              (not (string-match "\\`[ \t]*\\'" subject)))
2568         (ignore
2569          (message
2570           "The subject field is empty or missing.  Posting is denied.")))))
2571    ;; Check for commands in Subject.
2572    (message-check 'subject-cmsg
2573      (if (string-match "^cmsg " (message-fetch-field "subject"))
2574          (y-or-n-p
2575           "The control code \"cmsg\" is in the subject.  Really post? ")
2576        t))
2577    ;; Check for multiple identical headers.
2578    (message-check 'multiple-headers
2579      (let (found)
2580        (while (and (not found)
2581                    (re-search-forward "^[^ \t:]+: " nil t))
2582          (save-excursion
2583            (or (re-search-forward
2584                 (concat "^"
2585                         (regexp-quote
2586                          (setq found
2587                                (buffer-substring
2588                                 (match-beginning 0) (- (match-end 0) 2))))
2589                         ":")
2590                 nil t)
2591                (setq found nil))))
2592        (if found
2593            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2594          t)))
2595    ;; Check for Version and Sendsys.
2596    (message-check 'sendsys
2597      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2598          (y-or-n-p
2599           (format "The article contains a %s command.  Really post? "
2600                   (buffer-substring (match-beginning 0)
2601                                     (1- (match-end 0)))))
2602        t))
2603    ;; See whether we can shorten Followup-To.
2604    (message-check 'shorten-followup-to
2605      (let ((newsgroups (message-fetch-field "newsgroups"))
2606            (followup-to (message-fetch-field "followup-to"))
2607            to)
2608        (when (and newsgroups
2609                   (string-match "," newsgroups)
2610                   (not followup-to)
2611                   (not
2612                    (zerop
2613                     (length
2614                      (setq to (completing-read
2615                                "Followups to: (default all groups) "
2616                                (mapcar (lambda (g) (list g))
2617                                        (cons "poster"
2618                                              (message-tokenize-header
2619                                               newsgroups)))))))))
2620          (goto-char (point-min))
2621          (insert "Followup-To: " to "\n"))
2622        t))
2623    ;; Check "Shoot me".
2624    (message-check 'shoot
2625      (if (re-search-forward
2626           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2627          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2628        t))
2629    ;; Check for Approved.
2630    (message-check 'approved
2631      (if (re-search-forward "^Approved:" nil t)
2632          (y-or-n-p "The article contains an Approved header.  Really post? ")
2633        t))
2634    ;; Check the Message-ID header.
2635    (message-check 'message-id
2636      (let* ((case-fold-search t)
2637             (message-id (message-fetch-field "message-id" t)))
2638        (or (not message-id)
2639            ;; Is there an @ in the ID?
2640            (and (string-match "@" message-id)
2641                 ;; Is there a dot in the ID?
2642                 (string-match "@[^.]*\\." message-id)
2643                 ;; Does the ID end with a dot?
2644                 (not (string-match "\\.>" message-id)))
2645            (y-or-n-p
2646             (format "The Message-ID looks strange: \"%s\".  Really post? "
2647                     message-id)))))
2648    ;; Check the Newsgroups & Followup-To headers.
2649    (message-check 'existing-newsgroups
2650      (let* ((case-fold-search t)
2651             (newsgroups (message-fetch-field "newsgroups"))
2652             (followup-to (message-fetch-field "followup-to"))
2653             (groups (message-tokenize-header
2654                      (if followup-to
2655                          (concat newsgroups "," followup-to)
2656                        newsgroups)))
2657             (hashtb (and (boundp 'gnus-active-hashtb)
2658                          gnus-active-hashtb))
2659             errors)
2660        (if (or (not hashtb)
2661                (not (boundp 'gnus-read-active-file))
2662                (not gnus-read-active-file)
2663                (eq gnus-read-active-file 'some))
2664            t
2665          (while groups
2666            (when (and (not (boundp (intern (car groups) hashtb)))
2667                       (not (equal (car groups) "poster")))
2668              (push (car groups) errors))
2669            (pop groups))
2670          (if (not errors)
2671              t
2672            (y-or-n-p
2673             (format
2674              "Really post to %s unknown group%s: %s "
2675              (if (= (length errors) 1) "this" "these")
2676              (if (= (length errors) 1) "" "s")
2677              (mapconcat 'identity errors ", ")))))))
2678    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2679    (message-check 'valid-newsgroups
2680      (let ((case-fold-search t)
2681            (headers '("Newsgroups" "Followup-To"))
2682            header error)
2683        (while (and headers (not error))
2684          (when (setq header (mail-fetch-field (car headers)))
2685            (if (or
2686                 (not
2687                  (string-match
2688                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2689                   header))
2690                 (memq
2691                  nil (mapcar
2692                       (lambda (g)
2693                         (not (string-match "\\.\\'\\|\\.\\." g)))
2694                       (message-tokenize-header header ","))))
2695                (setq error t)))
2696          (unless error
2697            (pop headers)))
2698        (if (not error)
2699            t
2700          (y-or-n-p
2701           (format "The %s header looks odd: \"%s\".  Really post? "
2702                   (car headers) header)))))
2703    (message-check 'repeated-newsgroups
2704      (let ((case-fold-search t)
2705            (headers '("Newsgroups" "Followup-To"))
2706            header error groups group)
2707        (while (and headers
2708                    (not error))
2709          (when (setq header (mail-fetch-field (pop headers)))
2710            (setq groups (message-tokenize-header header ","))
2711            (while (setq group (pop groups))
2712              (when (member group groups)
2713                (setq error group
2714                      groups nil)))))
2715        (if (not error)
2716            t
2717          (y-or-n-p
2718           (format "Group %s is repeated in headers.  Really post? " error)))))
2719    ;; Check the From header.
2720    (message-check 'from
2721      (let* ((case-fold-search t)
2722             (from (message-fetch-field "from"))
2723             ad)
2724        (cond
2725         ((not from)
2726          (message "There is no From line.  Posting is denied.")
2727          nil)
2728         ((or (not (string-match
2729                    "@[^\\.]*\\."
2730                    (setq ad (nth 1 (mail-extract-address-components
2731                                     from))))) ;larsi@ifi
2732              (string-match "\\.\\." ad) ;larsi@ifi..uio
2733              (string-match "@\\." ad)   ;larsi@.ifi.uio
2734              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2735              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2736              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2737          (message
2738           "Denied posting -- the From looks strange: \"%s\"." from)
2739          nil)
2740         (t t))))))
2741
2742 (defun message-check-news-body-syntax ()
2743   (and
2744    ;; Check for long lines.
2745    (message-check 'long-lines
2746      (goto-char (point-min))
2747      (re-search-forward
2748       (concat "^" (regexp-quote mail-header-separator) "$"))
2749      (while (and
2750              (progn
2751                (end-of-line)
2752                (< (current-column) 80))
2753              (zerop (forward-line 1))))
2754      (or (bolp)
2755          (eobp)
2756          (y-or-n-p
2757           "You have lines longer than 79 characters.  Really post? ")))
2758    ;; Check whether the article is empty.
2759    (message-check 'empty
2760      (goto-char (point-min))
2761      (re-search-forward
2762       (concat "^" (regexp-quote mail-header-separator) "$"))
2763      (forward-line 1)
2764      (let ((b (point)))
2765        (goto-char (point-max))
2766        (re-search-backward message-signature-separator nil t)
2767        (beginning-of-line)
2768        (or (re-search-backward "[^ \n\t]" b t)
2769            (y-or-n-p "Empty article.  Really post? "))))
2770    ;; Check for control characters.
2771    (message-check 'control-chars
2772      (if (re-search-forward "[\000-\007\013\015-\032\034-\037\200-\237]" nil t)
2773          (y-or-n-p
2774           "The article contains control characters.  Really post? ")
2775        t))
2776    ;; Check excessive size.
2777    (message-check 'size
2778      (if (> (buffer-size) 60000)
2779          (y-or-n-p
2780           (format "The article is %d octets long.  Really post? "
2781                   (buffer-size)))
2782        t))
2783    ;; Check whether any new text has been added.
2784    (message-check 'new-text
2785      (or
2786       (not message-checksum)
2787       (not (eq (message-checksum) message-checksum))
2788       (y-or-n-p
2789        "It looks like no new text has been added.  Really post? ")))
2790    ;; Check the length of the signature.
2791    (message-check 'signature
2792      (goto-char (point-max))
2793      (if (> (count-lines (point) (point-max)) 5)
2794          (y-or-n-p
2795           (format
2796            "Your .sig is %d lines; it should be max 4.  Really post? "
2797            (1- (count-lines (point) (point-max)))))
2798        t))
2799    ;; Ensure that text follows last quoted portion.
2800    (message-check 'quoting-style
2801      (goto-char (point-max))
2802      (let ((no-problem t))
2803        (when (search-backward-regexp "^>[^\n]*\n>" nil t)
2804          (setq no-problem nil)
2805          (while (not (eobp))
2806            (when (and (not (eolp)) (looking-at "[^> \t]"))
2807              (setq no-problem t))
2808            (forward-line)))
2809        (if no-problem
2810            t
2811          (y-or-n-p "Your text should follow quoted text.  Really post? "))))))
2812
2813 (defun message-checksum ()
2814   "Return a \"checksum\" for the current buffer."
2815   (let ((sum 0))
2816     (save-excursion
2817       (goto-char (point-min))
2818       (re-search-forward
2819        (concat "^" (regexp-quote mail-header-separator) "$"))
2820       (while (not (eobp))
2821         (when (not (looking-at "[ \t\n]"))
2822           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2823                             (char-after))))
2824         (forward-char 1)))
2825     sum))
2826
2827 (defun message-do-fcc ()
2828   "Process Fcc headers in the current buffer."
2829   (let ((case-fold-search t)
2830         (buf (current-buffer))
2831         list file)
2832     (save-excursion
2833       (set-buffer (get-buffer-create " *message temp*"))
2834       (erase-buffer)
2835       (insert-buffer-substring buf)
2836       (save-restriction
2837         (message-narrow-to-headers)
2838         (while (setq file (message-fetch-field "fcc"))
2839           (push file list)
2840           (message-remove-header "fcc" nil t)))
2841       (message-encode-message-body)
2842       (save-restriction
2843         (message-narrow-to-headers)
2844         (let ((mail-parse-charset message-default-charset)
2845               (rfc2047-header-encoding-alist
2846                (cons '("Newsgroups" . default)
2847                      rfc2047-header-encoding-alist)))
2848           (mail-encode-encoded-word-buffer)))
2849       (goto-char (point-min))
2850       (when (re-search-forward
2851              (concat "^" (regexp-quote mail-header-separator) "$")
2852              nil t)
2853         (replace-match "" t t ))
2854       ;; Process FCC operations.
2855       (while list
2856         (setq file (pop list))
2857         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2858             ;; Pipe the article to the program in question.
2859             (call-process-region (point-min) (point-max) shell-file-name
2860                                  nil nil nil shell-command-switch
2861                                  (match-string 1 file))
2862           ;; Save the article.
2863           (setq file (expand-file-name file))
2864           (unless (file-exists-p (file-name-directory file))
2865             (make-directory (file-name-directory file) t))
2866           (if (and message-fcc-handler-function
2867                    (not (eq message-fcc-handler-function 'rmail-output)))
2868               (funcall message-fcc-handler-function file)
2869             (if (and (file-readable-p file) (mail-file-babyl-p file))
2870                 (rmail-output file 1 nil t)
2871               (let ((mail-use-rfc822 t))
2872                 (rmail-output file 1 t t))))))
2873       (kill-buffer (current-buffer)))))
2874
2875 (defun message-output (filename)
2876   "Append this article to Unix/babyl mail file.."
2877   (if (and (file-readable-p filename)
2878            (mail-file-babyl-p filename))
2879       (gnus-output-to-rmail filename t)
2880     (gnus-output-to-mail filename t)))
2881
2882 (defun message-cleanup-headers ()
2883   "Do various automatic cleanups of the headers."
2884   ;; Remove empty lines in the header.
2885   (save-restriction
2886     (message-narrow-to-headers)
2887     ;; Remove blank lines.
2888     (while (re-search-forward "^[ \t]*\n" nil t)
2889       (replace-match "" t t))
2890
2891     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2892     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2893     ;; embedded line breaks.
2894     (goto-char (point-min))
2895     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2896       (save-restriction
2897         (narrow-to-region
2898          (point)
2899          (if (re-search-forward "^[^ \t]" nil t)
2900              (match-beginning 0)
2901            (forward-line 1)
2902            (point)))
2903         (goto-char (point-min))
2904         (while (re-search-forward "\n[ \t]+" nil t)
2905           (replace-match " " t t))      ;No line breaks (too confusing)
2906         (goto-char (point-min))
2907         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2908           (replace-match "," t t))
2909         (goto-char (point-min))
2910         ;; Remove trailing commas.
2911         (when (re-search-forward ",+$" nil t)
2912           (replace-match "" t t))))))
2913
2914 (defun message-make-date (&optional now)
2915   "Make a valid data header.
2916 If NOW, use that time instead."
2917   (let* ((now (or now (current-time)))
2918          (zone (nth 8 (decode-time now)))
2919          (sign "+"))
2920     (when (< zone 0)
2921       (setq sign "-")
2922       (setq zone (- zone)))
2923     (concat
2924      (format-time-string "%d" now)
2925      ;; The month name of the %b spec is locale-specific.  Pfff.
2926      (format " %s "
2927              (capitalize (car (rassoc (nth 4 (decode-time now))
2928                                       parse-time-months))))
2929      (format-time-string "%Y %H:%M:%S " now)
2930      ;; We do all of this because XEmacs doesn't have the %z spec.
2931      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
2932
2933 (defun message-make-message-id ()
2934   "Make a unique Message-ID."
2935   (concat "<" (message-unique-id)
2936           (let ((psubject (save-excursion (message-fetch-field "subject")))
2937                 (psupersedes
2938                  (save-excursion (message-fetch-field "supersedes"))))
2939             (if (or
2940                  (and message-reply-headers
2941                       (mail-header-references message-reply-headers)
2942                       (mail-header-subject message-reply-headers)
2943                       psubject
2944                       (mail-header-subject message-reply-headers)
2945                       (not (string=
2946                             (message-strip-subject-re
2947                              (mail-header-subject message-reply-headers))
2948                             (message-strip-subject-re psubject))))
2949                  (and psupersedes
2950                       (string-match "_-_@" psupersedes)))
2951                 "_-_" ""))
2952           "@" (message-make-fqdn) ">"))
2953
2954 (defvar message-unique-id-char nil)
2955
2956 ;; If you ever change this function, make sure the new version
2957 ;; cannot generate IDs that the old version could.
2958 ;; You might for example insert a "." somewhere (not next to another dot
2959 ;; or string boundary), or modify the "fsf" string.
2960 (defun message-unique-id ()
2961   ;; Don't use microseconds from (current-time), they may be unsupported.
2962   ;; Instead we use this randomly inited counter.
2963   (setq message-unique-id-char
2964         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2965            ;; (current-time) returns 16-bit ints,
2966            ;; and 2^16*25 just fits into 4 digits i base 36.
2967            (* 25 25)))
2968   (let ((tm (current-time)))
2969     (concat
2970      (if (memq system-type '(ms-dos emx vax-vms))
2971          (let ((user (downcase (user-login-name))))
2972            (while (string-match "[^a-z0-9_]" user)
2973              (aset user (match-beginning 0) ?_))
2974            user)
2975        (message-number-base36 (user-uid) -1))
2976      (message-number-base36 (+ (car   tm)
2977                                (lsh (% message-unique-id-char 25) 16)) 4)
2978      (message-number-base36 (+ (nth 1 tm)
2979                                (lsh (/ message-unique-id-char 25) 16)) 4)
2980      ;; Append the newsreader name, because while the generated
2981      ;; ID is unique to this newsreader, other newsreaders might
2982      ;; otherwise generate the same ID via another algorithm.
2983      ".fsf")))
2984
2985 (defun message-number-base36 (num len)
2986   (if (if (< len 0)
2987           (<= num 0)
2988         (= len 0))
2989       ""
2990     (concat (message-number-base36 (/ num 36) (1- len))
2991             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2992                                   (% num 36))))))
2993
2994 (defun message-make-organization ()
2995   "Make an Organization header."
2996   (let* ((organization
2997           (when message-user-organization
2998             (if (message-functionp message-user-organization)
2999                 (funcall message-user-organization)
3000               message-user-organization))))
3001     (save-excursion
3002       (message-set-work-buffer)
3003       (cond ((stringp organization)
3004              (insert organization))
3005             ((and (eq t organization)
3006                   message-user-organization-file
3007                   (file-exists-p message-user-organization-file))
3008              (insert-file-contents message-user-organization-file)))
3009       (goto-char (point-min))
3010       (while (re-search-forward "[\t\n]+" nil t)
3011         (replace-match "" t t))
3012       (unless (zerop (buffer-size))
3013         (buffer-string)))))
3014
3015 (defun message-make-lines ()
3016   "Count the number of lines and return numeric string."
3017   (save-excursion
3018     (save-restriction
3019       (widen)
3020       (goto-char (point-min))
3021       (re-search-forward
3022        (concat "^" (regexp-quote mail-header-separator) "$"))
3023       (forward-line 1)
3024       (int-to-string (count-lines (point) (point-max))))))
3025
3026 (defun message-make-in-reply-to ()
3027   "Return the In-Reply-To header for this message."
3028   (when message-reply-headers
3029     (mail-header-message-id message-reply-headers)))
3030
3031 (defun message-make-distribution ()
3032   "Make a Distribution header."
3033   (let ((orig-distribution (message-fetch-reply-field "distribution")))
3034     (cond ((message-functionp message-distribution-function)
3035            (funcall message-distribution-function))
3036           (t orig-distribution))))
3037
3038 (defun message-make-expires ()
3039   "Return an Expires header based on `message-expires'."
3040   (let ((current (current-time))
3041         (future (* 1.0 message-expires 60 60 24)))
3042     ;; Add the future to current.
3043     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
3044     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
3045     (message-make-date current)))
3046
3047 (defun message-make-path ()
3048   "Return uucp path."
3049   (let ((login-name (user-login-name)))
3050     (cond ((null message-user-path)
3051            (concat (system-name) "!" login-name))
3052           ((stringp message-user-path)
3053            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
3054            (concat message-user-path "!" login-name))
3055           (t login-name))))
3056
3057 (defun message-make-from ()
3058   "Make a From header."
3059   (let* ((style message-from-style)
3060          (login (message-make-address))
3061          (fullname
3062           (or (and (boundp 'user-full-name)
3063                    user-full-name)
3064               (user-full-name))))
3065     (when (string= fullname "&")
3066       (setq fullname (user-login-name)))
3067     (save-excursion
3068       (message-set-work-buffer)
3069       (cond
3070        ((or (null style)
3071             (equal fullname ""))
3072         (insert login))
3073        ((or (eq style 'angles)
3074             (and (not (eq style 'parens))
3075                  ;; Use angles if no quoting is needed, or if parens would
3076                  ;; need quoting too.
3077                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
3078                      (let ((tmp (concat fullname nil)))
3079                        (while (string-match "([^()]*)" tmp)
3080                          (aset tmp (match-beginning 0) ?-)
3081                          (aset tmp (1- (match-end 0)) ?-))
3082                        (string-match "[\\()]" tmp)))))
3083         (insert fullname)
3084         (goto-char (point-min))
3085         ;; Look for a character that cannot appear unquoted
3086         ;; according to RFC 822.
3087         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
3088           ;; Quote fullname, escaping specials.
3089           (goto-char (point-min))
3090           (insert "\"")
3091           (while (re-search-forward "[\"\\]" nil 1)
3092             (replace-match "\\\\\\&" t))
3093           (insert "\""))
3094         (insert " <" login ">"))
3095        (t                               ; 'parens or default
3096         (insert login " (")
3097         (let ((fullname-start (point)))
3098           (insert fullname)
3099           (goto-char fullname-start)
3100           ;; RFC 822 says \ and nonmatching parentheses
3101           ;; must be escaped in comments.
3102           ;; Escape every instance of ()\ ...
3103           (while (re-search-forward "[()\\]" nil 1)
3104             (replace-match "\\\\\\&" t))
3105           ;; ... then undo escaping of matching parentheses,
3106           ;; including matching nested parentheses.
3107           (goto-char fullname-start)
3108           (while (re-search-forward
3109                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
3110                   nil 1)
3111             (replace-match "\\1(\\3)" t)
3112             (goto-char fullname-start)))
3113         (insert ")")))
3114       (buffer-string))))
3115
3116 (defun message-make-sender ()
3117   "Return the \"real\" user address.
3118 This function tries to ignore all user modifications, and
3119 give as trustworthy answer as possible."
3120   (concat (user-login-name) "@" (system-name)))
3121
3122 (defun message-make-address ()
3123   "Make the address of the user."
3124   (or (message-user-mail-address)
3125       (concat (user-login-name) "@" (message-make-domain))))
3126
3127 (defun message-user-mail-address ()
3128   "Return the pertinent part of `user-mail-address'."
3129   (when user-mail-address
3130     (if (string-match " " user-mail-address)
3131         (nth 1 (mail-extract-address-components user-mail-address))
3132       user-mail-address)))
3133
3134 (defun message-make-fqdn ()
3135   "Return user's fully qualified domain name."
3136   (let ((system-name (system-name))
3137         (user-mail (message-user-mail-address)))
3138     (cond
3139      ((string-match "[^.]\\.[^.]" system-name)
3140       ;; `system-name' returned the right result.
3141       system-name)
3142      ;; Try `mail-host-address'.
3143      ((and (boundp 'mail-host-address)
3144            (stringp mail-host-address)
3145            (string-match "\\." mail-host-address))
3146       mail-host-address)
3147      ;; We try `user-mail-address' as a backup.
3148      ((and user-mail
3149            (string-match "\\." user-mail)
3150            (string-match "@\\(.*\\)\\'" user-mail))
3151       (match-string 1 user-mail))
3152      ;; Default to this bogus thing.
3153      (t
3154       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
3155
3156 (defun message-make-host-name ()
3157   "Return the name of the host."
3158   (let ((fqdn (message-make-fqdn)))
3159     (string-match "^[^.]+\\." fqdn)
3160     (substring fqdn 0 (1- (match-end 0)))))
3161
3162 (defun message-make-domain ()
3163   "Return the domain name."
3164   (or mail-host-address
3165       (message-make-fqdn)))
3166
3167 (defun message-generate-headers (headers)
3168   "Prepare article HEADERS.
3169 Headers already prepared in the buffer are not modified."
3170   (save-restriction
3171     (message-narrow-to-headers)
3172     (let* ((Date (message-make-date))
3173            (Message-ID (message-make-message-id))
3174            (Organization (message-make-organization))
3175            (From (message-make-from))
3176            (Path (message-make-path))
3177            (Subject nil)
3178            (Newsgroups nil)
3179            (In-Reply-To (message-make-in-reply-to))
3180            (To nil)
3181            (Distribution (message-make-distribution))
3182            (Lines (message-make-lines))
3183            (User-Agent message-newsreader)
3184            (Expires (message-make-expires))
3185            (case-fold-search t)
3186            header value elem)
3187       ;; First we remove any old generated headers.
3188       (let ((headers message-deletable-headers))
3189         (unless (buffer-modified-p)
3190           (setq headers (delq 'Message-ID (copy-sequence headers))))
3191         (while headers
3192           (goto-char (point-min))
3193           (and (re-search-forward
3194                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3195                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3196                (message-delete-line))
3197           (pop headers)))
3198       ;; Go through all the required headers and see if they are in the
3199       ;; articles already.  If they are not, or are empty, they are
3200       ;; inserted automatically - except for Subject, Newsgroups and
3201       ;; Distribution.
3202       (while headers
3203         (goto-char (point-min))
3204         (setq elem (pop headers))
3205         (if (consp elem)
3206             (if (eq (car elem) 'optional)
3207                 (setq header (cdr elem))
3208               (setq header (car elem)))
3209           (setq header elem))
3210         (when (or (not (re-search-forward
3211                         (concat "^"
3212                                 (regexp-quote
3213                                  (downcase
3214                                   (if (stringp header)
3215                                       header
3216                                     (symbol-name header))))
3217                                 ":")
3218                         nil t))
3219                   (progn
3220                     ;; The header was found.  We insert a space after the
3221                     ;; colon, if there is none.
3222                     (if (/= (char-after) ? ) (insert " ") (forward-char 1))
3223                     ;; Find out whether the header is empty...
3224                     (looking-at "[ \t]*\n[^ \t]")))
3225           ;; So we find out what value we should insert.
3226           (setq value
3227                 (cond
3228                  ((and (consp elem) (eq (car elem) 'optional))
3229                   ;; This is an optional header.  If the cdr of this
3230                   ;; is something that is nil, then we do not insert
3231                   ;; this header.
3232                   (setq header (cdr elem))
3233                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3234                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3235                  ((consp elem)
3236                   ;; The element is a cons.  Either the cdr is a
3237                   ;; string to be inserted verbatim, or it is a
3238                   ;; function, and we insert the value returned from
3239                   ;; this function.
3240                   (or (and (stringp (cdr elem)) (cdr elem))
3241                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3242                  ((and (boundp header) (symbol-value header))
3243                   ;; The element is a symbol.  We insert the value
3244                   ;; of this symbol, if any.
3245                   (symbol-value header))
3246                  ((not (message-check-element header))
3247                   ;; We couldn't generate a value for this header,
3248                   ;; so we just ask the user.
3249                   (read-from-minibuffer
3250                    (format "Empty header for %s; enter value: " header)))))
3251           ;; Finally insert the header.
3252           (when (and value
3253                      (not (equal value "")))
3254             (save-excursion
3255               (if (bolp)
3256                   (progn
3257                     ;; This header didn't exist, so we insert it.
3258                     (goto-char (point-max))
3259                     (insert (if (stringp header) header (symbol-name header))
3260                             ": " value "\n")
3261                     (forward-line -1))
3262                 ;; The value of this header was empty, so we clear
3263                 ;; totally and insert the new value.
3264                 (delete-region (point) (gnus-point-at-eol))
3265                 (insert value))
3266               ;; Add the deletable property to the headers that require it.
3267               (and (memq header message-deletable-headers)
3268                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3269                    (add-text-properties
3270                     (point) (match-end 0)
3271                     '(message-deletable t face italic) (current-buffer)))))))
3272       ;; Insert new Sender if the From is strange.
3273       (let ((from (message-fetch-field "from"))
3274             (sender (message-fetch-field "sender"))
3275             (secure-sender (message-make-sender)))
3276         (when (and from
3277                    (not (message-check-element 'sender))
3278                    (not (string=
3279                          (downcase
3280                           (cadr (mail-extract-address-components from)))
3281                          (downcase secure-sender)))
3282                    (or (null sender)
3283                        (not
3284                         (string=
3285                          (downcase
3286                           (cadr (mail-extract-address-components sender)))
3287                          (downcase secure-sender)))))
3288           (goto-char (point-min))
3289           ;; Rename any old Sender headers to Original-Sender.
3290           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3291             (beginning-of-line)
3292             (insert "Original-")
3293             (beginning-of-line))
3294           (when (or (message-news-p)
3295                     (string-match "@.+\\.." secure-sender))
3296             (insert "Sender: " secure-sender "\n")))))))
3297
3298 (defun message-insert-courtesy-copy ()
3299   "Insert a courtesy message in mail copies of combined messages."
3300   (let (newsgroups)
3301     (save-excursion
3302       (save-restriction
3303         (message-narrow-to-headers)
3304         (when (setq newsgroups (message-fetch-field "newsgroups"))
3305           (goto-char (point-max))
3306           (insert "Posted-To: " newsgroups "\n")))
3307       (forward-line 1)
3308       (when message-courtesy-message
3309         (cond
3310          ((string-match "%s" message-courtesy-message)
3311           (insert (format message-courtesy-message newsgroups)))
3312          (t
3313           (insert message-courtesy-message)))))))
3314
3315 ;;;
3316 ;;; Setting up a message buffer
3317 ;;;
3318
3319 (defun message-fill-address (header value)
3320   (save-restriction
3321     (narrow-to-region (point) (point))
3322     (insert (capitalize (symbol-name header))
3323             ": "
3324             (if (consp value) (car value) value)
3325             "\n")
3326     (narrow-to-region (point-min) (1- (point-max)))
3327     (let (quoted last)
3328       (goto-char (point-min))
3329       (while (not (eobp))
3330         (skip-chars-forward "^,\"" (point-max))
3331         (if (or (eq (char-after) ?,)
3332                 (eobp))
3333             (when (not quoted)
3334               (if (and (> (current-column) 78)
3335                        last)
3336                   (progn
3337                     (save-excursion
3338                       (goto-char last)
3339                       (insert "\n\t"))
3340                     (setq last (1+ (point))))
3341                 (setq last (1+ (point)))))
3342           (setq quoted (not quoted)))
3343         (unless (eobp)
3344           (forward-char 1))))
3345     (goto-char (point-max))
3346     (widen)
3347     (forward-line 1)))
3348
3349 (defun message-fill-header (header value)
3350   (let ((begin (point))
3351         (fill-column 78)
3352         (fill-prefix "\t"))
3353     (insert (capitalize (symbol-name header))
3354             ": "
3355             (if (consp value) (car value) value)
3356             "\n")
3357     (save-restriction
3358       (narrow-to-region begin (point))
3359       (fill-region-as-paragraph begin (point))
3360       ;; Tapdance around looong Message-IDs.
3361       (forward-line -1)
3362       (when (looking-at "[ \t]*$")
3363         (message-delete-line))
3364       (goto-char begin)
3365       (re-search-forward ":" nil t)
3366       (when (looking-at "\n[ \t]+")
3367         (replace-match " " t t))
3368       (goto-char (point-max)))))
3369
3370 (defun message-shorten-1 (list cut surplus)
3371   ;; Cut SURPLUS elements out of LIST, beginning with CUTth one.
3372   (setcdr (nthcdr (- cut 2) list)
3373           (nthcdr (+ (- cut 2) surplus 1) list)))
3374
3375 (defun message-shorten-references (header references)
3376   "Trim REFERENCES to be less than 31 Message-ID long, and fold them.
3377 If folding is disallowed, also check that the REFERENCES are less
3378 than 988 characters long, and if they are not, trim them until they are."
3379   (let ((maxcount 31)
3380         (count 0)
3381         (cut 6)
3382         refs)
3383     (with-temp-buffer
3384       (insert references)
3385       (goto-char (point-min))
3386       ;; Cons a list of valid references.
3387       (while (re-search-forward "<[^>]+>" nil t)
3388         (push (match-string 0) refs))
3389       (setq refs (nreverse refs)
3390             count (length refs)))
3391
3392     ;; If the list has more than MAXCOUNT elements, trim it by
3393     ;; removing the CUTth element and the required number of
3394     ;; elements that follow.
3395     (when (> count maxcount)
3396       (let ((surplus (- count maxcount)))
3397         (message-shorten-1 refs cut surplus)
3398         (decf count surplus)))
3399
3400     ;; If folding is disallowed, make sure the total length (including
3401     ;; the spaces between) will be less than MAXSIZE characters.
3402     ;;
3403     ;; Only disallow folding for News messages. At this point the headers
3404     ;; have not been generated, thus we use message-this-is-news directly.
3405     (when (and message-this-is-news message-cater-to-broken-inn)
3406       (let ((maxsize 988)
3407             (totalsize (+ (apply #'+ (mapcar #'length refs))
3408                           (1- count)))
3409             (surplus 0)
3410             (ptr (nthcdr (1- cut) refs)))
3411         ;; Decide how many elements to cut off...
3412         (while (> totalsize maxsize)
3413           (decf totalsize (1+ (length (car ptr))))
3414           (incf surplus)
3415           (setq ptr (cdr ptr)))
3416         ;; ...and do it.
3417         (when (> surplus 0)
3418           (message-shorten-1 refs cut surplus))))
3419
3420     ;; Finally, collect the references back into a string and insert
3421     ;; it into the buffer.
3422     (let ((refstring (mapconcat #'identity refs " ")))
3423       (if (and message-this-is-news message-cater-to-broken-inn)
3424           (insert (capitalize (symbol-name header)) ": "
3425                   refstring "\n")
3426         (message-fill-header header refstring)))))
3427
3428 (defun message-position-point ()
3429   "Move point to where the user probably wants to find it."
3430   (message-narrow-to-headers)
3431   (cond
3432    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3433     (search-backward ":" )
3434     (widen)
3435     (forward-char 1)
3436     (if (eq (char-after) ? )
3437         (forward-char 1)
3438       (insert " ")))
3439    (t
3440     (goto-char (point-max))
3441     (widen)
3442     (forward-line 1)
3443     (unless (looking-at "$")
3444       (forward-line 2)))
3445    (sit-for 0)))
3446
3447 (defun message-buffer-name (type &optional to group)
3448   "Return a new (unique) buffer name based on TYPE and TO."
3449   (cond
3450    ;; Generate a new buffer name The Message Way.
3451    ((eq message-generate-new-buffers 'unique)
3452     (generate-new-buffer-name
3453      (concat "*" type
3454              (if to
3455                  (concat " to "
3456                          (or (car (mail-extract-address-components to))
3457                              to) "")
3458                "")
3459              (if (and group (not (string= group ""))) (concat " on " group) "")
3460              "*")))
3461    ;; Check whether `message-generate-new-buffers' is a function,
3462    ;; and if so, call it.
3463    ((message-functionp message-generate-new-buffers)
3464     (funcall message-generate-new-buffers type to group))
3465    ((eq message-generate-new-buffers 'unsent)
3466     (generate-new-buffer-name
3467      (concat "*unsent " type
3468              (if to
3469                  (concat " to "
3470                          (or (car (mail-extract-address-components to))
3471                              to) "")
3472                "")
3473              (if (and group (not (string= group ""))) (concat " on " group) "")
3474              "*")))
3475    ;; Use standard name.
3476    (t
3477     (format "*%s message*" type))))
3478
3479 (defun message-pop-to-buffer (name)
3480   "Pop to buffer NAME, and warn if it already exists and is modified."
3481   (let ((buffer (get-buffer name)))
3482     (if (and buffer
3483              (buffer-name buffer))
3484         (progn
3485           (set-buffer (pop-to-buffer buffer))
3486           (when (and (buffer-modified-p)
3487                      (not (y-or-n-p
3488                            "Message already being composed; erase? ")))
3489             (error "Message being composed")))
3490       (set-buffer (pop-to-buffer name)))
3491     (erase-buffer)
3492     (message-mode)))
3493
3494 (defun message-do-send-housekeeping ()
3495   "Kill old message buffers."
3496   ;; We might have sent this buffer already.  Delete it from the
3497   ;; list of buffers.
3498   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3499   (while (and message-max-buffers
3500               message-buffer-list
3501               (>= (length message-buffer-list) message-max-buffers))
3502     ;; Kill the oldest buffer -- unless it has been changed.
3503     (let ((buffer (pop message-buffer-list)))
3504       (when (and (buffer-name buffer)
3505                  (not (buffer-modified-p buffer)))
3506         (kill-buffer buffer))))
3507   ;; Rename the buffer.
3508   (if message-send-rename-function
3509       (funcall message-send-rename-function)
3510     (when (string-match "\\`\\*\\(unsent \\)?" (buffer-name))
3511       (rename-buffer
3512        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3513   ;; Push the current buffer onto the list.
3514   (when message-max-buffers
3515     (setq message-buffer-list
3516           (nconc message-buffer-list (list (current-buffer))))))
3517
3518 (defvar mc-modes-alist)
3519 (defun message-setup (headers &optional replybuffer actions)
3520   (when (and (boundp 'mc-modes-alist)
3521              (not (assq 'message-mode mc-modes-alist)))
3522     (push '(message-mode (encrypt . mc-encrypt-message)
3523                          (sign . mc-sign-message))
3524           mc-modes-alist))
3525   (when actions
3526     (setq message-send-actions actions))
3527   (setq message-reply-buffer replybuffer)
3528   (goto-char (point-min))
3529   ;; Insert all the headers.
3530   (mail-header-format
3531    (let ((h headers)
3532          (alist message-header-format-alist))
3533      (while h
3534        (unless (assq (caar h) message-header-format-alist)
3535          (push (list (caar h)) alist))
3536        (pop h))
3537      alist)
3538    headers)
3539   (delete-region (point) (progn (forward-line -1) (point)))
3540   (when message-default-headers
3541     (insert message-default-headers)
3542     (or (bolp) (insert ?\n)))
3543   (put-text-property
3544    (point)
3545    (progn
3546      (insert mail-header-separator "\n")
3547      (1- (point)))
3548    'read-only nil)
3549   (forward-line -1)
3550   (when (message-news-p)
3551     (when message-default-news-headers
3552       (insert message-default-news-headers)
3553       (or (bolp) (insert ?\n)))
3554     (when message-generate-headers-first
3555       (message-generate-headers
3556        (delq 'Lines
3557              (delq 'Subject
3558                    (copy-sequence message-required-news-headers))))))
3559   (when (message-mail-p)
3560     (when message-default-mail-headers
3561       (insert message-default-mail-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-mail-headers))))))
3568   (run-hooks 'message-signature-setup-hook)
3569   (message-insert-signature)
3570   (save-restriction
3571     (message-narrow-to-headers)
3572     (run-hooks 'message-header-setup-hook))
3573   (set-buffer-modified-p nil)
3574   (setq buffer-undo-list nil)
3575   (run-hooks 'message-setup-hook)
3576   (message-position-point)
3577   (undo-boundary))
3578
3579 (defun message-set-auto-save-file-name ()
3580   "Associate the message buffer with a file in the drafts directory."
3581   (when message-auto-save-directory
3582     (if (gnus-alive-p)
3583         (setq message-draft-article
3584               (nndraft-request-associate-buffer "drafts"))
3585       (setq buffer-file-name (expand-file-name "*message*"
3586                                                message-auto-save-directory))
3587       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3588     (clear-visited-file-modtime)
3589     (setq buffer-file-coding-system message-draft-coding-system)))
3590
3591 (defun message-disassociate-draft ()
3592   "Disassociate the message buffer from the drafts directory."
3593   (when message-draft-article
3594     (nndraft-request-expire-articles
3595      (list message-draft-article) "drafts" nil t)))
3596
3597 (defun message-insert-headers ()
3598   "Generate the headers for the article."
3599   (interactive)
3600   (save-excursion
3601     (save-restriction
3602       (message-narrow-to-headers)
3603       (when (message-news-p)
3604         (message-generate-headers
3605          (delq 'Lines
3606                (delq 'Subject
3607                      (copy-sequence message-required-news-headers)))))
3608       (when (message-mail-p)
3609         (message-generate-headers
3610          (delq 'Lines
3611                (delq 'Subject
3612                      (copy-sequence message-required-mail-headers))))))))
3613
3614 \f
3615
3616 ;;;
3617 ;;; Commands for interfacing with message
3618 ;;;
3619
3620 ;;;###autoload
3621 (defun message-mail (&optional to subject
3622                                other-headers continue switch-function
3623                                yank-action send-actions)
3624   "Start editing a mail message to be sent.
3625 OTHER-HEADERS is an alist of header/value pairs."
3626   (interactive)
3627   (let ((message-this-is-mail t))
3628     (message-pop-to-buffer (message-buffer-name "mail" to))
3629     (message-setup
3630      (nconc
3631       `((To . ,(or to "")) (Subject . ,(or subject "")))
3632       (when other-headers other-headers)))))
3633
3634 ;;;###autoload
3635 (defun message-news (&optional newsgroups subject)
3636   "Start editing a news article to be sent."
3637   (interactive)
3638   (let ((message-this-is-news t))
3639     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3640     (message-setup `((Newsgroups . ,(or newsgroups ""))
3641                      (Subject . ,(or subject ""))))))
3642
3643 (defun message-get-reply-headers (wide &optional to-address)
3644   (let (follow-to mct never-mct from to cc reply-to ccalist)
3645     ;; Find all relevant headers we need.
3646     (setq from (message-fetch-field "from")
3647           to (message-fetch-field "to")
3648           cc (message-fetch-field "cc")
3649           mct (message-fetch-field "mail-copies-to")
3650           reply-to (message-fetch-field "reply-to"))
3651
3652     ;; Handle special values of Mail-Copies-To.
3653     (when mct
3654       (cond ((or (equal (downcase mct) "never")
3655                  (equal (downcase mct) "nobody"))
3656              (setq never-mct t)
3657              (setq mct nil))
3658             ((or (equal (downcase mct) "always")
3659                  (equal (downcase mct) "poster"))
3660              (setq mct (or reply-to from)))))
3661
3662     (if (or (not wide)
3663             to-address)
3664         (progn
3665           (setq follow-to (list (cons 'To (or to-address reply-to from))))
3666           (when (and wide mct)
3667             (push (cons 'Cc mct) follow-to)))
3668       (let (ccalist)
3669         (save-excursion
3670           (message-set-work-buffer)
3671           (unless never-mct
3672             (insert (or reply-to from "")))
3673           (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3674           (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3675           (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3676           (goto-char (point-min))
3677           (while (re-search-forward "[ \t]+" nil t)
3678             (replace-match " " t t))
3679           ;; Remove addresses that match `rmail-dont-reply-to-names'.
3680           (let ((rmail-dont-reply-to-names message-dont-reply-to-names))
3681             (insert (prog1 (rmail-dont-reply-to (buffer-string))
3682                       (erase-buffer))))
3683           (goto-char (point-min))
3684           ;; Perhaps "Mail-Copies-To: never" removed the only address?
3685           (when (eobp)
3686             (insert (or reply-to from "")))
3687           (setq ccalist
3688                 (mapcar
3689                  (lambda (addr)
3690                    (cons (mail-strip-quoted-names addr) addr))
3691                  (message-tokenize-header (buffer-string))))
3692           (let ((s ccalist))
3693             (while s
3694               (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3695         (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3696         (when ccalist
3697           (let ((ccs (cons 'Cc (mapconcat
3698                                 (lambda (addr) (cdr addr)) ccalist ", "))))
3699             (when (string-match "^ +" (cdr ccs))
3700               (setcdr ccs (substring (cdr ccs) (match-end 0))))
3701             (push ccs follow-to)))))
3702     follow-to))
3703
3704
3705 ;;;###autoload
3706 (defun message-reply (&optional to-address wide)
3707   "Start editing a reply to the article in the current buffer."
3708   (interactive)
3709   (require 'gnus-sum)                   ; for gnus-list-identifiers
3710   (let ((cur (current-buffer))
3711         from subject date reply-to to cc
3712         references message-id follow-to
3713         (inhibit-point-motion-hooks t)
3714         (message-this-is-mail t)
3715         gnus-warning)
3716     (save-restriction
3717       (message-narrow-to-head)
3718       ;; Allow customizations to have their say.
3719       (if (not wide)
3720           ;; This is a regular reply.
3721           (if (message-functionp message-reply-to-function)
3722               (setq follow-to (funcall message-reply-to-function)))
3723         ;; This is a followup.
3724         (if (message-functionp message-wide-reply-to-function)
3725             (save-excursion
3726               (setq follow-to
3727                     (funcall message-wide-reply-to-function)))))
3728       (setq message-id (message-fetch-field "message-id" t)
3729             references (message-fetch-field "references")
3730             date (message-fetch-field "date")
3731             from (message-fetch-field "from")
3732             subject (or (message-fetch-field "subject") "none"))
3733     (if gnus-list-identifiers
3734         (setq subject (message-strip-list-identifiers subject)))
3735     (setq subject (concat "Re: " (message-strip-subject-re subject)))
3736
3737     (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3738                (string-match "<[^>]+>" gnus-warning))
3739       (setq message-id (match-string 0 gnus-warning)))
3740
3741     (unless follow-to
3742       (setq follow-to (message-get-reply-headers wide to-address))))
3743
3744     (message-pop-to-buffer
3745      (message-buffer-name
3746       (if wide "wide reply" "reply") from
3747       (if wide to-address nil)))
3748
3749     (setq message-reply-headers
3750           (vector 0 subject from date message-id references 0 0 ""))
3751
3752     (message-setup
3753      `((Subject . ,subject)
3754        ,@follow-to
3755        ,@(if (or references message-id)
3756              `((References . ,(concat (or references "") (and references " ")
3757                                       (or message-id ""))))
3758            nil))
3759      cur)))
3760
3761 ;;;###autoload
3762 (defun message-wide-reply (&optional to-address)
3763   "Make a \"wide\" reply to the message in the current buffer."
3764   (interactive)
3765   (message-reply to-address t))
3766
3767 ;;;###autoload
3768 (defun message-followup (&optional to-newsgroups)
3769   "Follow up to the message in the current buffer.
3770 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3771   (interactive)
3772   (require 'gnus-sum)                   ; for gnus-list-identifiers
3773   (let ((cur (current-buffer))
3774         from subject date reply-to mct
3775         references message-id follow-to
3776         (inhibit-point-motion-hooks t)
3777         (message-this-is-news t)
3778         followup-to distribution newsgroups gnus-warning posted-to)
3779     (save-restriction
3780       (narrow-to-region
3781        (goto-char (point-min))
3782        (if (search-forward "\n\n" nil t)
3783            (1- (point))
3784          (point-max)))
3785       (when (message-functionp message-followup-to-function)
3786         (setq follow-to
3787               (funcall message-followup-to-function)))
3788       (setq from (message-fetch-field "from")
3789             date (message-fetch-field "date")
3790             subject (or (message-fetch-field "subject") "none")
3791             references (message-fetch-field "references")
3792             message-id (message-fetch-field "message-id" t)
3793             followup-to (message-fetch-field "followup-to")
3794             newsgroups (message-fetch-field "newsgroups")
3795             posted-to (message-fetch-field "posted-to")
3796             reply-to (message-fetch-field "reply-to")
3797             distribution (message-fetch-field "distribution")
3798             mct (message-fetch-field "mail-copies-to"))
3799       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3800                  (string-match "<[^>]+>" gnus-warning))
3801         (setq message-id (match-string 0 gnus-warning)))
3802       ;; Remove bogus distribution.
3803       (when (and (stringp distribution)
3804                  (let ((case-fold-search t))
3805                    (string-match "world" distribution)))
3806         (setq distribution nil))
3807       (if gnus-list-identifiers
3808           (setq subject (message-strip-list-identifiers subject)))
3809       (setq subject (concat "Re: " (message-strip-subject-re subject)))
3810       (widen))
3811
3812     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3813
3814     (message-setup
3815      `((Subject . ,subject)
3816        ,@(cond
3817           (to-newsgroups
3818            (list (cons 'Newsgroups to-newsgroups)))
3819           (follow-to follow-to)
3820           ((and followup-to message-use-followup-to)
3821            (list
3822             (cond
3823              ((equal (downcase followup-to) "poster")
3824               (if (or (eq message-use-followup-to 'use)
3825                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3826 You should normally obey the Followup-To: header.
3827
3828 `Followup-To: poster' sends your response via e-mail instead of news.
3829
3830 A typical situation where `Followup-To: poster' is used is when the poster
3831 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3832                   (progn
3833                     (setq message-this-is-news nil)
3834                     (cons 'To (or reply-to from "")))
3835                 (cons 'Newsgroups newsgroups)))
3836              (t
3837               (if (or (equal followup-to newsgroups)
3838                       (not (eq message-use-followup-to 'ask))
3839                       (message-y-or-n-p
3840                        (concat "Obey Followup-To: " followup-to "? ") t "\
3841 You should normally obey the Followup-To: header.
3842
3843         `Followup-To: " followup-to "'
3844 directs your response to " (if (string-match "," followup-to)
3845                                "the specified newsgroups"
3846                              "that newsgroup only") ".
3847
3848 If a message is posted to several newsgroups, Followup-To is often
3849 used to direct the following discussion to one newsgroup only,
3850 because discussions that are spread over several newsgroup tend to
3851 be fragmented and very difficult to follow.
3852
3853 Also, some source/announcement newsgroups are not indented for discussion;
3854 responses here are directed to other newsgroups."))
3855                   (cons 'Newsgroups followup-to)
3856                 (cons 'Newsgroups newsgroups))))))
3857           (posted-to
3858            `((Newsgroups . ,posted-to)))
3859           (t
3860            `((Newsgroups . ,newsgroups))))
3861        ,@(and distribution (list (cons 'Distribution distribution)))
3862        ,@(if (or references message-id)
3863              `((References . ,(concat (or references "") (and references " ")
3864                                       (or message-id "")))))
3865        ,@(when (and mct
3866                     (not (or (equal (downcase mct) "never")
3867                              (equal (downcase mct) "nobody"))))
3868            (list (cons 'Cc (if (or (equal (downcase mct) "always")
3869                                    (equal (downcase mct) "poster"))
3870                                (or reply-to from "")
3871                              mct)))))
3872
3873      cur)
3874
3875     (setq message-reply-headers
3876           (vector 0 subject from date message-id references 0 0 ""))))
3877
3878
3879 ;;;###autoload
3880 (defun message-cancel-news (&optional arg)
3881   "Cancel an article you posted.
3882 If ARG, allow editing of the cancellation message."
3883   (interactive "P")
3884   (unless (message-news-p)
3885     (error "This is not a news article; canceling is impossible"))
3886   (when (yes-or-no-p "Do you really want to cancel this article? ")
3887     (let (from newsgroups message-id distribution buf sender)
3888       (save-excursion
3889         ;; Get header info from original article.
3890         (save-restriction
3891           (message-narrow-to-head)
3892           (setq from (message-fetch-field "from")
3893                 sender (message-fetch-field "sender")
3894                 newsgroups (message-fetch-field "newsgroups")
3895                 message-id (message-fetch-field "message-id" t)
3896                 distribution (message-fetch-field "distribution")))
3897         ;; Make sure that this article was written by the user.
3898         (unless (or (and sender
3899                          (string-equal
3900                           (downcase sender)
3901                           (downcase (message-make-sender))))
3902                     (string-equal
3903                      (downcase (cadr (mail-extract-address-components from)))
3904                      (downcase (cadr (mail-extract-address-components
3905                                       (message-make-from))))))
3906           (error "This article is not yours"))
3907         ;; Make control message.
3908         (if arg
3909             (message-news)
3910           (setq buf (set-buffer (get-buffer-create " *message cancel*"))))
3911         (erase-buffer)
3912         (insert "Newsgroups: " newsgroups "\n"
3913                "From: " from "\n"
3914                 "Subject: cmsg cancel " message-id "\n"
3915                 "Control: cancel " message-id "\n"
3916                 (if distribution
3917                     (concat "Distribution: " distribution "\n")
3918                   "")
3919                 mail-header-separator "\n"
3920                 message-cancel-message)
3921         (run-hooks 'message-cancel-hook)
3922         (unless arg
3923           (message "Canceling your article...")
3924           (if (let ((message-syntax-checks
3925                      'dont-check-for-anything-just-trust-me))
3926                 (funcall message-send-news-function))
3927               (message "Canceling your article...done"))
3928           (kill-buffer buf))))))
3929
3930 ;;;###autoload
3931 (defun message-supersede ()
3932   "Start composing a message to supersede the current message.
3933 This is done simply by taking the old article and adding a Supersedes
3934 header line with the old Message-ID."
3935   (interactive)
3936   (let ((cur (current-buffer))
3937         (sender (message-fetch-field "sender"))
3938         (from (message-fetch-field "from")))
3939     ;; Check whether the user owns the article that is to be superseded.
3940     (unless (or (and sender
3941                      (string-equal
3942                       (downcase sender)
3943                       (downcase (message-make-sender))))
3944                 (string-equal
3945                  (downcase (cadr (mail-extract-address-components from)))
3946                  (downcase (cadr (mail-extract-address-components
3947                                   (message-make-from))))))
3948       (error "This article is not yours"))
3949     ;; Get a normal message buffer.
3950     (message-pop-to-buffer (message-buffer-name "supersede"))
3951     (insert-buffer-substring cur)
3952     (mime-to-mml)
3953     (message-narrow-to-head)
3954     ;; Remove unwanted headers.
3955     (when message-ignored-supersedes-headers
3956       (message-remove-header message-ignored-supersedes-headers t))
3957     (goto-char (point-min))
3958     (if (not (re-search-forward "^Message-ID: " nil t))
3959         (error "No Message-ID in this article")
3960       (replace-match "Supersedes: " t t))
3961     (goto-char (point-max))
3962     (insert mail-header-separator)
3963     (widen)
3964     (forward-line 1)))
3965
3966 ;;;###autoload
3967 (defun message-recover ()
3968   "Reread contents of current buffer from its last auto-save file."
3969   (interactive)
3970   (let ((file-name (make-auto-save-file-name)))
3971     (cond ((save-window-excursion
3972              (if (not (eq system-type 'vax-vms))
3973                  (with-output-to-temp-buffer "*Directory*"
3974                    (with-current-buffer standard-output
3975                      (fundamental-mode)) ; for Emacs 20.4+
3976                    (buffer-disable-undo standard-output)
3977                    (let ((default-directory "/"))
3978                      (call-process
3979                       "ls" nil standard-output nil "-l" file-name))))
3980              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3981            (let ((buffer-read-only nil))
3982              (erase-buffer)
3983              (insert-file-contents file-name nil)))
3984           (t (error "message-recover cancelled")))))
3985
3986 ;;; Washing Subject:
3987
3988 (defun message-wash-subject (subject)
3989   "Remove junk like \"Re:\", \"(fwd)\", etc. that was added to the subject by previous forwarders, replyers, etc."
3990   (with-temp-buffer
3991     (insert-string subject)
3992     (goto-char (point-min))
3993     ;; strip Re/Fwd stuff off the beginning
3994     (while (re-search-forward
3995             "\\([Rr][Ee]:\\|[Ff][Ww][Dd]\\(\\[[0-9]*\\]\\)?:\\|[Ff][Ww]:\\)" nil t)
3996       (replace-match ""))
3997
3998     ;; and gnus-style forwards [foo@bar.com] subject
3999     (goto-char (point-min))
4000     (while (re-search-forward "\\[[^ \t]*\\(@\\|\\.\\)[^ \t]*\\]" nil t)
4001       (replace-match ""))
4002
4003     ;; and off the end
4004     (goto-char (point-max))
4005     (while (re-search-backward "([Ff][Ww][Dd])" nil t)
4006       (replace-match ""))
4007
4008     ;; and finally, any whitespace that was left-over
4009     (goto-char (point-min))
4010     (while (re-search-forward "^[ \t]+" nil t)
4011       (replace-match ""))
4012     (goto-char (point-max))
4013     (while (re-search-backward "[ \t]+$" nil t)
4014       (replace-match ""))
4015
4016     (buffer-string)))
4017
4018 ;;; Forwarding messages.
4019
4020 (defun message-forward-subject-author-subject (subject)
4021   "Generate a subject for a forwarded message.
4022 The form is: [Source] Subject, where if the original message was mail,
4023 Source is the sender, and if the original message was news, Source is
4024 the list of newsgroups is was posted to."
4025   (concat "["
4026           (or (message-fetch-field
4027                (if (message-news-p) "newsgroups" "from"))
4028               "(nowhere)")
4029           "] " subject))
4030
4031 (defun message-forward-subject-fwd (subject)
4032   "Generate a subject for a forwarded message.
4033 The form is: Fwd: Subject, where Subject is the original subject of
4034 the message."
4035   (concat "Fwd: " subject))
4036
4037 (defun message-make-forward-subject ()
4038   "Return a Subject header suitable for the message in the current buffer."
4039   (save-excursion
4040     (save-restriction
4041       (current-buffer)
4042       (message-narrow-to-head)
4043       (let ((funcs message-make-forward-subject-function)
4044             (subject (if message-wash-forwarded-subjects
4045                          (message-wash-subject
4046                           (or (message-fetch-field "Subject") ""))
4047                        (or (message-fetch-field "Subject") ""))))
4048         ;; Make sure funcs is a list.
4049         (and funcs
4050              (not (listp funcs))
4051              (setq funcs (list funcs)))
4052         ;; Apply funcs in order, passing subject generated by previous
4053         ;; func to the next one.
4054         (while funcs
4055           (when (message-functionp (car funcs))
4056             (setq subject (funcall (car funcs) subject)))
4057           (setq funcs (cdr funcs)))
4058         subject))))
4059
4060 ;;;###autoload
4061 (defun message-forward (&optional news digest)
4062   "Forward the current message via mail.
4063 Optional NEWS will use news to forward instead of mail.
4064 Optional DIGEST will use digest to forward."
4065   (interactive "P")
4066   (let* ((cur (current-buffer))
4067          (subject (if message-forward-show-mml
4068                       (message-make-forward-subject)
4069                     (mail-decode-encoded-word-string
4070                      (message-make-forward-subject))))
4071          art-beg)
4072     (if news
4073         (message-news nil subject)
4074       (message-mail nil subject))
4075     ;; Put point where we want it before inserting the forwarded
4076     ;; message.
4077     (if message-forward-before-signature
4078         (message-goto-body)
4079       (goto-char (point-max)))
4080     (if message-forward-as-mime
4081         (if digest
4082             (insert "\n<#multipart type=digest>\n")
4083           (if message-forward-show-mml
4084               (insert "\n\n<#mml type=message/rfc822 disposition=inline>\n")
4085             (insert "\n\n<#part type=message/rfc822 disposition=inline raw=t>\n")))
4086       (insert "\n-------------------- Start of forwarded message --------------------\n"))
4087     (let ((b (point)) e)
4088       (if digest
4089           (if message-forward-as-mime
4090               (insert-buffer-substring cur)
4091             (mml-insert-buffer cur))
4092         (if message-forward-show-mml
4093             (insert-buffer-substring cur)
4094           (mml-insert-buffer cur)))
4095       (setq e (point))
4096       (if message-forward-as-mime
4097           (if digest
4098               (insert "<#/multipart>\n")
4099             (if message-forward-show-mml
4100                 (insert "<#/mml>\n")
4101               (insert "<#/part>\n")))
4102         (insert "\n-------------------- End of forwarded message --------------------\n"))
4103       (if (and digest message-forward-as-mime)
4104           (save-restriction
4105             (narrow-to-region b e)
4106             (goto-char b)
4107             (narrow-to-region (point) 
4108                               (or (search-forward "\n\n" nil t) (point)))
4109             (delete-region (point-min) (point-max)))
4110         (when (and (not current-prefix-arg)
4111                    message-forward-ignored-headers)
4112           (save-restriction
4113             (narrow-to-region b e)
4114             (goto-char b)
4115             (narrow-to-region (point) 
4116                               (or (search-forward "\n\n" nil t) (point)))
4117             (message-remove-header message-forward-ignored-headers t)))))
4118     (message-position-point)))
4119
4120 ;;;###autoload
4121 (defun message-resend (address)
4122   "Resend the current article to ADDRESS."
4123   (interactive
4124    (list (message-read-from-minibuffer "Resend message to: ")))
4125   (message "Resending message to %s..." address)
4126   (save-excursion
4127     (let ((cur (current-buffer))
4128           beg)
4129       ;; We first set up a normal mail buffer.
4130       (set-buffer (get-buffer-create " *message resend*"))
4131       (erase-buffer)
4132       (message-setup `((To . ,address)))
4133       ;; Insert our usual headers.
4134       (message-generate-headers '(From Date To))
4135       (message-narrow-to-headers)
4136       ;; Rename them all to "Resent-*".
4137       (while (re-search-forward "^[A-Za-z]" nil t)
4138         (forward-char -1)
4139         (insert "Resent-"))
4140       (widen)
4141       (forward-line)
4142       (delete-region (point) (point-max))
4143       (setq beg (point))
4144       ;; Insert the message to be resent.
4145       (insert-buffer-substring cur)
4146       (goto-char (point-min))
4147       (search-forward "\n\n")
4148       (forward-char -1)
4149       (save-restriction
4150         (narrow-to-region beg (point))
4151         (message-remove-header message-ignored-resent-headers t)
4152         (goto-char (point-max)))
4153       (insert mail-header-separator)
4154       ;; Rename all old ("Also-")Resent headers.
4155       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
4156         (beginning-of-line)
4157         (insert "Also-"))
4158       ;; Quote any "From " lines at the beginning.
4159       (goto-char beg)
4160       (when (looking-at "From ")
4161         (replace-match "X-From-Line: "))
4162       ;; Send it.
4163       (let ((message-inhibit-body-encoding t)
4164             message-required-mail-headers)
4165         (message-send-mail))
4166       (kill-buffer (current-buffer)))
4167     (message "Resending message to %s...done" address)))
4168
4169 ;;;###autoload
4170 (defun message-bounce ()
4171   "Re-mail the current message.
4172 This only makes sense if the current message is a bounce message that
4173 contains some mail you have written which has been bounced back to
4174 you."
4175   (interactive)
4176   (let ((handles (mm-dissect-buffer t))
4177         boundary)
4178     (message-pop-to-buffer (message-buffer-name "bounce"))
4179     (if (stringp (car handles))
4180         ;; This is a MIME bounce.
4181         (mm-insert-part (car (last handles)))
4182       ;; This is a non-MIME bounce, so we try to remove things
4183       ;; manually.
4184       (mm-insert-part handles)
4185       (undo-boundary)
4186       (goto-char (point-min))
4187       (search-forward "\n\n" nil t)
4188       (or (and (re-search-forward message-unsent-separator nil t)
4189                (forward-line 1))
4190           (re-search-forward "^Return-Path:.*\n" nil t))
4191       ;; We remove everything before the bounced mail.
4192       (delete-region
4193        (point-min)
4194        (if (re-search-forward "^[^ \n\t]+:" nil t)
4195            (match-beginning 0)
4196          (point))))
4197     (mm-enable-multibyte)
4198     (mime-to-mml)
4199     (save-restriction
4200       (message-narrow-to-head)
4201       (message-remove-header message-ignored-bounced-headers t)
4202       (goto-char (point-max))
4203       (insert mail-header-separator))
4204     (message-position-point)))
4205
4206 ;;;
4207 ;;; Interactive entry points for new message buffers.
4208 ;;;
4209
4210 ;;;###autoload
4211 (defun message-mail-other-window (&optional to subject)
4212   "Like `message-mail' command, but display mail buffer in another window."
4213   (interactive)
4214   (let ((pop-up-windows t)
4215         (special-display-buffer-names nil)
4216         (special-display-regexps nil)
4217         (same-window-buffer-names nil)
4218         (same-window-regexps nil))
4219     (message-pop-to-buffer (message-buffer-name "mail" to)))
4220   (let ((message-this-is-mail t))
4221     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4222
4223 ;;;###autoload
4224 (defun message-mail-other-frame (&optional to subject)
4225   "Like `message-mail' command, but display mail buffer in another frame."
4226   (interactive)
4227   (let ((pop-up-frames t)
4228         (special-display-buffer-names nil)
4229         (special-display-regexps nil)
4230         (same-window-buffer-names nil)
4231         (same-window-regexps nil))
4232     (message-pop-to-buffer (message-buffer-name "mail" to)))
4233   (let ((message-this-is-mail t))
4234     (message-setup `((To . ,(or to "")) (Subject . ,(or subject ""))))))
4235
4236 ;;;###autoload
4237 (defun message-news-other-window (&optional newsgroups subject)
4238   "Start editing a news article to be sent."
4239   (interactive)
4240   (let ((pop-up-windows t)
4241         (special-display-buffer-names nil)
4242         (special-display-regexps nil)
4243         (same-window-buffer-names nil)
4244         (same-window-regexps nil))
4245     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4246   (let ((message-this-is-news t))
4247     (message-setup `((Newsgroups . ,(or newsgroups ""))
4248                      (Subject . ,(or subject ""))))))
4249
4250 ;;;###autoload
4251 (defun message-news-other-frame (&optional newsgroups subject)
4252   "Start editing a news article to be sent."
4253   (interactive)
4254   (let ((pop-up-frames t)
4255         (special-display-buffer-names nil)
4256         (special-display-regexps nil)
4257         (same-window-buffer-names nil)
4258         (same-window-regexps nil))
4259     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
4260   (let ((message-this-is-news t))
4261     (message-setup `((Newsgroups . ,(or newsgroups ""))
4262                      (Subject . ,(or subject ""))))))
4263
4264 ;;; underline.el
4265
4266 ;; This code should be moved to underline.el (from which it is stolen).
4267
4268 ;;;###autoload
4269 (defun bold-region (start end)
4270   "Bold all nonblank characters in the region.
4271 Works by overstriking characters.
4272 Called from program, takes two arguments START and END
4273 which specify the range to operate on."
4274   (interactive "r")
4275   (save-excursion
4276     (let ((end1 (make-marker)))
4277       (move-marker end1 (max start end))
4278       (goto-char (min start end))
4279       (while (< (point) end1)
4280         (or (looking-at "[_\^@- ]")
4281             (insert (char-after) "\b"))
4282         (forward-char 1)))))
4283
4284 ;;;###autoload
4285 (defun unbold-region (start end)
4286   "Remove all boldness (overstruck characters) in the region.
4287 Called from program, takes two arguments START and END
4288 which specify the range to operate on."
4289   (interactive "r")
4290   (save-excursion
4291     (let ((end1 (make-marker)))
4292       (move-marker end1 (max start end))
4293       (goto-char (min start end))
4294       (while (re-search-forward "\b" end1 t)
4295         (if (eq (char-after) (char-after (- (point) 2)))
4296             (delete-char -2))))))
4297
4298 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
4299
4300 ;; Support for toolbar
4301 (when (featurep 'xemacs)
4302   (require 'messagexmas))
4303
4304 ;;; Group name completion.
4305
4306 (defvar message-newgroups-header-regexp
4307   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
4308   "Regexp that match headers that lists groups.")
4309
4310 (defun message-tab ()
4311   "Expand group names in Newsgroups and Followup-To headers.
4312 Do a `tab-to-tab-stop' if not in those headers."
4313   (interactive)
4314   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
4315         (mail-abbrev-in-expansion-header-p))
4316       (message-expand-group)
4317     (tab-to-tab-stop)))
4318
4319 (defvar gnus-active-hashtb)
4320 (defun message-expand-group ()
4321   "Expand the group name under point."
4322   (let* ((b (save-excursion
4323               (save-restriction
4324                 (narrow-to-region
4325                  (save-excursion
4326                    (beginning-of-line)
4327                    (skip-chars-forward "^:")
4328                    (1+ (point)))
4329                  (point))
4330                 (skip-chars-backward "^, \t\n") (point))))
4331          (completion-ignore-case t)
4332          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
4333                                             (point))))
4334          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
4335          (completions (all-completions string hashtb))
4336          comp)
4337     (delete-region b (point))
4338     (cond
4339      ((= (length completions) 1)
4340       (if (string= (car completions) string)
4341           (progn
4342             (insert string)
4343             (message "Only matching group"))
4344         (insert (car completions))))
4345      ((and (setq comp (try-completion string hashtb))
4346            (not (string= comp string)))
4347       (insert comp))
4348      (t
4349       (insert string)
4350       (if (not comp)
4351           (message "No matching groups")
4352         (save-selected-window
4353           (pop-to-buffer "*Completions*")
4354           (buffer-disable-undo)
4355           (let ((buffer-read-only nil))
4356             (erase-buffer)
4357             (let ((standard-output (current-buffer)))
4358               (display-completion-list (sort completions 'string<)))
4359             (goto-char (point-min))
4360             (delete-region (point) (progn (forward-line 3) (point))))))))))
4361
4362 ;;; Help stuff.
4363
4364 (defun message-talkative-question (ask question show &rest text)
4365   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
4366 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
4367 The following arguments may contain lists of values."
4368   (if (and show
4369            (setq text (message-flatten-list text)))
4370       (save-window-excursion
4371         (save-excursion
4372           (with-output-to-temp-buffer " *MESSAGE information message*"
4373             (set-buffer " *MESSAGE information message*")
4374             (fundamental-mode)          ; for Emacs 20.4+
4375             (mapcar 'princ text)
4376             (goto-char (point-min))))
4377         (funcall ask question))
4378     (funcall ask question)))
4379
4380 (defun message-flatten-list (list)
4381   "Return a new, flat list that contains all elements of LIST.
4382
4383 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
4384 => (1 2 3 4 5 6 7)"
4385   (cond ((consp list)
4386          (apply 'append (mapcar 'message-flatten-list list)))
4387         (list
4388          (list list))))
4389
4390 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4391   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4392 Then clone the local variables and values from the old buffer to the
4393 new one, cloning only the locals having a substring matching the
4394 regexp varstr."
4395   (let ((oldbuf (current-buffer)))
4396     (save-excursion
4397       (set-buffer (generate-new-buffer name))
4398       (message-clone-locals oldbuf varstr)
4399       (current-buffer))))
4400
4401 (defun message-clone-locals (buffer &optional varstr)
4402   "Clone the local variables from BUFFER to the current buffer."
4403   (let ((locals (save-excursion
4404                   (set-buffer buffer)
4405                   (buffer-local-variables)))
4406         (regexp "^gnus\\|^nn\\|^message\\|^user-mail-address"))
4407     (mapcar
4408      (lambda (local)
4409        (when (and (consp local)
4410                   (car local)
4411                   (string-match regexp (symbol-name (car local)))
4412                   (or (null varstr)
4413                       (string-match varstr (symbol-name (car local)))))
4414          (ignore-errors
4415            (set (make-local-variable (car local))
4416                 (cdr local)))))
4417      locals)))
4418
4419 ;;; Miscellaneous functions
4420
4421 ;; stolen (and renamed) from nnheader.el
4422 (if (fboundp 'subst-char-in-string)
4423     (defsubst message-replace-chars-in-string (string from to)
4424       (subst-char-in-string from to string))
4425   (defun message-replace-chars-in-string (string from to)
4426     "Replace characters in STRING from FROM to TO."
4427     (let ((string (substring string 0)) ;Copy string.
4428           (len (length string))
4429           (idx 0))
4430       ;; Replace all occurrences of FROM with TO.
4431       (while (< idx len)
4432         (when (= (aref string idx) from)
4433           (aset string idx to))
4434         (setq idx (1+ idx)))
4435       string)))
4436
4437 ;;;
4438 ;;; MIME functions
4439 ;;;
4440
4441 (defvar message-inhibit-body-encoding nil)
4442
4443 (defun message-encode-message-body ()
4444   (unless message-inhibit-body-encoding 
4445     (let ((mail-parse-charset (or mail-parse-charset
4446                                   message-default-charset))
4447           (case-fold-search t)
4448           lines content-type-p)
4449       (message-goto-body)
4450       (save-restriction
4451         (narrow-to-region (point) (point-max))
4452         (let ((new (mml-generate-mime)))
4453           (when new
4454             (delete-region (point-min) (point-max))
4455             (insert new)
4456             (goto-char (point-min))
4457             (if (eq (aref new 0) ?\n)
4458                 (delete-char 1)
4459               (search-forward "\n\n")
4460               (setq lines (buffer-substring (point-min) (1- (point))))
4461               (delete-region (point-min) (point))))))
4462       (save-restriction
4463         (message-narrow-to-headers-or-head)
4464         (message-remove-header "Mime-Version")
4465         (goto-char (point-max))
4466         (insert "MIME-Version: 1.0\n")
4467         (when lines
4468           (insert lines))
4469         (setq content-type-p
4470               (re-search-backward "^Content-Type:" nil t)))
4471       (save-restriction
4472         (message-narrow-to-headers-or-head)
4473         (message-remove-first-header "Content-Type")
4474         (message-remove-first-header "Content-Transfer-Encoding"))
4475       ;; We always make sure that the message has a Content-Type header.
4476       ;; This is because some broken MTAs and MUAs get awfully confused
4477       ;; when confronted with a message with a MIME-Version header and
4478       ;; without a Content-Type header.  For instance, Solaris'
4479       ;; /usr/bin/mail.
4480       (unless content-type-p
4481         (goto-char (point-min))
4482         (re-search-forward "^MIME-Version:")
4483         (forward-line 1)
4484         (insert "Content-Type: text/plain; charset=us-ascii\n")))))
4485
4486 (defun message-read-from-minibuffer (prompt)
4487   "Read from the minibuffer while providing abbrev expansion."
4488   (if (fboundp 'mail-abbrevs-setup)
4489       (let ((mail-abbrev-mode-regexp "")
4490             (minibuffer-setup-hook 'mail-abbrevs-setup))
4491         (read-from-minibuffer prompt))
4492     (let ((minibuffer-setup-hook 'mail-abbrev-minibuffer-setup-hook))
4493       (read-string prompt))))
4494
4495 (provide 'message)
4496
4497 (run-hooks 'message-load-hook)
4498
4499 ;; Local Variables:
4500 ;; coding: iso-8859-1
4501 ;; End:
4502
4503 ;;; message.el ends here