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