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