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