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