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