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