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