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