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