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