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