Sync up with Gnus 5.6.7.
[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@ifi.uio.no>
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 ((value (mail-fetch-field header nil (not not-all))))
1008     (when value
1009       (nnheader-replace-chars-in-string value ?\n ? ))))
1010
1011 (defun message-add-header (&rest headers)
1012   "Add the HEADERS to the message header, skipping those already present."
1013   (while headers
1014     (let (hclean)
1015       (unless (string-match "^\\([^:]+\\):[ \t]*[^ \t]" (car headers))
1016         (error "Invalid header `%s'" (car headers)))
1017       (setq hclean (match-string 1 (car headers)))
1018     (save-restriction
1019       (message-narrow-to-headers)
1020       (unless (re-search-forward (concat "^" (regexp-quote hclean) ":") nil t)
1021         (insert (car headers) ?\n))))
1022     (setq headers (cdr headers))))
1023
1024 (defun message-fetch-reply-field (header)
1025   "Fetch FIELD from the message we're replying to."
1026   (when (and message-reply-buffer
1027              (buffer-name message-reply-buffer))
1028     (save-excursion
1029       (set-buffer message-reply-buffer)
1030       (message-fetch-field header))))
1031
1032 (defun message-set-work-buffer ()
1033   (if (get-buffer " *message work*")
1034       (progn
1035         (set-buffer " *message work*")
1036         (erase-buffer))
1037     (set-buffer (get-buffer-create " *message work*"))
1038     (kill-all-local-variables)
1039     (buffer-disable-undo (current-buffer))))
1040
1041 (defun message-functionp (form)
1042   "Return non-nil if FORM is funcallable."
1043   (or (and (symbolp form) (fboundp form))
1044       (and (listp form) (eq (car form) 'lambda))
1045       (byte-code-function-p form)))
1046
1047 (defun message-strip-subject-re (subject)
1048   "Remove \"Re:\" from subject lines."
1049   (if (string-match "^[Rr][Ee]: *" subject)
1050       (substring subject (match-end 0))
1051     subject))
1052
1053 (defun message-remove-header (header &optional is-regexp first reverse)
1054   "Remove HEADER in the narrowed buffer.
1055 If REGEXP, HEADER is a regular expression.
1056 If FIRST, only remove the first instance of the header.
1057 Return the number of headers removed."
1058   (goto-char (point-min))
1059   (let ((regexp (if is-regexp header (concat "^" header ":")))
1060         (number 0)
1061         (case-fold-search t)
1062         last)
1063     (while (and (not (eobp))
1064                 (not last))
1065       (if (if reverse
1066               (not (looking-at regexp))
1067             (looking-at regexp))
1068           (progn
1069             (incf number)
1070             (when first
1071               (setq last t))
1072             (delete-region
1073              (point)
1074              ;; There might be a continuation header, so we have to search
1075              ;; until we find a new non-continuation line.
1076              (progn
1077                (forward-line 1)
1078                (if (re-search-forward "^[^ \t]" nil t)
1079                    (goto-char (match-beginning 0))
1080                  (point-max)))))
1081         (forward-line 1)
1082         (if (re-search-forward "^[^ \t]" nil t)
1083             (goto-char (match-beginning 0))
1084           (point-max))))
1085     number))
1086
1087 (defun message-narrow-to-headers ()
1088   "Narrow the buffer to the head of the message."
1089   (widen)
1090   (narrow-to-region
1091    (goto-char (point-min))
1092    (if (re-search-forward
1093         (concat "^" (regexp-quote mail-header-separator) "\n") nil t)
1094        (match-beginning 0)
1095      (point-max)))
1096   (goto-char (point-min)))
1097
1098 (defun message-narrow-to-head ()
1099   "Narrow the buffer to the head of the message."
1100   (widen)
1101   (narrow-to-region
1102    (goto-char (point-min))
1103    (if (search-forward "\n\n" nil 1)
1104        (1- (point))
1105      (point-max)))
1106   (goto-char (point-min)))
1107
1108 (defun message-news-p ()
1109   "Say whether the current buffer contains a news message."
1110   (or message-this-is-news
1111       (save-excursion
1112         (save-restriction
1113           (message-narrow-to-headers)
1114           (and (message-fetch-field "newsgroups")
1115                (not (message-fetch-field "posted-to")))))))
1116
1117 (defun message-mail-p ()
1118   "Say whether the current buffer contains a mail message."
1119   (or message-this-is-mail
1120       (save-excursion
1121         (save-restriction
1122           (message-narrow-to-headers)
1123           (or (message-fetch-field "to")
1124               (message-fetch-field "cc")
1125               (message-fetch-field "bcc"))))))
1126
1127 (defun message-next-header ()
1128   "Go to the beginning of the next header."
1129   (beginning-of-line)
1130   (or (eobp) (forward-char 1))
1131   (not (if (re-search-forward "^[^ \t]" nil t)
1132            (beginning-of-line)
1133          (goto-char (point-max)))))
1134
1135 (defun message-sort-headers-1 ()
1136   "Sort the buffer as headers using `message-rank' text props."
1137   (goto-char (point-min))
1138   (sort-subr
1139    nil 'message-next-header
1140    (lambda ()
1141      (message-next-header)
1142      (unless (bobp)
1143        (forward-char -1)))
1144    (lambda ()
1145      (or (get-text-property (point) 'message-rank)
1146          10000))))
1147
1148 (defun message-sort-headers ()
1149   "Sort the headers of the current message according to `message-header-format-alist'."
1150   (interactive)
1151   (save-excursion
1152     (save-restriction
1153       (let ((max (1+ (length message-header-format-alist)))
1154             rank)
1155         (message-narrow-to-headers)
1156         (while (re-search-forward "^[^ \n]+:" nil t)
1157           (put-text-property
1158            (match-beginning 0) (1+ (match-beginning 0))
1159            'message-rank
1160            (if (setq rank (length (memq (assq (intern (buffer-substring
1161                                                        (match-beginning 0)
1162                                                        (1- (match-end 0))))
1163                                               message-header-format-alist)
1164                                         message-header-format-alist)))
1165                (- max rank)
1166              (1+ max)))))
1167       (message-sort-headers-1))))
1168
1169 \f
1170
1171 ;;;
1172 ;;; Message mode
1173 ;;;
1174
1175 ;;; Set up keymap.
1176
1177 (defvar message-mode-map nil)
1178
1179 (unless message-mode-map
1180   (setq message-mode-map (copy-keymap text-mode-map))
1181   (define-key message-mode-map "\C-c?" 'describe-mode)
1182
1183   (define-key message-mode-map "\C-c\C-f\C-t" 'message-goto-to)
1184   (define-key message-mode-map "\C-c\C-f\C-b" 'message-goto-bcc)
1185   (define-key message-mode-map "\C-c\C-f\C-w" 'message-goto-fcc)
1186   (define-key message-mode-map "\C-c\C-f\C-c" 'message-goto-cc)
1187   (define-key message-mode-map "\C-c\C-f\C-s" 'message-goto-subject)
1188   (define-key message-mode-map "\C-c\C-f\C-r" 'message-goto-reply-to)
1189   (define-key message-mode-map "\C-c\C-f\C-n" 'message-goto-newsgroups)
1190   (define-key message-mode-map "\C-c\C-f\C-d" 'message-goto-distribution)
1191   (define-key message-mode-map "\C-c\C-f\C-f" 'message-goto-followup-to)
1192   (define-key message-mode-map "\C-c\C-f\C-k" 'message-goto-keywords)
1193   (define-key message-mode-map "\C-c\C-f\C-u" 'message-goto-summary)
1194   (define-key message-mode-map "\C-c\C-b" 'message-goto-body)
1195   (define-key message-mode-map "\C-c\C-i" 'message-goto-signature)
1196
1197   (define-key message-mode-map "\C-c\C-t" 'message-insert-to)
1198   (define-key message-mode-map "\C-c\C-n" 'message-insert-newsgroups)
1199
1200   (define-key message-mode-map "\C-c\C-y" 'message-yank-original)
1201   (define-key message-mode-map "\C-c\C-q" 'message-fill-yanked-message)
1202   (define-key message-mode-map "\C-c\C-w" 'message-insert-signature)
1203   (define-key message-mode-map "\C-c\C-r" 'message-caesar-buffer-body)
1204   (define-key message-mode-map "\C-c\C-o" 'message-sort-headers)
1205   (define-key message-mode-map "\C-c\M-r" 'message-rename-buffer)
1206
1207   (define-key message-mode-map "\C-c\C-c" 'message-send-and-exit)
1208   (define-key message-mode-map "\C-c\C-s" 'message-send)
1209   (define-key message-mode-map "\C-c\C-k" 'message-kill-buffer)
1210   (define-key message-mode-map "\C-c\C-d" 'message-dont-send)
1211
1212   (define-key message-mode-map "\C-c\C-e" 'message-elide-region)
1213   (define-key message-mode-map "\C-c\C-v" 'message-delete-not-region)
1214   (define-key message-mode-map "\C-c\C-z" 'message-kill-to-signature)
1215   (define-key message-mode-map "\M-\r" 'message-newline-and-reformat)
1216
1217   (define-key message-mode-map "\t" 'message-tab))
1218
1219 (easy-menu-define
1220  message-mode-menu message-mode-map "Message Menu."
1221  '("Message"
1222    ["Sort Headers" message-sort-headers t]
1223    ["Yank Original" message-yank-original t]
1224    ["Fill Yanked Message" message-fill-yanked-message t]
1225    ["Insert Signature" message-insert-signature t]
1226    ["Caesar (rot13) Message" message-caesar-buffer-body t]
1227    ["Caesar (rot13) Region" message-caesar-region (mark t)]
1228    ["Elide Region" message-elide-region (mark t)]
1229    ["Delete Outside Region" message-delete-not-region (mark t)]
1230    ["Kill To Signature" message-kill-to-signature t]
1231    ["Newline and Reformat" message-newline-and-reformat t]
1232    ["Rename buffer" message-rename-buffer t]
1233    ["Spellcheck" ispell-message t]
1234    "----"
1235    ["Send Message" message-send-and-exit t]
1236    ["Abort Message" message-dont-send t]))
1237
1238 (easy-menu-define
1239  message-mode-field-menu message-mode-map ""
1240  '("Field"
1241    ["Fetch To" message-insert-to t]
1242    ["Fetch Newsgroups" message-insert-newsgroups t]
1243    "----"
1244    ["To" message-goto-to t]
1245    ["Subject" message-goto-subject t]
1246    ["Cc" message-goto-cc t]
1247    ["Reply-To" message-goto-reply-to t]
1248    ["Summary" message-goto-summary t]
1249    ["Keywords" message-goto-keywords t]
1250    ["Newsgroups" message-goto-newsgroups t]
1251    ["Followup-To" message-goto-followup-to t]
1252    ["Distribution" message-goto-distribution t]
1253    ["Body" message-goto-body t]
1254    ["Signature" message-goto-signature t]))
1255
1256 (defvar facemenu-add-face-function)
1257 (defvar facemenu-remove-face-function)
1258
1259 ;;;###autoload
1260 (defun message-mode ()
1261   "Major mode for editing mail and news to be sent.
1262 Like Text Mode but with these additional commands:
1263 C-c C-s  message-send (send the message)    C-c C-c  message-send-and-exit
1264 C-c C-f  move to a header field (and create it if there isn't):
1265          C-c C-f C-t  move to To        C-c C-f C-s  move to Subject
1266          C-c C-f C-c  move to Cc        C-c C-f C-b  move to Bcc
1267          C-c C-f C-w  move to Fcc       C-c C-f C-r  move to Reply-To
1268          C-c C-f C-u  move to Summary   C-c C-f C-n  move to Newsgroups
1269          C-c C-f C-k  move to Keywords  C-c C-f C-d  move to Distribution
1270          C-c C-f C-f  move to Followup-To
1271 C-c C-t  message-insert-to (add a To header to a news followup)
1272 C-c C-n  message-insert-newsgroups (add a Newsgroup header to a news reply)
1273 C-c C-b  message-goto-body (move to beginning of message text).
1274 C-c C-i  message-goto-signature (move to the beginning of the signature).
1275 C-c C-w  message-insert-signature (insert `message-signature-file' file).
1276 C-c C-y  message-yank-original (insert current message, if any).
1277 C-c C-q  message-fill-yanked-message (fill what was yanked).
1278 C-c C-e  message-elide-region (elide the text between point and mark).
1279 C-c C-z  message-kill-to-signature (kill the text up to the signature).
1280 C-c C-r  message-caesar-buffer-body (rot13 the message body)."
1281   (interactive)
1282   (kill-all-local-variables)
1283   (make-local-variable 'message-reply-buffer)
1284   (setq message-reply-buffer nil)
1285   (make-local-variable 'message-send-actions) 
1286   (make-local-variable 'message-exit-actions) 
1287   (make-local-variable 'message-kill-actions)
1288   (make-local-variable 'message-postpone-actions)
1289   (make-local-variable 'message-draft-article)
1290   (make-local-hook 'kill-buffer-hook)
1291   (set-syntax-table message-mode-syntax-table)
1292   (use-local-map message-mode-map)
1293   (setq local-abbrev-table message-mode-abbrev-table)
1294   (setq major-mode 'message-mode)
1295   (setq mode-name "Message")
1296   (setq buffer-offer-save t)
1297   (make-local-variable 'facemenu-add-face-function)
1298   (make-local-variable 'facemenu-remove-face-function)
1299   (setq facemenu-add-face-function
1300         (lambda (face end)
1301           (let ((face-fun (cdr (assq face message-face-alist))))
1302             (if face-fun
1303                 (funcall face-fun (point) end)
1304               (error "Face %s not configured for %s mode" face mode-name)))
1305           "")
1306         facemenu-remove-face-function t)
1307   (make-local-variable 'paragraph-separate)
1308   (make-local-variable 'paragraph-start)
1309   (setq paragraph-start
1310         (concat (regexp-quote mail-header-separator)
1311                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1312                 "-- $\\|"
1313                 ;;!!! Uhm... shurely this can't be right?
1314                 "[> " (regexp-quote message-yank-prefix) "]+$\\|"
1315                 paragraph-start))
1316   (setq paragraph-separate
1317         (concat (regexp-quote mail-header-separator)
1318                 "$\\|[ \t]*[-_][-_][-_]+$\\|"
1319                 "-- $\\|"
1320                 "[> " (regexp-quote message-yank-prefix) "]+$\\|"
1321                 paragraph-separate))
1322   (make-local-variable 'message-reply-headers)
1323   (setq message-reply-headers nil)
1324   (make-local-variable 'message-newsreader)
1325   (make-local-variable 'message-mailer)
1326   (make-local-variable 'message-post-method)
1327   (make-local-variable 'message-sent-message-via)
1328   (setq message-sent-message-via nil)
1329   (make-local-variable 'message-checksum)
1330   (setq message-checksum nil)
1331   ;;(when (fboundp 'mail-hist-define-keys)
1332   ;;  (mail-hist-define-keys))
1333   (when (string-match "XEmacs\\|Lucid" emacs-version)
1334     (message-setup-toolbar))
1335   (easy-menu-add message-mode-menu message-mode-map)
1336   (easy-menu-add message-mode-field-menu message-mode-map)
1337   ;; Allow mail alias things.
1338   (when (eq message-mail-alias-type 'abbrev)
1339     (if (fboundp 'mail-abbrevs-setup)
1340         (mail-abbrevs-setup)
1341       (funcall (intern "mail-aliases-setup"))))
1342   (message-set-auto-save-file-name)
1343   (unless (string-match "XEmacs" emacs-version)
1344     (set (make-local-variable 'font-lock-defaults)
1345          '(message-font-lock-keywords t)))
1346   (make-local-variable 'adaptive-fill-regexp)
1347   (setq adaptive-fill-regexp
1348         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|" adaptive-fill-regexp))
1349   (unless (boundp 'adaptive-fill-first-line-regexp)
1350     (setq adaptive-fill-first-line-regexp nil))
1351   (make-local-variable 'adaptive-fill-first-line-regexp)
1352   (setq adaptive-fill-first-line-regexp
1353         (concat "[ \t]*[-a-z0-9A-Z]*>+[ \t]*\\|"
1354                 adaptive-fill-first-line-regexp))
1355   (run-hooks 'text-mode-hook 'message-mode-hook))
1356
1357 \f
1358
1359 ;;;
1360 ;;; Message mode commands
1361 ;;;
1362
1363 ;;; Movement commands
1364
1365 (defun message-goto-to ()
1366   "Move point to the To header."
1367   (interactive)
1368   (message-position-on-field "To"))
1369
1370 (defun message-goto-subject ()
1371   "Move point to the Subject header."
1372   (interactive)
1373   (message-position-on-field "Subject"))
1374
1375 (defun message-goto-cc ()
1376   "Move point to the Cc header."
1377   (interactive)
1378   (message-position-on-field "Cc" "To"))
1379
1380 (defun message-goto-bcc ()
1381   "Move point to the Bcc  header."
1382   (interactive)
1383   (message-position-on-field "Bcc" "Cc" "To"))
1384
1385 (defun message-goto-fcc ()
1386   "Move point to the Fcc header."
1387   (interactive)
1388   (message-position-on-field "Fcc" "To" "Newsgroups"))
1389
1390 (defun message-goto-reply-to ()
1391   "Move point to the Reply-To header."
1392   (interactive)
1393   (message-position-on-field "Reply-To" "Subject"))
1394
1395 (defun message-goto-newsgroups ()
1396   "Move point to the Newsgroups header."
1397   (interactive)
1398   (message-position-on-field "Newsgroups"))
1399
1400 (defun message-goto-distribution ()
1401   "Move point to the Distribution header."
1402   (interactive)
1403   (message-position-on-field "Distribution"))
1404
1405 (defun message-goto-followup-to ()
1406   "Move point to the Followup-To header."
1407   (interactive)
1408   (message-position-on-field "Followup-To" "Newsgroups"))
1409
1410 (defun message-goto-keywords ()
1411   "Move point to the Keywords header."
1412   (interactive)
1413   (message-position-on-field "Keywords" "Subject"))
1414
1415 (defun message-goto-summary ()
1416   "Move point to the Summary header."
1417   (interactive)
1418   (message-position-on-field "Summary" "Subject"))
1419
1420 (defun message-goto-body ()
1421   "Move point to the beginning of the message body."
1422   (interactive)
1423   (if (looking-at "[ \t]*\n") (expand-abbrev))
1424   (goto-char (point-min))
1425   (search-forward (concat "\n" mail-header-separator "\n") nil t))
1426
1427 (defun message-goto-signature ()
1428   "Move point to the beginning of the message signature."
1429   (interactive)
1430   (goto-char (point-min))
1431   (if (re-search-forward message-signature-separator nil t)
1432       (forward-line 1)
1433     (goto-char (point-max))))
1434
1435 \f
1436
1437 (defun message-insert-to (&optional force)
1438   "Insert a To header that points to the author of the article being replied to.
1439 If the original author requested not to be sent mail, the function signals
1440 an error.
1441 With the prefix argument FORCE, insert the header anyway."
1442   (interactive "P")
1443   (let ((co (message-fetch-reply-field "mail-copies-to")))
1444     (when (and (null force)
1445                co
1446                (equal (downcase co) "never"))
1447       (error "The user has requested not to have copies sent via mail")))
1448   (when (and (message-position-on-field "To")
1449              (mail-fetch-field "to")
1450              (not (string-match "\\` *\\'" (mail-fetch-field "to"))))
1451     (insert ", "))
1452   (insert (or (message-fetch-reply-field "reply-to")
1453               (message-fetch-reply-field "from") "")))
1454
1455 (defun message-insert-newsgroups ()
1456   "Insert the Newsgroups header from the article being replied to."
1457   (interactive)
1458   (when (and (message-position-on-field "Newsgroups")
1459              (mail-fetch-field "newsgroups")
1460              (not (string-match "\\` *\\'" (mail-fetch-field "newsgroups"))))
1461     (insert ","))
1462   (insert (or (message-fetch-reply-field "newsgroups") "")))
1463
1464 \f
1465
1466 ;;; Various commands
1467
1468 (defun message-delete-not-region (beg end)
1469   "Delete everything in the body of the current message that is outside of the region."
1470   (interactive "r")
1471   (save-excursion
1472     (goto-char end)
1473     (delete-region (point) (progn (message-goto-signature)
1474                                   (forward-line -2)
1475                                   (point)))
1476     (insert "\n")
1477     (goto-char beg)
1478     (delete-region beg (progn (message-goto-body)
1479                               (forward-line 2)
1480                               (point))))
1481   (message-goto-signature)
1482   (forward-line -2))
1483
1484 (defun message-kill-to-signature ()
1485   "Deletes all text up to the signature."
1486   (interactive)
1487   (let ((point (point)))
1488     (message-goto-signature)
1489     (unless (eobp)
1490       (forward-line -2))
1491     (kill-region point (point))
1492     (unless (bolp)
1493       (insert "\n"))))
1494
1495 (defun message-newline-and-reformat ()
1496   "Insert four newlines, and then reformat if inside quoted text."
1497   (interactive)
1498   (let ((point (point))
1499         quoted)
1500     (save-excursion
1501       (beginning-of-line)
1502       (setq quoted (looking-at (regexp-quote message-yank-prefix))))
1503     (insert "\n\n\n\n")
1504     (when quoted
1505       (insert message-yank-prefix))
1506     (fill-paragraph nil)
1507     (goto-char point)
1508     (forward-line 2)))
1509
1510 (defun message-insert-signature (&optional force)
1511   "Insert a signature.  See documentation for the `message-signature' variable."
1512   (interactive (list 0))
1513   (let* ((signature
1514           (cond
1515            ((and (null message-signature)
1516                  (eq force 0))
1517             (save-excursion
1518               (goto-char (point-max))
1519               (not (re-search-backward
1520                     message-signature-separator nil t))))
1521            ((and (null message-signature)
1522                  force)
1523             t)
1524            ((message-functionp message-signature)
1525             (funcall message-signature))
1526            ((listp message-signature)
1527             (eval message-signature))
1528            (t message-signature)))
1529          (signature
1530           (cond ((stringp signature)
1531                  signature)
1532                 ((and (eq t signature)
1533                       message-signature-file
1534                       (file-exists-p message-signature-file))
1535                  signature))))
1536     (when signature
1537       (goto-char (point-max))
1538       ;; Insert the signature.
1539       (unless (bolp)
1540         (insert "\n"))
1541       (insert "\n-- \n")
1542       (if (eq signature t)
1543           (insert-file-contents message-signature-file)
1544         (insert signature))
1545       (goto-char (point-max))
1546       (or (bolp) (insert "\n")))))
1547
1548 (defun message-elide-region (b e)
1549   "Elide the text between point and mark.
1550 An ellipsis (from `message-elide-elipsis') will be inserted where the
1551 text was killed."
1552   (interactive "r")
1553   (kill-region b e)
1554   (unless (bolp)
1555     (insert "\n"))
1556   (insert message-elide-elipsis))
1557
1558 (defvar message-caesar-translation-table nil)
1559
1560 (defun message-caesar-region (b e &optional n)
1561   "Caesar rotation of region by N, default 13, for decrypting netnews."
1562   (interactive
1563    (list
1564     (min (point) (or (mark t) (point)))
1565     (max (point) (or (mark t) (point)))
1566     (when current-prefix-arg
1567       (prefix-numeric-value current-prefix-arg))))
1568
1569   (setq n (if (numberp n) (mod n 26) 13)) ;canonize N
1570   (unless (or (zerop n)                 ; no action needed for a rot of 0
1571               (= b e))                  ; no region to rotate
1572     ;; We build the table, if necessary.
1573     (when (or (not message-caesar-translation-table)
1574               (/= (aref message-caesar-translation-table ?a) (+ ?a n)))
1575         (setq message-caesar-translation-table
1576               (message-make-caesar-translation-table n)))
1577     ;; Then we translate the region.  Do it this way to retain
1578     ;; text properties.
1579     (while (< b e)
1580       (subst-char-in-region
1581        b (1+ b) (char-after b)
1582        (aref message-caesar-translation-table (char-after b)))
1583       (incf b))))
1584
1585 (defun message-make-caesar-translation-table (n)
1586   "Create a rot table with offset N."
1587   (let ((i -1)
1588         (table (make-string 256 0)))
1589     (while (< (incf i) 256)
1590       (aset table i i))
1591     (concat
1592      (substring table 0 ?A)
1593      (substring table (+ ?A n) (+ ?A n (- 26 n)))
1594      (substring table ?A (+ ?A n))
1595      (substring table (+ ?A 26) ?a)
1596      (substring table (+ ?a n) (+ ?a n (- 26 n)))
1597      (substring table ?a (+ ?a n))
1598      (substring table (+ ?a 26) 255))))
1599
1600 (defun message-caesar-buffer-body (&optional rotnum)
1601   "Caesar rotates all letters in the current buffer by 13 places.
1602 Used to encode/decode possiblyun offensive messages (commonly in net.jokes).
1603 With prefix arg, specifies the number of places to rotate each letter forward.
1604 Mail and USENET news headers are not rotated."
1605   (interactive (if current-prefix-arg
1606                    (list (prefix-numeric-value current-prefix-arg))
1607                  (list nil)))
1608   (save-excursion
1609     (save-restriction
1610       (when (message-goto-body)
1611         (narrow-to-region (point) (point-max)))
1612       (message-caesar-region (point-min) (point-max) rotnum))))
1613
1614 (defun message-pipe-buffer-body (program)
1615   "Pipe the message body in the current buffer through PROGRAM."
1616   (save-excursion
1617     (save-restriction
1618       (when (message-goto-body)
1619         (narrow-to-region (point) (point-max)))
1620       (let ((body (buffer-substring (point-min) (point-max))))
1621         (unless (equal 0 (call-process-region
1622                            (point-min) (point-max) program t t))
1623             (insert body)
1624             (message "%s failed." program))))))
1625
1626 (defun message-rename-buffer (&optional enter-string)
1627   "Rename the *message* buffer to \"*message* RECIPIENT\".
1628 If the function is run with a prefix, it will ask for a new buffer
1629 name, rather than giving an automatic name."
1630   (interactive "Pbuffer name: ")
1631   (save-excursion
1632     (save-restriction
1633       (goto-char (point-min))
1634       (narrow-to-region (point)
1635                         (search-forward mail-header-separator nil 'end))
1636       (let* ((mail-to (or
1637                        (if (message-news-p) (message-fetch-field "Newsgroups")
1638                          (message-fetch-field "To"))
1639                        ""))
1640              (mail-trimmed-to
1641               (if (string-match "," mail-to)
1642                   (concat (substring mail-to 0 (match-beginning 0)) ", ...")
1643                 mail-to))
1644              (name-default (concat "*message* " mail-trimmed-to))
1645              (name (if enter-string
1646                        (read-string "New buffer name: " name-default)
1647                      name-default)))
1648         (rename-buffer name t)))))
1649
1650 (defun message-fill-yanked-message (&optional justifyp)
1651   "Fill the paragraphs of a message yanked into this one.
1652 Numeric argument means justify as well."
1653   (interactive "P")
1654   (save-excursion
1655     (goto-char (point-min))
1656     (search-forward (concat "\n" mail-header-separator "\n") nil t)
1657     (let ((fill-prefix message-yank-prefix))
1658       (fill-individual-paragraphs (point) (point-max) justifyp t))))
1659
1660 (defun message-indent-citation ()
1661   "Modify text just inserted from a message to be cited.
1662 The inserted text should be the region.
1663 When this function returns, the region is again around the modified text.
1664
1665 Normally, indent each nonblank line `message-indentation-spaces' spaces.
1666 However, if `message-yank-prefix' is non-nil, insert that prefix on each line."
1667   (let ((start (point)))
1668     ;; Remove unwanted headers.
1669     (when message-ignored-cited-headers
1670       (let (all-removed)
1671         (save-restriction
1672           (narrow-to-region
1673            (goto-char start)
1674            (if (search-forward "\n\n" nil t)
1675                (1- (point))
1676              (point)))
1677           (message-remove-header message-ignored-cited-headers t)
1678           (when (= (point-min) (point-max))
1679             (setq all-removed t))
1680           (goto-char (point-max)))
1681         (if all-removed
1682             (goto-char start)
1683           (forward-line 1))))
1684     ;; Delete blank lines at the start of the buffer.
1685     (while (and (point-min)
1686                 (eolp)
1687                 (not (eobp)))
1688       (message-delete-line))
1689     ;; Delete blank lines at the end of the buffer.
1690     (goto-char (point-max))
1691     (unless (eolp)
1692       (insert "\n"))
1693     (while (and (zerop (forward-line -1))
1694                 (looking-at "$"))
1695       (message-delete-line))
1696     ;; Do the indentation.
1697     (if (null message-yank-prefix)
1698         (indent-rigidly start (mark t) message-indentation-spaces)
1699       (save-excursion
1700         (goto-char start)
1701         (while (< (point) (mark t))
1702           (insert message-yank-prefix)
1703           (forward-line 1))))
1704     (goto-char start)))
1705
1706 (defun message-yank-original (&optional arg)
1707   "Insert the message being replied to, if any.
1708 Puts point before the text and mark after.
1709 Normally indents each nonblank line ARG spaces (default 3).  However,
1710 if `message-yank-prefix' is non-nil, insert that prefix on each line.
1711
1712 This function uses `message-cite-function' to do the actual citing.
1713
1714 Just \\[universal-argument] as argument means don't indent, insert no
1715 prefix, and don't delete any headers."
1716   (interactive "P")
1717   (let ((modified (buffer-modified-p)))
1718     (when (and message-reply-buffer
1719                message-cite-function)
1720       (delete-windows-on message-reply-buffer t)
1721       (insert-buffer message-reply-buffer)
1722       (funcall message-cite-function)
1723       (message-exchange-point-and-mark)
1724       (unless (bolp)
1725         (insert ?\n))
1726       (unless modified
1727         (setq message-checksum (cons (message-checksum) (buffer-size)))))))
1728
1729 (defun message-cite-original-without-signature ()
1730   "Cite function in the standard Message manner."
1731   (let ((start (point))
1732         (end (mark t))
1733         (functions
1734          (when message-indent-citation-function
1735            (if (listp message-indent-citation-function)
1736                message-indent-citation-function
1737              (list message-indent-citation-function)))))
1738     (goto-char end)
1739     (when (re-search-backward "^-- $" start t)
1740       (delete-region (point) end))
1741     (goto-char start)
1742     (while functions
1743       (funcall (pop functions)))
1744     (when message-citation-line-function
1745       (unless (bolp)
1746         (insert "\n"))
1747       (funcall message-citation-line-function))))
1748
1749 (defun message-cite-original ()
1750   "Cite function in the standard Message manner."
1751   (let ((start (point))
1752         (functions
1753          (when message-indent-citation-function
1754            (if (listp message-indent-citation-function)
1755                message-indent-citation-function
1756              (list message-indent-citation-function)))))
1757     (goto-char start)
1758     (while functions
1759       (funcall (pop functions)))
1760     (when message-citation-line-function
1761       (unless (bolp)
1762         (insert "\n"))
1763       (funcall message-citation-line-function))))
1764
1765 (defun message-insert-citation-line ()
1766   "Function that inserts a simple citation line."
1767   (when message-reply-headers
1768     (insert (mail-header-from message-reply-headers) " writes:\n\n")))
1769
1770 (defun message-position-on-field (header &rest afters)
1771   (let ((case-fold-search t))
1772     (save-restriction
1773       (narrow-to-region
1774        (goto-char (point-min))
1775        (progn
1776          (re-search-forward
1777           (concat "^" (regexp-quote mail-header-separator) "$"))
1778          (match-beginning 0)))
1779       (goto-char (point-min))
1780       (if (re-search-forward (concat "^" (regexp-quote header) ":") nil t)
1781           (progn
1782             (re-search-forward "^[^ \t]" nil 'move)
1783             (beginning-of-line)
1784             (skip-chars-backward "\n")
1785             t)
1786         (while (and afters
1787                     (not (re-search-forward
1788                           (concat "^" (regexp-quote (car afters)) ":")
1789                           nil t)))
1790           (pop afters))
1791         (when afters
1792           (re-search-forward "^[^ \t]" nil 'move)
1793           (beginning-of-line))
1794         (insert header ": \n")
1795         (forward-char -1)
1796         nil))))
1797
1798 (defun message-remove-signature ()
1799   "Remove the signature from the text between point and mark.
1800 The text will also be indented the normal way."
1801   (save-excursion
1802     (let ((start (point))
1803           mark)
1804       (if (not (re-search-forward message-signature-separator (mark t) t))
1805           ;; No signature here, so we just indent the cited text.
1806           (message-indent-citation)
1807         ;; Find the last non-empty line.
1808         (forward-line -1)
1809         (while (looking-at "[ \t]*$")
1810           (forward-line -1))
1811         (forward-line 1)
1812         (setq mark (set-marker (make-marker) (point)))
1813         (goto-char start)
1814         (message-indent-citation)
1815         ;; Enable undoing the deletion.
1816         (undo-boundary)
1817         (delete-region mark (mark t))
1818         (set-marker mark nil)))))
1819
1820 \f
1821
1822 ;;;
1823 ;;; Sending messages
1824 ;;;
1825
1826 (defun message-send-and-exit (&optional arg)
1827   "Send message like `message-send', then, if no errors, exit from mail buffer."
1828   (interactive "P")
1829   (let ((buf (current-buffer))
1830         (actions message-exit-actions))
1831     (when (and (message-send arg)
1832                (buffer-name buf))
1833       (if message-kill-buffer-on-exit
1834           (kill-buffer buf)
1835         (bury-buffer buf)
1836         (when (eq buf (current-buffer))
1837           (message-bury buf)))
1838       (message-do-actions actions))))
1839
1840 (defun message-dont-send ()
1841   "Don't send the message you have been editing."
1842   (interactive)
1843   (set-buffer-modified-p t)
1844   (save-buffer)
1845   (let ((actions message-postpone-actions))
1846     (message-bury (current-buffer))
1847     (message-do-actions actions)))
1848
1849 (defun message-kill-buffer ()
1850   "Kill the current buffer."
1851   (interactive)
1852   (when (or (not (buffer-modified-p))
1853             (yes-or-no-p "Message modified; kill anyway? "))
1854     (let ((actions message-kill-actions))
1855       (setq buffer-file-name nil)
1856       (kill-buffer (current-buffer))
1857       (message-do-actions actions))))
1858
1859 (defun message-bury (buffer)
1860   "Bury this mail buffer."
1861   (let ((newbuf (other-buffer buffer)))
1862     (bury-buffer buffer)
1863     (if (and (fboundp 'frame-parameters)
1864              (cdr (assq 'dedicated (frame-parameters)))
1865              (not (null (delq (selected-frame) (visible-frame-list)))))
1866         (delete-frame (selected-frame))
1867       (switch-to-buffer newbuf))))
1868
1869 (defun message-send (&optional arg)
1870   "Send the message in the current buffer.
1871 If `message-interactive' is non-nil, wait for success indication
1872 or error messages, and inform user.
1873 Otherwise any failure is reported in a message back to
1874 the user from the mailer."
1875   (interactive "P")
1876   ;; Disabled test.
1877   (when (or (buffer-modified-p)
1878             (message-check-element 'unchanged)
1879             (y-or-n-p "No changes in the buffer; really send? "))
1880     ;; Make it possible to undo the coming changes.
1881     (undo-boundary)
1882     (let ((inhibit-read-only t))
1883       (put-text-property (point-min) (point-max) 'read-only nil))
1884     (message-fix-before-sending)
1885     (run-hooks 'message-send-hook)
1886     (message "Sending...")
1887     (let ((message-encoding-buffer
1888            (message-generate-new-buffer-clone-locals " message encoding"))
1889           (message-edit-buffer (current-buffer))
1890           (message-mime-mode mime-edit-mode-flag)
1891           (alist message-send-method-alist)
1892           (success t)
1893           elem sent)
1894       (save-excursion
1895         (set-buffer message-encoding-buffer)
1896         (erase-buffer)
1897         (insert-buffer message-edit-buffer)
1898         (funcall message-encode-function)
1899         (while (and success
1900                     (setq elem (pop alist)))
1901           (when (and (or (not (funcall (cadr elem)))
1902                          (and (or (not (memq (car elem)
1903                                              message-sent-message-via))
1904                                   (y-or-n-p
1905                                    (format
1906                                     "Already sent message via %s; resend? "
1907                                     (car elem))))
1908                               (setq success (funcall (caddr elem) arg)))))
1909             (setq sent t))))
1910       (when (and success sent)
1911         (message-do-fcc)
1912         ;;(when (fboundp 'mail-hist-put-headers-into-history)
1913         ;; (mail-hist-put-headers-into-history))
1914         (run-hooks 'message-sent-hook)
1915         (message "Sending...done")
1916         ;; Mark the buffer as unmodified and delete autosave.
1917         (set-buffer-modified-p nil)
1918         (delete-auto-save-file-if-necessary t)
1919         (message-disassociate-draft)
1920         ;; Delete other mail buffers and stuff.
1921         (message-do-send-housekeeping)
1922         (message-do-actions message-send-actions)
1923         ;; Return success.
1924         t))))
1925
1926 (defun message-send-via-mail (arg)
1927   "Send the current message via mail."  
1928   (message-send-mail arg))
1929
1930 (defun message-send-via-news (arg)
1931   "Send the current message via news."
1932   (message-send-news arg))
1933
1934 (defun message-fix-before-sending ()
1935   "Do various things to make the message nice before sending it."
1936   ;; Make sure there's a newline at the end of the message.
1937   (goto-char (point-max))
1938   (unless (bolp)
1939     (insert "\n")))
1940
1941 (defun message-add-action (action &rest types)
1942   "Add ACTION to be performed when doing an exit of type TYPES."
1943   (let (var)
1944     (while types
1945       (set (setq var (intern (format "message-%s-actions" (pop types))))
1946            (nconc (symbol-value var) (list action))))))
1947
1948 (defun message-do-actions (actions)
1949   "Perform all actions in ACTIONS."
1950   ;; Now perform actions on successful sending.
1951   (while actions
1952     (ignore-errors
1953       (cond
1954        ;; A simple function.
1955        ((message-functionp (car actions))
1956         (funcall (car actions)))
1957        ;; Something to be evaled.
1958        (t
1959         (eval (car actions)))))
1960     (pop actions)))
1961
1962 (defun message-send-mail (&optional arg)
1963   (require 'mail-utils)
1964   (let ((tembuf (message-generate-new-buffer-clone-locals " message temp"))
1965         (case-fold-search nil)
1966         (news (message-news-p)))
1967     (save-restriction
1968       (message-narrow-to-headers)
1969       ;; Insert some headers.
1970       (let ((message-deletable-headers
1971              (if news nil message-deletable-headers)))
1972         (message-generate-headers message-required-mail-headers))
1973       ;; Let the user do all of the above.
1974       (run-hooks 'message-header-hook))
1975     (unwind-protect
1976         (save-excursion
1977           (set-buffer tembuf)
1978           (erase-buffer)
1979           (insert-buffer message-encoding-buffer)
1980           ;; Remove some headers.
1981           (save-restriction
1982             (message-narrow-to-headers)
1983             ;; Remove some headers.
1984             (message-remove-header message-ignored-mail-headers t))
1985           (goto-char (point-max))
1986           ;; require one newline at the end.
1987           (or (= (preceding-char) ?\n)
1988               (insert ?\n))
1989           (when (and news
1990                      (or (message-fetch-field "cc")
1991                          (message-fetch-field "to")))
1992             (message-insert-courtesy-copy))
1993           (mime-edit-maybe-split-and-send
1994            (function
1995             (lambda ()
1996               (interactive)
1997               (funcall message-send-mail-function)
1998               )))
1999           (funcall message-send-mail-function))
2000       (kill-buffer tembuf))
2001     (set-buffer message-edit-buffer)
2002     (push 'mail message-sent-message-via)))
2003
2004 (defun message-send-mail-with-sendmail ()
2005   "Send off the prepared buffer with sendmail."
2006   (let ((errbuf (if message-interactive
2007                     (generate-new-buffer " sendmail errors")
2008                   0))
2009         resend-to-addresses delimline)
2010     (let ((case-fold-search t))
2011       (save-restriction
2012         (message-narrow-to-headers)
2013         (setq resend-to-addresses (message-fetch-field "resent-to")))
2014       ;; Change header-delimiter to be what sendmail expects.
2015       (goto-char (point-min))
2016       (re-search-forward
2017        (concat "^" (regexp-quote mail-header-separator) "\n"))
2018       (replace-match "\n")
2019       (backward-char 1)
2020       (setq delimline (point-marker))
2021       (run-hooks 'message-send-mail-hook)
2022       ;; Insert an extra newline if we need it to work around
2023       ;; Sun's bug that swallows newlines.
2024       (goto-char (1+ delimline))
2025       (when (eval message-mailer-swallows-blank-line)
2026         (newline))
2027       (when message-interactive
2028         (save-excursion
2029           (set-buffer errbuf)
2030           (erase-buffer))))
2031     (let ((default-directory "/")
2032           (coding-system-for-write 'binary))
2033       (apply 'call-process-region
2034              (append (list (point-min) (point-max)
2035                            (if (boundp 'sendmail-program)
2036                                sendmail-program
2037                              "/usr/lib/sendmail")
2038                            nil errbuf nil "-oi")
2039                      ;; Always specify who from,
2040                      ;; since some systems have broken sendmails.
2041                      ;; But some systems are more broken with -f, so
2042                      ;; we'll let users override this.
2043                      (if (null message-sendmail-f-is-evil)
2044                          (list "-f" (user-login-name)))
2045                      ;; These mean "report errors by mail"
2046                      ;; and "deliver in background".
2047                      (if (null message-interactive) '("-oem" "-odb"))
2048                      ;; Get the addresses from the message
2049                      ;; unless this is a resend.
2050                      ;; We must not do that for a resend
2051                      ;; because we would find the original addresses.
2052                      ;; For a resend, include the specific addresses.
2053                      (if resend-to-addresses
2054                          (list resend-to-addresses)
2055                        '("-t")))))
2056     (when message-interactive
2057       (save-excursion
2058         (set-buffer errbuf)
2059         (goto-char (point-min))
2060         (while (re-search-forward "\n\n* *" nil t)
2061           (replace-match "; "))
2062         (if (not (zerop (buffer-size)))
2063             (error "Sending...failed to %s"
2064                    (buffer-substring (point-min) (point-max)))))
2065       (when (bufferp errbuf)
2066         (kill-buffer errbuf)))))
2067
2068 (defun message-send-mail-with-qmail ()
2069   "Pass the prepared message buffer to qmail-inject.
2070 Refer to the documentation for the variable `message-send-mail-function'
2071 to find out how to use this."
2072   ;; replace the header delimiter with a blank line
2073   (goto-char (point-min))
2074   (re-search-forward
2075    (concat "^" (regexp-quote mail-header-separator) "\n"))
2076   (replace-match "\n")
2077   (run-hooks 'message-send-mail-hook)
2078   ;; send the message
2079   (case
2080       (let ((coding-system-for-write 'binary))
2081         (apply
2082          'call-process-region 1 (point-max) message-qmail-inject-program
2083          nil nil nil
2084          ;; qmail-inject's default behaviour is to look for addresses on the
2085          ;; command line; if there're none, it scans the headers.
2086          ;; yes, it does The Right Thing w.r.t. Resent-To and it's kin.
2087          ;;
2088          ;; in general, ALL of qmail-inject's defaults are perfect for simply
2089          ;; reading a formatted (i. e., at least a To: or Resent-To header)
2090          ;; message from stdin.
2091          ;;
2092          ;; qmail also has the advantage of not having been raped by
2093          ;; various vendors, so we don't have to allow for that, either --
2094          ;; compare this with message-send-mail-with-sendmail and weep
2095          ;; for sendmail's lost innocence.
2096          ;;
2097          ;; all this is way cool coz it lets us keep the arguments entirely
2098          ;; free for -inject-arguments -- a big win for the user and for us
2099          ;; since we don't have to play that double-guessing game and the user
2100          ;; gets full control (no gestapo'ish -f's, for instance).  --sj
2101          message-qmail-inject-args))
2102     ;; qmail-inject doesn't say anything on it's stdout/stderr,
2103     ;; we have to look at the retval instead
2104     (0 nil)
2105     (1   (error "qmail-inject reported permanent failure"))
2106     (111 (error "qmail-inject reported transient failure"))
2107     ;; should never happen
2108     (t   (error "qmail-inject reported unknown failure"))))
2109
2110 (defun message-send-mail-with-mh ()
2111   "Send the prepared message buffer with mh."
2112   (let ((mh-previous-window-config nil)
2113         (name (mh-new-draft-name)))
2114     (setq buffer-file-name name)
2115     ;; MH wants to generate these headers itself.
2116     (when message-mh-deletable-headers
2117       (let ((headers message-mh-deletable-headers))
2118         (while headers
2119           (goto-char (point-min))
2120           (and (re-search-forward
2121                 (concat "^" (symbol-name (car headers)) ": *") nil t)
2122                (message-delete-line))
2123           (pop headers))))
2124     (run-hooks 'message-send-mail-hook)
2125     ;; Pass it on to mh.
2126     (mh-send-letter)))
2127
2128 (defun message-send-mail-with-smtp ()
2129   "Send the prepared message buffer with SMTP."
2130   (require 'smtp)
2131   (let ((errbuf (if mail-interactive
2132                     (generate-new-buffer " smtp errors")
2133                   0))
2134         (case-fold-search nil)
2135         resend-to-addresses
2136         delimline)
2137     (unwind-protect
2138         (save-excursion
2139           (goto-char (point-max))
2140           ;; require one newline at the end.
2141           (or (= (preceding-char) ?\n)
2142               (insert ?\n))
2143           ;; Change header-delimiter to be what sendmail expects.
2144           (goto-char (point-min))
2145           (re-search-forward
2146            (concat "^" (regexp-quote mail-header-separator) "\n"))
2147           (replace-match "\n")
2148           (backward-char 1)
2149           (setq delimline (point-marker))
2150           (run-hooks 'message-send-mail-hook)
2151           ;; (sendmail-synch-aliases)
2152           ;; (if mail-aliases
2153           ;;     (expand-mail-aliases (point-min) delimline))
2154           (goto-char (point-min))
2155           ;; ignore any blank lines in the header
2156           (while (and (re-search-forward "\n\n\n*" delimline t)
2157                       (< (point) delimline))
2158             (replace-match "\n"))
2159           (let ((case-fold-search t))
2160             (goto-char (point-min))
2161             (goto-char (point-min))
2162             (while (re-search-forward "^Resent-to:" delimline t)
2163               (setq resend-to-addresses
2164                     (save-restriction
2165                       (narrow-to-region (point)
2166                                         (save-excursion
2167                                           (end-of-line)
2168                                           (point)))
2169                       (append (mail-parse-comma-list)
2170                               resend-to-addresses))))
2171 ;;; Apparently this causes a duplicate Sender.
2172 ;;;         ;; If the From is different than current user, insert Sender.
2173 ;;;         (goto-char (point-min))
2174 ;;;         (and (re-search-forward "^From:"  delimline t)
2175 ;;;              (progn
2176 ;;;                (require 'mail-utils)
2177 ;;;                (not (string-equal
2178 ;;;                      (mail-strip-quoted-names
2179 ;;;                       (save-restriction
2180 ;;;                         (narrow-to-region (point-min) delimline)
2181 ;;;                         (mail-fetch-field "From")))
2182 ;;;                      (user-login-name))))
2183 ;;;              (progn
2184 ;;;                (forward-line 1)
2185 ;;;                (insert "Sender: " (user-login-name) "\n")))
2186             ;; Don't send out a blank subject line
2187             (goto-char (point-min))
2188             (if (re-search-forward "^Subject:[ \t]*\n" delimline t)
2189                 (replace-match ""))
2190             ;; Put the "From:" field in unless for some odd reason
2191             ;; they put one in themselves.
2192             (goto-char (point-min))
2193             (if (not (re-search-forward "^From:" delimline t))
2194                 (let* ((login user-mail-address)
2195                        (fullname (user-full-name)))
2196                   (cond ((eq mail-from-style 'angles)
2197                          (insert "From: " fullname)
2198                          (let ((fullname-start (+ (point-min) 6))
2199                                (fullname-end (point-marker)))
2200                            (goto-char fullname-start)
2201                            ;; Look for a character that cannot appear unquoted
2202                            ;; according to RFC 822.
2203                            (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
2204                                                   fullname-end 1)
2205                                (progn
2206                                  ;; Quote fullname, escaping specials.
2207                                  (goto-char fullname-start)
2208                                  (insert "\"")
2209                                  (while (re-search-forward "[\"\\]"
2210                                                            fullname-end 1)
2211                                    (replace-match "\\\\\\&" t))
2212                                  (insert "\""))))
2213                          (insert " <" login ">\n"))
2214                         ((eq mail-from-style 'parens)
2215                          (insert "From: " login " (")
2216                          (let ((fullname-start (point)))
2217                            (insert fullname)
2218                            (let ((fullname-end (point-marker)))
2219                              (goto-char fullname-start)
2220                              ;; RFC 822 says \ and nonmatching parentheses
2221                              ;; must be escaped in comments.
2222                              ;; Escape every instance of ()\ ...
2223                              (while (re-search-forward "[()\\]" fullname-end 1)
2224                                (replace-match "\\\\\\&" t))
2225                              ;; ... then undo escaping of matching parentheses,
2226                              ;; including matching nested parentheses.
2227                              (goto-char fullname-start)
2228                              (while (re-search-forward 
2229                                      "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2230                                      fullname-end 1)
2231                                (replace-match "\\1(\\3)" t)
2232                                (goto-char fullname-start))))
2233                          (insert ")\n"))
2234                         ((null mail-from-style)
2235                          (insert "From: " login "\n")))))
2236             ;; Insert an extra newline if we need it to work around
2237             ;; Sun's bug that swallows newlines.
2238             (goto-char (1+ delimline))
2239             (if (eval mail-mailer-swallows-blank-line)
2240                 (newline))
2241             ;; Find and handle any FCC fields.
2242             (goto-char (point-min))
2243             (if (re-search-forward "^FCC:" delimline t)
2244                 (mail-do-fcc delimline))
2245             (if mail-interactive
2246                 (save-excursion
2247                   (set-buffer errbuf)
2248                   (erase-buffer))))
2249           ;;
2250           ;;
2251           ;;
2252           (let ((recipient-address-list
2253                  (or resend-to-addresses
2254                      (smtp-deduce-address-list (current-buffer)
2255                                                (point-min) delimline))))
2256             (smtp-do-bcc delimline)
2257             
2258             (if recipient-address-list
2259                 (if (not (smtp-via-smtp recipient-address-list
2260                                         (current-buffer)))
2261                     (error "Sending failed; SMTP protocol error"))
2262               (error "Sending failed; no recipients"))
2263             ))
2264       (if (bufferp errbuf)
2265           (kill-buffer errbuf)))))
2266
2267 (defun message-send-news (&optional arg)
2268   (let ((tembuf (message-generate-new-buffer-clone-locals " *message temp*"))
2269         (case-fold-search nil)
2270         (method (if (message-functionp message-post-method)
2271                     (funcall message-post-method arg)
2272                   message-post-method))
2273         (message-syntax-checks
2274          (if arg
2275              (cons '(existing-newsgroups . disabled)
2276                    message-syntax-checks)
2277            message-syntax-checks))
2278         result)
2279     (save-restriction
2280       (message-narrow-to-headers)
2281       ;; Insert some headers.
2282       (message-generate-headers message-required-news-headers)
2283       ;; Let the user do all of the above.
2284       (run-hooks 'message-header-hook))
2285     (message-cleanup-headers)
2286     (if (not (message-check-news-syntax))
2287         (progn
2288           ;;(message "Posting not performed")
2289           nil)
2290       (unwind-protect
2291           (save-excursion
2292             (set-buffer tembuf)
2293             (buffer-disable-undo (current-buffer))
2294             (erase-buffer)
2295             (insert-buffer message-encoding-buffer)
2296             ;; Remove some headers.
2297             (save-restriction
2298               (message-narrow-to-headers)
2299               ;; Remove some headers.
2300               (message-remove-header message-ignored-news-headers t))
2301             (goto-char (point-max))
2302             ;; require one newline at the end.
2303             (or (= (preceding-char) ?\n)
2304                 (insert ?\n))
2305             (mime-edit-maybe-split-and-send
2306              (function
2307               (lambda ()
2308                 (interactive)
2309                 (save-restriction
2310                   (std11-narrow-to-header mail-header-separator)
2311                   (goto-char (point-min))
2312                   (when (re-search-forward "^Message-Id:" nil t)
2313                     (delete-region (match-end 0)(std11-field-end))
2314                     (insert (concat " " (message-make-message-id)))
2315                     ))
2316                 (funcall message-send-news-function method)
2317                 )))
2318             (setq result (funcall message-send-news-function method)))
2319         (kill-buffer tembuf))
2320       (set-buffer message-edit-buffer)
2321       (if result
2322           (push 'news message-sent-message-via)
2323         (message "Couldn't send message via news: %s"
2324                  (nnheader-get-report (car method)))
2325         nil))))
2326
2327 ;; 1997-09-29 by MORIOKA Tomohiko
2328 (defun message-send-news-with-gnus (method)
2329   (let ((case-fold-search t))
2330     ;; Remove the delimiter.
2331     (goto-char (point-min))
2332     (re-search-forward
2333      (concat "^" (regexp-quote mail-header-separator) "\n"))
2334     (replace-match "\n")
2335     (backward-char 1)
2336     (run-hooks 'message-send-news-hook)
2337     ;;(require (car method))
2338     ;;(funcall (intern (format "%s-open-server" (car method)))
2339     ;;(cadr method) (cddr method))
2340     ;;(setq result
2341     ;;    (funcall (intern (format "%s-request-post" (car method)))
2342     ;;             (cadr method)))
2343     (gnus-open-server method)
2344     (gnus-request-post method)
2345     ))
2346
2347 ;;;
2348 ;;; Header generation & syntax checking.
2349 ;;;
2350
2351 (defmacro message-check (type &rest forms)
2352   "Eval FORMS if TYPE is to be checked."
2353   `(or (message-check-element ,type)
2354        (save-excursion
2355          ,@forms)))
2356
2357 (put 'message-check 'lisp-indent-function 1)
2358 (put 'message-check 'edebug-form-spec '(form body))
2359
2360 (defun message-check-element (type)
2361   "Returns non-nil if this type is not to be checked."
2362   (if (eq message-syntax-checks 'dont-check-for-anything-just-trust-me)
2363       t
2364     (let ((able (assq type message-syntax-checks)))
2365       (and (consp able)
2366            (eq (cdr able) 'disabled)))))
2367
2368 (defun message-check-news-syntax ()
2369   "Check the syntax of the message."
2370   (save-excursion
2371     (save-restriction
2372       (widen)
2373       (and
2374        ;; We narrow to the headers and check them first.
2375        (save-excursion
2376          (save-restriction
2377            (message-narrow-to-headers)
2378            (message-check-news-header-syntax)))
2379        ;; Check the body.
2380        (save-excursion
2381          (set-buffer message-edit-buffer)
2382          (message-check-news-body-syntax))))))
2383
2384 (defun message-check-news-header-syntax ()
2385   (and
2386    ;; Check the Subject header.
2387    (message-check 'subject
2388      (let* ((case-fold-search t)
2389             (subject (message-fetch-field "subject")))
2390        (or
2391         (and subject
2392              (not (string-match "\\`[ \t]*\\'" subject)))
2393         (ignore
2394          (message
2395           "The subject field is empty or missing.  Posting is denied.")))))
2396    ;; Check for commands in Subject.
2397    (message-check 'subject-cmsg
2398      (if (string-match "^cmsg " (message-fetch-field "subject"))
2399          (y-or-n-p
2400           "The control code \"cmsg\" is in the subject.  Really post? ")
2401        t))
2402    ;; Check for multiple identical headers.
2403    (message-check 'multiple-headers
2404      (let (found)
2405        (while (and (not found)
2406                    (re-search-forward "^[^ \t:]+: " nil t))
2407          (save-excursion
2408            (or (re-search-forward
2409                 (concat "^"
2410                         (regexp-quote
2411                          (setq found
2412                                (buffer-substring
2413                                 (match-beginning 0) (- (match-end 0) 2))))
2414                         ":")
2415                 nil t)
2416                (setq found nil))))
2417        (if found
2418            (y-or-n-p (format "Multiple %s headers.  Really post? " found))
2419          t)))
2420    ;; Check for Version and Sendsys.
2421    (message-check 'sendsys
2422      (if (re-search-forward "^Sendsys:\\|^Version:" nil t)
2423          (y-or-n-p
2424           (format "The article contains a %s command.  Really post? "
2425                   (buffer-substring (match-beginning 0)
2426                                     (1- (match-end 0)))))
2427        t))
2428    ;; See whether we can shorten Followup-To.
2429    (message-check 'shorten-followup-to
2430      (let ((newsgroups (message-fetch-field "newsgroups"))
2431            (followup-to (message-fetch-field "followup-to"))
2432            to)
2433        (when (and newsgroups
2434                   (string-match "," newsgroups)
2435                   (not followup-to)
2436                   (not
2437                    (zerop
2438                     (length
2439                      (setq to (completing-read
2440                                "Followups to: (default all groups) "
2441                                (mapcar (lambda (g) (list g))
2442                                        (cons "poster"
2443                                              (message-tokenize-header
2444                                               newsgroups)))))))))
2445          (goto-char (point-min))
2446          (insert "Followup-To: " to "\n"))
2447        t))
2448    ;; Check "Shoot me".
2449    (message-check 'shoot
2450      (if (re-search-forward
2451           "Message-ID.*.i-did-not-set--mail-host-address--so-shoot-me" nil t)
2452          (y-or-n-p "You appear to have a misconfigured system.  Really post? ")
2453        t))
2454    ;; Check for Approved.
2455    (message-check 'approved
2456      (if (re-search-forward "^Approved:" nil t)
2457          (y-or-n-p "The article contains an Approved header.  Really post? ")
2458        t))
2459    ;; Check the Message-ID header.
2460    (message-check 'message-id
2461      (let* ((case-fold-search t)
2462             (message-id (message-fetch-field "message-id" t)))
2463        (or (not message-id)
2464            ;; Is there an @ in the ID?
2465            (and (string-match "@" message-id)
2466                 ;; Is there a dot in the ID?
2467                 (string-match "@[^.]*\\." message-id)
2468                 ;; Does the ID end with a dot?
2469                 (not (string-match "\\.>" message-id)))
2470            (y-or-n-p
2471             (format "The Message-ID looks strange: \"%s\".  Really post? "
2472                     message-id)))))
2473    ;; Check the Newsgroups & Followup-To headers.
2474    (message-check 'existing-newsgroups
2475      (let* ((case-fold-search t)
2476             (newsgroups (message-fetch-field "newsgroups"))
2477             (followup-to (message-fetch-field "followup-to"))
2478             (groups (message-tokenize-header
2479                      (if followup-to
2480                          (concat newsgroups "," followup-to)
2481                        newsgroups)))
2482             (hashtb (and (boundp 'gnus-active-hashtb)
2483                          gnus-active-hashtb))
2484             errors)
2485        (if (or (not hashtb)
2486                (not (boundp 'gnus-read-active-file))
2487                (not gnus-read-active-file)
2488                (eq gnus-read-active-file 'some))
2489            t
2490          (while groups
2491            (when (and (not (boundp (intern (car groups) hashtb)))
2492                       (not (equal (car groups) "poster")))
2493              (push (car groups) errors))
2494            (pop groups))
2495          (if (not errors)
2496              t
2497            (y-or-n-p
2498             (format
2499              "Really post to %s unknown group%s: %s "
2500              (if (= (length errors) 1) "this" "these")
2501              (if (= (length errors) 1) "" "s")
2502              (mapconcat 'identity errors ", ")))))))
2503    ;; Check the Newsgroups & Followup-To headers for syntax errors.
2504    (message-check 'valid-newsgroups
2505      (let ((case-fold-search t)
2506            (headers '("Newsgroups" "Followup-To"))
2507            header error)
2508        (while (and headers (not error))
2509          (when (setq header (mail-fetch-field (car headers)))
2510            (if (or
2511                 (not
2512                  (string-match
2513                   "\\`\\([-+_&.a-zA-Z0-9]+\\)?\\(,[-+_&.a-zA-Z0-9]+\\)*\\'"
2514                   header))
2515                 (memq
2516                  nil (mapcar
2517                       (lambda (g)
2518                         (not (string-match "\\.\\'\\|\\.\\." g)))
2519                       (message-tokenize-header header ","))))
2520                (setq error t)))
2521          (unless error
2522            (pop headers)))
2523        (if (not error)
2524            t
2525          (y-or-n-p
2526           (format "The %s header looks odd: \"%s\".  Really post? "
2527                   (car headers) header)))))
2528    (message-check 'repeated-newsgroups
2529      (let ((case-fold-search t)
2530            (headers '("Newsgroups" "Followup-To"))
2531            header error groups group)
2532        (while (and headers
2533                    (not error))
2534          (when (setq header (mail-fetch-field (pop headers)))
2535            (setq groups (message-tokenize-header header ","))
2536            (while (setq group (pop groups))
2537              (when (member group groups)
2538                (setq error group
2539                      groups nil)))))
2540        (if (not error)
2541            t
2542          (y-or-n-p
2543           (format "Group %s is repeated in headers.  Really post? " error)))))
2544    ;; Check the From header.
2545    (message-check 'from
2546      (let* ((case-fold-search t)
2547             (from (message-fetch-field "from"))
2548             (ad (nth 1 (mail-extract-address-components from))))
2549        (cond
2550         ((not from)
2551          (message "There is no From line.  Posting is denied.")
2552          nil)
2553         ((or (not (string-match "@[^\\.]*\\." ad)) ;larsi@ifi
2554              (string-match "\\.\\." ad) ;larsi@ifi..uio
2555              (string-match "@\\." ad)   ;larsi@.ifi.uio
2556              (string-match "\\.$" ad)   ;larsi@ifi.uio.
2557              (not (string-match "^[^@]+@[^@]+$" ad)) ;larsi.ifi.uio
2558              (string-match "(.*).*(.*)" from)) ;(lars) (lars)
2559          (message
2560           "Denied posting -- the From looks strange: \"%s\"." from)
2561          nil)
2562         (t t))))))
2563
2564 (defun message-check-news-body-syntax ()
2565   (and
2566    ;; Check for long lines.
2567    (message-check 'long-lines
2568      (goto-char (point-min))
2569      (re-search-forward
2570       (concat "^" (regexp-quote mail-header-separator) "$"))
2571      (while (and
2572              (progn
2573                (end-of-line)
2574                (< (current-column) 80))
2575              (zerop (forward-line 1))))
2576      (or (bolp)
2577          (eobp)
2578          (y-or-n-p
2579           "You have lines longer than 79 characters.  Really post? ")))
2580    ;; Check whether the article is empty.
2581    (message-check 'empty
2582      (goto-char (point-min))
2583      (re-search-forward
2584       (concat "^" (regexp-quote mail-header-separator) "$"))
2585      (forward-line 1)
2586      (let ((b (point)))
2587        (goto-char (point-max))
2588        (re-search-backward message-signature-separator nil t)
2589        (beginning-of-line)
2590        (or (re-search-backward "[^ \n\t]" b t)
2591            (y-or-n-p "Empty article.  Really post? "))))
2592    ;; Check for control characters.
2593    (message-check 'control-chars
2594      (if (re-search-forward "[\000-\007\013\015-\037\200-\237]" nil t)
2595          (y-or-n-p
2596           "The article contains control characters.  Really post? ")
2597        t))
2598    ;; Check excessive size.
2599    (message-check 'size
2600      (if (> (buffer-size) 60000)
2601          (y-or-n-p
2602           (format "The article is %d octets long.  Really post? "
2603                   (buffer-size)))
2604        t))
2605    ;; Check whether any new text has been added.
2606    (message-check 'new-text
2607      (or
2608       (not message-checksum)
2609       (not (and (eq (message-checksum) (car message-checksum))
2610                 (eq (buffer-size) (cdr message-checksum))))
2611       (y-or-n-p
2612        "It looks like no new text has been added.  Really post? ")))
2613    ;; Check the length of the signature.
2614    (message-check 'signature
2615      (goto-char (point-max))
2616      (if (or (not (re-search-backward message-signature-separator nil t))
2617              (search-forward message-forward-end-separator nil t))
2618          t
2619        (if (> (count-lines (point) (point-max)) 5)
2620            (y-or-n-p
2621             (format
2622              "Your .sig is %d lines; it should be max 4.  Really post? "
2623              (1- (count-lines (point) (point-max)))))
2624          t)))))
2625
2626 (defun message-checksum ()
2627   "Return a \"checksum\" for the current buffer."
2628   (let ((sum 0))
2629     (save-excursion
2630       (goto-char (point-min))
2631       (re-search-forward
2632        (concat "^" (regexp-quote mail-header-separator) "$"))
2633       (while (not (eobp))
2634         (when (not (looking-at "[ \t\n]"))
2635           (setq sum (logxor (ash sum 1) (if (natnump sum) 0 1)
2636                             (following-char))))
2637         (forward-char 1)))
2638     sum))
2639
2640 (defun message-do-fcc ()
2641   "Process Fcc headers in the current buffer."
2642   (let ((case-fold-search t)
2643         (coding-system-for-write 'raw-text)
2644         list file)
2645     (save-excursion
2646       (set-buffer (get-buffer-create " *message temp*"))
2647       (buffer-disable-undo (current-buffer))
2648       (erase-buffer)
2649       (insert-buffer-substring message-encoding-buffer)
2650       (save-restriction
2651         (message-narrow-to-headers)
2652         (while (setq file (message-fetch-field "fcc"))
2653           (push file list)
2654           (message-remove-header "fcc" nil t)))
2655       (run-hooks 'message-header-hook 'message-before-do-fcc-hook)
2656       (goto-char (point-min))
2657       (re-search-forward (concat "^" (regexp-quote mail-header-separator) "$"))
2658       (replace-match "" t t)
2659       ;; Process FCC operations.
2660       (while list
2661         (setq file (pop list))
2662         (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
2663             ;; Pipe the article to the program in question.
2664             (call-process-region (point-min) (point-max) shell-file-name
2665                                  nil nil nil shell-command-switch
2666                                  (match-string 1 file))
2667           ;; Save the article.
2668           (setq file (expand-file-name file))
2669           (unless (file-exists-p (file-name-directory file))
2670             (make-directory (file-name-directory file) t))
2671           (if (and message-fcc-handler-function
2672                    (not (eq message-fcc-handler-function 'rmail-output)))
2673               (funcall message-fcc-handler-function file)
2674             (if (and (file-readable-p file) (mail-file-babyl-p file))
2675                 (rmail-output file 1 nil t)
2676               (let ((mail-use-rfc822 t))
2677                 (rmail-output file 1 t t))))))
2678
2679       (kill-buffer (current-buffer)))))
2680
2681 (defun message-output (filename)
2682   "Append this article to Unix/babyl mail file.."
2683   (if (and (file-readable-p filename)
2684            (mail-file-babyl-p filename))
2685       (gnus-output-to-rmail filename t)
2686     (gnus-output-to-mail filename t)))
2687
2688 (defun message-cleanup-headers ()
2689   "Do various automatic cleanups of the headers."
2690   ;; Remove empty lines in the header.
2691   (save-restriction
2692     (message-narrow-to-headers)
2693     ;; Remove blank lines.
2694     (while (re-search-forward "^[ \t]*\n" nil t)
2695       (replace-match "" t t))
2696
2697     ;; Correct Newsgroups and Followup-To headers:  Change sequence of
2698     ;; spaces to comma and eliminate spaces around commas.  Eliminate
2699     ;; embedded line breaks.
2700     (goto-char (point-min))
2701     (while (re-search-forward "^\\(Newsgroups\\|Followup-To\\): +" nil t)
2702       (save-restriction
2703         (narrow-to-region
2704          (point)
2705          (if (re-search-forward "^[^ \t]" nil t)
2706              (match-beginning 0)
2707            (forward-line 1)
2708            (point)))
2709         (goto-char (point-min))
2710         (while (re-search-forward "\n[ \t]+" nil t)
2711           (replace-match " " t t))      ;No line breaks (too confusing)
2712         (goto-char (point-min))
2713         (while (re-search-forward "[ \t\n]*,[ \t\n]*\\|[ \t]+" nil t)
2714           (replace-match "," t t))
2715         (goto-char (point-min))
2716         ;; Remove trailing commas.
2717         (when (re-search-forward ",+$" nil t)
2718           (replace-match "" t t))))))
2719
2720 (defun message-make-date ()
2721   "Make a valid data header."
2722   (let ((now (current-time)))
2723     (timezone-make-date-arpa-standard
2724      (current-time-string now) (current-time-zone now))))
2725
2726 (defun message-make-message-id ()
2727   "Make a unique Message-ID."
2728   (concat "<" (message-unique-id)
2729           (let ((psubject (save-excursion (message-fetch-field "subject")))
2730                 (psupersedes
2731                  (save-excursion (message-fetch-field "supersedes"))))
2732             (if (or
2733                  (and message-reply-headers
2734                       (mail-header-references message-reply-headers)
2735                       (mail-header-subject message-reply-headers)
2736                       psubject
2737                       (mail-header-subject message-reply-headers)
2738                       (not (string=
2739                             (message-strip-subject-re
2740                              (mail-header-subject message-reply-headers))
2741                             (message-strip-subject-re psubject))))
2742                  (and psupersedes
2743                       (string-match "_-_@" psupersedes)))
2744                 "_-_" ""))
2745           "@" (message-make-fqdn) ">"))
2746
2747 (defvar message-unique-id-char nil)
2748
2749 ;; If you ever change this function, make sure the new version
2750 ;; cannot generate IDs that the old version could.
2751 ;; You might for example insert a "." somewhere (not next to another dot
2752 ;; or string boundary), or modify the "fsf" string.
2753 (defun message-unique-id ()
2754   ;; Don't use microseconds from (current-time), they may be unsupported.
2755   ;; Instead we use this randomly inited counter.
2756   (setq message-unique-id-char
2757         (% (1+ (or message-unique-id-char (logand (random t) (1- (lsh 1 20)))))
2758            ;; (current-time) returns 16-bit ints,
2759            ;; and 2^16*25 just fits into 4 digits i base 36.
2760            (* 25 25)))
2761   (let ((tm (current-time)))
2762     (concat
2763      (if (memq system-type '(ms-dos emx vax-vms))
2764          (let ((user (downcase (user-login-name))))
2765            (while (string-match "[^a-z0-9_]" user)
2766              (aset user (match-beginning 0) ?_))
2767            user)
2768        (message-number-base36 (user-uid) -1))
2769      (message-number-base36 (+ (car   tm)
2770                                (lsh (% message-unique-id-char 25) 16)) 4)
2771      (message-number-base36 (+ (nth 1 tm)
2772                                (lsh (/ message-unique-id-char 25) 16)) 4)
2773      ;; Append the newsreader name, because while the generated
2774      ;; ID is unique to this newsreader, other newsreaders might
2775      ;; otherwise generate the same ID via another algorithm.
2776      ".fsf")))
2777
2778 (defun message-number-base36 (num len)
2779   (if (if (< len 0)
2780           (<= num 0)
2781         (= len 0))
2782       ""
2783     (concat (message-number-base36 (/ num 36) (1- len))
2784             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
2785                                   (% num 36))))))
2786
2787 (defun message-make-organization ()
2788   "Make an Organization header."
2789   (let* ((organization
2790           (when message-user-organization
2791                 (if (message-functionp message-user-organization)
2792                     (funcall message-user-organization)
2793                   message-user-organization))))
2794     (save-excursion
2795       (message-set-work-buffer)
2796       (cond ((stringp organization)
2797              (insert organization))
2798             ((and (eq t organization)
2799                   message-user-organization-file
2800                   (file-exists-p message-user-organization-file))
2801              (insert-file-contents message-user-organization-file)))
2802       (goto-char (point-min))
2803       (while (re-search-forward "[\t\n]+" nil t)
2804         (replace-match "" t t))
2805       (unless (zerop (buffer-size))
2806         (buffer-string)))))
2807
2808 (defun message-make-lines ()
2809   "Count the number of lines and return numeric string."
2810   (save-excursion
2811     (save-restriction
2812       (widen)
2813       (goto-char (point-min))
2814       (re-search-forward
2815        (concat "^" (regexp-quote mail-header-separator) "$"))
2816       (forward-line 1)
2817       (int-to-string (count-lines (point) (point-max))))))
2818
2819 (defun message-make-in-reply-to ()
2820   "Return the In-Reply-To header for this message."
2821   (when message-reply-headers
2822     (let ((from (mail-header-from message-reply-headers))
2823           (date (mail-header-date message-reply-headers)))
2824       (when from
2825         (let ((stop-pos
2826                (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
2827           (concat (if (and stop-pos
2828                            (not (zerop stop-pos)))
2829                       (substring from 0 stop-pos) from)
2830                   "'s message of \""
2831                   (if (or (not date) (string= date ""))
2832                       "(unknown date)" date)
2833                   "\""))))))
2834
2835 (defun message-make-distribution ()
2836   "Make a Distribution header."
2837   (let ((orig-distribution (message-fetch-reply-field "distribution")))
2838     (cond ((message-functionp message-distribution-function)
2839            (funcall message-distribution-function))
2840           (t orig-distribution))))
2841
2842 (defun message-make-expires ()
2843   "Return an Expires header based on `message-expires'."
2844   (let ((current (current-time))
2845         (future (* 1.0 message-expires 60 60 24)))
2846     ;; Add the future to current.
2847     (setcar current (+ (car current) (round (/ future (expt 2 16)))))
2848     (setcar (cdr current) (+ (nth 1 current) (% (round future) (expt 2 16))))
2849     ;; Return the date in the future in UT.
2850     (timezone-make-date-arpa-standard
2851      (current-time-string current) (current-time-zone current) '(0 "UT"))))
2852
2853 (defun message-make-path ()
2854   "Return uucp path."
2855   (let ((login-name (user-login-name)))
2856     (cond ((null message-user-path)
2857            (concat (system-name) "!" login-name))
2858           ((stringp message-user-path)
2859            ;; Support GENERICPATH.  Suggested by vixie@decwrl.dec.com.
2860            (concat message-user-path "!" login-name))
2861           (t login-name))))
2862
2863 (defun message-make-from ()
2864   "Make a From header."
2865   (let* ((style message-from-style)
2866          (login (message-make-address))
2867          (fullname
2868           (or (and (boundp 'user-full-name)
2869                    user-full-name)
2870               (user-full-name))))
2871     (when (string= fullname "&")
2872       (setq fullname (user-login-name)))
2873     (save-excursion
2874       (message-set-work-buffer)
2875       (cond
2876        ((or (null style)
2877             (equal fullname ""))
2878         (insert login))
2879        ((or (eq style 'angles)
2880             (and (not (eq style 'parens))
2881                  ;; Use angles if no quoting is needed, or if parens would
2882                  ;; need quoting too.
2883                  (or (not (string-match "[^- !#-'*+/-9=?A-Z^-~]" fullname))
2884                      (let ((tmp (concat fullname nil)))
2885                        (while (string-match "([^()]*)" tmp)
2886                          (aset tmp (match-beginning 0) ?-)
2887                          (aset tmp (1- (match-end 0)) ?-))
2888                        (string-match "[\\()]" tmp)))))
2889         (insert fullname)
2890         (goto-char (point-min))
2891         ;; Look for a character that cannot appear unquoted
2892         ;; according to RFC 822.
2893         (when (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]" nil 1)
2894           ;; Quote fullname, escaping specials.
2895           (goto-char (point-min))
2896           (insert "\"")
2897           (while (re-search-forward "[\"\\]" nil 1)
2898             (replace-match "\\\\\\&" t))
2899           (insert "\""))
2900         (insert " <" login ">"))
2901        (t                               ; 'parens or default
2902         (insert login " (")
2903         (let ((fullname-start (point)))
2904           (insert fullname)
2905           (goto-char fullname-start)
2906           ;; RFC 822 says \ and nonmatching parentheses
2907           ;; must be escaped in comments.
2908           ;; Escape every instance of ()\ ...
2909           (while (re-search-forward "[()\\]" nil 1)
2910             (replace-match "\\\\\\&" t))
2911           ;; ... then undo escaping of matching parentheses,
2912           ;; including matching nested parentheses.
2913           (goto-char fullname-start)
2914           (while (re-search-forward
2915                   "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
2916                   nil 1)
2917             (replace-match "\\1(\\3)" t)
2918             (goto-char fullname-start)))
2919         (insert ")")))
2920       (buffer-string))))
2921
2922 (defun message-make-sender ()
2923   "Return the \"real\" user address.
2924 This function tries to ignore all user modifications, and
2925 give as trustworthy answer as possible."
2926   (concat (user-login-name) "@" (system-name)))
2927
2928 (defun message-make-address ()
2929   "Make the address of the user."
2930   (or (message-user-mail-address)
2931       (concat (user-login-name) "@" (message-make-domain))))
2932
2933 (defun message-user-mail-address ()
2934   "Return the pertinent part of `user-mail-address'."
2935   (when user-mail-address
2936     (if (string-match " " user-mail-address)
2937         (nth 1 (mail-extract-address-components user-mail-address))
2938       user-mail-address)))
2939
2940 (defun message-make-fqdn ()
2941   "Return user's fully qualified domain name."
2942   (let ((system-name (system-name))
2943         (user-mail (message-user-mail-address)))
2944     (cond
2945      ((string-match "[^.]\\.[^.]" system-name)
2946       ;; `system-name' returned the right result.
2947       system-name)
2948      ;; Try `mail-host-address'.
2949      ((and (boundp 'mail-host-address)
2950            (stringp mail-host-address)
2951            (string-match "\\." mail-host-address))
2952       mail-host-address)
2953      ;; We try `user-mail-address' as a backup.
2954      ((and user-mail
2955            (string-match "\\." user-mail)
2956            (string-match "@\\(.*\\)\\'" user-mail))
2957       (match-string 1 user-mail))
2958      ;; Default to this bogus thing.
2959      (t
2960       (concat system-name ".i-did-not-set--mail-host-address--so-shoot-me")))))
2961
2962 (defun message-make-host-name ()
2963   "Return the name of the host."
2964   (let ((fqdn (message-make-fqdn)))
2965     (string-match "^[^.]+\\." fqdn)
2966     (substring fqdn 0 (1- (match-end 0)))))
2967
2968 (defun message-make-domain ()
2969   "Return the domain name."
2970   (or mail-host-address
2971       (message-make-fqdn)))
2972
2973 (defun message-generate-headers (headers)
2974   "Prepare article HEADERS.
2975 Headers already prepared in the buffer are not modified."
2976   (save-restriction
2977     (message-narrow-to-headers)
2978     (let* ((Date (message-make-date))
2979            (Message-ID (message-make-message-id))
2980            (Organization (message-make-organization))
2981            (From (message-make-from))
2982            (Path (message-make-path))
2983            (Subject nil)
2984            (Newsgroups nil)
2985            (In-Reply-To (message-make-in-reply-to))
2986            (To nil)
2987            (Distribution (message-make-distribution))
2988            (Lines (message-make-lines))
2989            (X-Newsreader message-newsreader)
2990            (X-Mailer (and (not (message-fetch-field "X-Newsreader"))
2991                           message-mailer))
2992            (Expires (message-make-expires))
2993            (case-fold-search t)
2994            header value elem)
2995       ;; First we remove any old generated headers.
2996       (let ((headers message-deletable-headers))
2997         (unless (buffer-modified-p)
2998           (setq headers (delq 'Message-ID (copy-sequence headers))))
2999         (while headers
3000           (goto-char (point-min))
3001           (and (re-search-forward
3002                 (concat "^" (symbol-name (car headers)) ": *") nil t)
3003                (get-text-property (1+ (match-beginning 0)) 'message-deletable)
3004                (message-delete-line))
3005           (pop headers)))
3006       ;; Go through all the required headers and see if they are in the
3007       ;; articles already.  If they are not, or are empty, they are
3008       ;; inserted automatically - except for Subject, Newsgroups and
3009       ;; Distribution.
3010       (while headers
3011         (goto-char (point-min))
3012         (setq elem (pop headers))
3013         (if (consp elem)
3014             (if (eq (car elem) 'optional)
3015                 (setq header (cdr elem))
3016               (setq header (car elem)))
3017           (setq header elem))
3018         (when (or (not (re-search-forward
3019                         (concat "^" (downcase (symbol-name header)) ":")
3020                         nil t))
3021                   (progn
3022                     ;; The header was found.  We insert a space after the
3023                     ;; colon, if there is none.
3024                     (if (/= (following-char) ? ) (insert " ") (forward-char 1))
3025                     ;; Find out whether the header is empty...
3026                     (looking-at "[ \t]*$")))
3027           ;; So we find out what value we should insert.
3028           (setq value
3029                 (cond
3030                  ((and (consp elem) (eq (car elem) 'optional))
3031                   ;; This is an optional header.  If the cdr of this
3032                   ;; is something that is nil, then we do not insert
3033                   ;; this header.
3034                   (setq header (cdr elem))
3035                   (or (and (fboundp (cdr elem)) (funcall (cdr elem)))
3036                       (and (boundp (cdr elem)) (symbol-value (cdr elem)))))
3037                  ((consp elem)
3038                   ;; The element is a cons.  Either the cdr is a
3039                   ;; string to be inserted verbatim, or it is a
3040                   ;; function, and we insert the value returned from
3041                   ;; this function.
3042                   (or (and (stringp (cdr elem)) (cdr elem))
3043                       (and (fboundp (cdr elem)) (funcall (cdr elem)))))
3044                  ((and (boundp header) (symbol-value header))
3045                   ;; The element is a symbol.  We insert the value
3046                   ;; of this symbol, if any.
3047                   (symbol-value header))
3048                  (t
3049                   ;; We couldn't generate a value for this header,
3050                   ;; so we just ask the user.
3051                   (read-from-minibuffer
3052                    (format "Empty header for %s; enter value: " header)))))
3053           ;; Finally insert the header.
3054           (when (and value
3055                      (not (equal value "")))
3056             (save-excursion
3057               (if (bolp)
3058                   (progn
3059                     ;; This header didn't exist, so we insert it.
3060                     (goto-char (point-max))
3061                     (insert (symbol-name header) ": " value "\n")
3062                     (forward-line -1))
3063                 ;; The value of this header was empty, so we clear
3064                 ;; totally and insert the new value.
3065                 (delete-region (point) (gnus-point-at-eol))
3066                 (insert value))
3067               ;; Add the deletable property to the headers that require it.
3068               (and (memq header message-deletable-headers)
3069                    (progn (beginning-of-line) (looking-at "[^:]+: "))
3070                    (add-text-properties
3071                     (point) (match-end 0)
3072                     '(message-deletable t face italic) (current-buffer)))))))
3073       ;; Insert new Sender if the From is strange.
3074       (let ((from (message-fetch-field "from"))
3075             (sender (message-fetch-field "sender"))
3076             (secure-sender (message-make-sender)))
3077         (when (and from
3078                    (not (message-check-element 'sender))
3079                    (not (string=
3080                          (downcase
3081                           (cadr (mail-extract-address-components from)))
3082                          (downcase secure-sender)))
3083                    (or (null sender)
3084                        (not
3085                         (string=
3086                          (downcase
3087                           (cadr (mail-extract-address-components sender)))
3088                          (downcase secure-sender)))))
3089           (goto-char (point-min))
3090           ;; Rename any old Sender headers to Original-Sender.
3091           (when (re-search-forward "^\\(Original-\\)*Sender:" nil t)
3092             (beginning-of-line)
3093             (insert "Original-")
3094             (beginning-of-line))
3095           (when (or (message-news-p)
3096                     (string-match "^[^@]+@.+\\..+" secure-sender))
3097             (insert "Sender: " secure-sender "\n")))))))
3098
3099 (defun message-insert-courtesy-copy ()
3100   "Insert a courtesy message in mail copies of combined messages."
3101   (let (newsgroups)
3102     (save-excursion
3103       (save-restriction
3104         (message-narrow-to-headers)
3105         (when (setq newsgroups (message-fetch-field "newsgroups"))
3106           (goto-char (point-max))
3107           (insert "Posted-To: " newsgroups "\n")))
3108       (forward-line 1)
3109       (when message-courtesy-message
3110         (cond
3111          ((string-match "%s" message-courtesy-message)
3112           (insert (format message-courtesy-message newsgroups)))
3113          (t
3114           (insert message-courtesy-message)))))))
3115
3116 ;;;
3117 ;;; Setting up a message buffer
3118 ;;;
3119
3120 (defun message-fill-address (header value)
3121   (save-restriction
3122     (narrow-to-region (point) (point))
3123     (insert (capitalize (symbol-name header))
3124             ": "
3125             (if (consp value) (car value) value)
3126             "\n")
3127     (narrow-to-region (point-min) (1- (point-max)))
3128     (let (quoted last)
3129       (goto-char (point-min))
3130       (while (not (eobp))
3131         (skip-chars-forward "^,\"" (point-max))
3132         (if (or (= (following-char) ?,)
3133                 (eobp))
3134             (when (not quoted)
3135               (if (and (> (current-column) 78)
3136                        last)
3137                   (progn
3138                     (save-excursion
3139                       (goto-char last)
3140                       (insert "\n\t"))
3141                     (setq last (1+ (point))))
3142                 (setq last (1+ (point)))))
3143           (setq quoted (not quoted)))
3144         (unless (eobp)
3145           (forward-char 1))))
3146     (goto-char (point-max))
3147     (widen)
3148     (forward-line 1)))
3149
3150 (defun message-fill-references (header value)
3151   (insert (capitalize (symbol-name header))
3152           ": "
3153           (std11-fill-msg-id-list-string
3154            (if (consp value) (car value) value))
3155           "\n"))
3156
3157 (defun message-fill-header (header value)
3158   (let ((begin (point))
3159         (fill-column 990)
3160         (fill-prefix "\t"))
3161     (insert (capitalize (symbol-name header))
3162             ": "
3163             (if (consp value) (car value) value)
3164             "\n")
3165     (save-restriction
3166       (narrow-to-region begin (point))
3167       (fill-region-as-paragraph begin (point))
3168       ;; Tapdance around looong Message-IDs.
3169       (forward-line -1)
3170       (when (looking-at "[ \t]*$")
3171         (message-delete-line))
3172       (goto-char begin)
3173       (re-search-forward ":" nil t)
3174       (when (looking-at "\n[ \t]+")
3175         (replace-match " " t t))
3176       (goto-char (point-max)))))
3177
3178 (defun message-position-point ()
3179   "Move point to where the user probably wants to find it."
3180   (message-narrow-to-headers)
3181   (cond
3182    ((re-search-forward "^[^:]+:[ \t]*$" nil t)
3183     (search-backward ":" )
3184     (widen)
3185     (forward-char 1)
3186     (if (= (following-char) ? )
3187         (forward-char 1)
3188       (insert " ")))
3189    (t
3190     (goto-char (point-max))
3191     (widen)
3192     (forward-line 1)
3193     (unless (looking-at "$")
3194       (forward-line 2)))
3195    (sit-for 0)))
3196
3197 (defun message-buffer-name (type &optional to group)
3198   "Return a new (unique) buffer name based on TYPE and TO."
3199   (cond
3200    ;; Check whether `message-generate-new-buffers' is a function,
3201    ;; and if so, call it.
3202    ((message-functionp message-generate-new-buffers)
3203     (funcall message-generate-new-buffers type to group))
3204    ;; Generate a new buffer name The Message Way.
3205    (message-generate-new-buffers
3206     (generate-new-buffer-name
3207      (concat "*" type
3208              (if to
3209                  (concat " to "
3210                          (or (car (mail-extract-address-components to))
3211                              to) "")
3212                "")
3213              (if (and group (not (string= group ""))) (concat " on " group) "")
3214              "*")))
3215    ;; Use standard name.
3216    (t
3217     (format "*%s message*" type))))
3218
3219 (defun message-pop-to-buffer (name)
3220   "Pop to buffer NAME, and warn if it already exists and is modified."
3221   (let ((buffer (get-buffer name)))
3222     (if (and buffer
3223              (buffer-name buffer))
3224         (progn
3225           (set-buffer (pop-to-buffer buffer))
3226           (when (and (buffer-modified-p)
3227                      (not (y-or-n-p
3228                            "Message already being composed; erase? ")))
3229             (error "Message being composed")))
3230       (set-buffer (pop-to-buffer name))))
3231   (erase-buffer)
3232   (message-mode))
3233
3234 (defun message-do-send-housekeeping ()
3235   "Kill old message buffers."
3236   ;; We might have sent this buffer already.  Delete it from the
3237   ;; list of buffers.
3238   (setq message-buffer-list (delq (current-buffer) message-buffer-list))
3239   (while (and message-max-buffers
3240               message-buffer-list
3241               (>= (length message-buffer-list) message-max-buffers))
3242     ;; Kill the oldest buffer -- unless it has been changed.
3243     (let ((buffer (pop message-buffer-list)))
3244       (when (and (buffer-name buffer)
3245                  (not (buffer-modified-p buffer)))
3246         (kill-buffer buffer))))
3247   ;; Rename the buffer.
3248   (if message-send-rename-function
3249       (funcall message-send-rename-function)
3250     (when (string-match "\\`\\*" (buffer-name))
3251       (rename-buffer
3252        (concat "*sent " (substring (buffer-name) (match-end 0))) t)))
3253   ;; Push the current buffer onto the list.
3254   (when message-max-buffers
3255     (setq message-buffer-list
3256           (nconc message-buffer-list (list (current-buffer))))))
3257
3258 (defvar mc-modes-alist)
3259 (defun message-setup (headers &optional replybuffer actions)
3260   (when (and (boundp 'mc-modes-alist)
3261              (not (assq 'message-mode mc-modes-alist)))
3262     (push '(message-mode (encrypt . mc-encrypt-message)
3263                          (sign . mc-sign-message))
3264           mc-modes-alist))
3265   (when actions
3266     (setq message-send-actions actions))
3267   (setq message-reply-buffer replybuffer)
3268   (goto-char (point-min))
3269   ;; Insert all the headers.
3270   (mail-header-format
3271    (let ((h headers)
3272          (alist message-header-format-alist))
3273      (while h
3274        (unless (assq (caar h) message-header-format-alist)
3275          (push (list (caar h)) alist))
3276        (pop h))
3277      alist)
3278    headers)
3279   (delete-region (point) (progn (forward-line -1) (point)))
3280   (when message-default-headers
3281     (insert message-default-headers)
3282     (or (bolp) (insert ?\n)))
3283   (put-text-property
3284    (point)
3285    (progn
3286      (insert mail-header-separator "\n")
3287      (1- (point)))
3288    'read-only nil)
3289   (forward-line -1)
3290   (when (message-news-p)
3291     (when message-default-news-headers
3292       (insert message-default-news-headers)
3293       (or (bolp) (insert ?\n)))
3294     (when message-generate-headers-first
3295       (message-generate-headers
3296        (delq 'Lines
3297              (delq 'Subject
3298                    (copy-sequence message-required-news-headers))))))
3299   (when (message-mail-p)
3300     (when message-default-mail-headers
3301       (insert message-default-mail-headers)
3302       (or (bolp) (insert ?\n)))
3303     (when message-generate-headers-first
3304       (message-generate-headers
3305        (delq 'Lines
3306              (delq 'Subject
3307                    (copy-sequence message-required-mail-headers))))))
3308   (run-hooks 'message-signature-setup-hook)
3309   (message-insert-signature)
3310   (save-restriction
3311     (message-narrow-to-headers)
3312     (run-hooks 'message-header-setup-hook))
3313   (set-buffer-modified-p nil)
3314   (setq buffer-undo-list nil)
3315   (run-hooks 'message-setup-hook)
3316   (message-position-point)
3317   (undo-boundary))
3318
3319 (defun message-set-auto-save-file-name ()
3320   "Associate the message buffer with a file in the drafts directory."
3321   (when message-autosave-directory
3322     (if (gnus-alive-p)
3323         (setq message-draft-article
3324               (nndraft-request-associate-buffer "drafts"))
3325       (setq buffer-file-name (expand-file-name "*message*"
3326                                                message-autosave-directory))
3327       (setq buffer-auto-save-file-name (make-auto-save-file-name)))
3328     (clear-visited-file-modtime)))
3329
3330 (defun message-disassociate-draft ()
3331   "Disassociate the message buffer from the drafts directory."
3332   (when message-draft-article
3333     (nndraft-request-expire-articles
3334      (list message-draft-article) "drafts" nil t)))
3335
3336 \f
3337
3338 ;;;
3339 ;;; Commands for interfacing with message
3340 ;;;
3341
3342 ;;;###autoload
3343 (defun message-mail (&optional to subject
3344                                other-headers continue switch-function
3345                                yank-action send-actions)
3346   "Start editing a mail message to be sent."
3347   (interactive)
3348   (let ((message-this-is-mail t))
3349     (message-pop-to-buffer (message-buffer-name "mail" to))
3350     (message-setup
3351      (nconc
3352       `((To . ,(or to "")) (Subject . ,(or subject "")))
3353       (when other-headers other-headers)))))
3354
3355 ;;;###autoload
3356 (defun message-news (&optional newsgroups subject)
3357   "Start editing a news article to be sent."
3358   (interactive)
3359   (let ((message-this-is-news t))
3360     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups))
3361     (message-setup `((Newsgroups . ,(or newsgroups ""))
3362                      (Subject . ,(or subject ""))))))
3363
3364 ;;;###autoload
3365 (defun message-reply (&optional to-address wide ignore-reply-to)
3366   "Start editing a reply to the article in the current buffer."
3367   (interactive)
3368   (let ((cur (current-buffer))
3369         from subject date reply-to to cc
3370         references message-id follow-to
3371         (inhibit-point-motion-hooks t)
3372         mct never-mct gnus-warning)
3373     (save-restriction
3374       (message-narrow-to-head)
3375       ;; Allow customizations to have their say.
3376       (if (not wide)
3377           ;; This is a regular reply.
3378           (if (message-functionp message-reply-to-function)
3379               (setq follow-to (funcall message-reply-to-function)))
3380         ;; This is a followup.
3381         (if (message-functionp message-wide-reply-to-function)
3382             (save-excursion
3383               (setq follow-to
3384                     (funcall message-wide-reply-to-function)))))
3385       ;; Find all relevant headers we need.
3386       (setq from (message-fetch-field "from")
3387             date (message-fetch-field "date")
3388             subject (or (message-fetch-field "subject") "none")
3389             to (message-fetch-field "to")
3390             cc (message-fetch-field "cc")
3391             mct (message-fetch-field "mail-copies-to")
3392             reply-to (unless ignore-reply-to (message-fetch-field "reply-to"))
3393             references (message-fetch-field "references")
3394             message-id (message-fetch-field "message-id" t))
3395       ;; Remove any (buggy) Re:'s that are present and make a
3396       ;; proper one.
3397       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3398         (setq subject (substring subject (match-end 0))))
3399       (setq subject (concat "Re: " subject))
3400
3401       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3402                  (string-match "<[^>]+>" gnus-warning))
3403         (setq message-id (match-string 0 gnus-warning)))
3404
3405       ;; Handle special values of Mail-Copies-To.
3406       (when mct
3407         (cond ((equal (downcase mct) "never")
3408                (setq never-mct t)
3409                (setq mct nil))
3410               ((equal (downcase mct) "always")
3411                (setq mct (or reply-to from)))))
3412
3413       (unless follow-to
3414         (if (or (not wide)
3415                 to-address)
3416             (progn
3417               (setq follow-to (list (cons 'To (or to-address reply-to from))))
3418               (when (and wide mct)
3419                 (push (cons 'Cc mct) follow-to)))
3420           (let (ccalist)
3421             (save-excursion
3422               (message-set-work-buffer)
3423               (unless never-mct
3424                 (insert (or reply-to from "")))
3425               (insert (if to (concat (if (bolp) "" ", ") to "") ""))
3426               (insert (if mct (concat (if (bolp) "" ", ") mct) ""))
3427               (insert (if cc (concat (if (bolp) "" ", ") cc) ""))
3428               (goto-char (point-min))
3429               (while (re-search-forward "[ \t]+" nil t)
3430                 (replace-match " " t t))
3431               ;; Remove addresses that match `rmail-dont-reply-to-names'.
3432               (insert (prog1 (rmail-dont-reply-to (buffer-string))
3433                         (erase-buffer)))
3434               (goto-char (point-min))
3435               ;; Perhaps Mail-Copies-To: never removed the only address?
3436               (when (eobp)
3437                 (insert (or reply-to from "")))
3438               (setq ccalist
3439                     (mapcar
3440                      (lambda (addr)
3441                        (cons (mail-strip-quoted-names addr) addr))
3442                      (message-tokenize-header (buffer-string))))
3443               (let ((s ccalist))
3444                 (while s
3445                   (setq ccalist (delq (assoc (car (pop s)) s) ccalist)))))
3446             (setq follow-to (list (cons 'To (cdr (pop ccalist)))))
3447             (when ccalist
3448               (let ((ccs (cons 'Cc (mapconcat
3449                                     (lambda (addr) (cdr addr)) ccalist ", "))))
3450                 (when (string-match "^ +" (cdr ccs))
3451                   (setcdr ccs (substring (cdr ccs) (match-end 0))))
3452                 (push ccs follow-to))))))
3453       (widen))
3454
3455     (message-pop-to-buffer (message-buffer-name
3456                             (if wide "wide reply" "reply") from
3457                             (if wide to-address nil)))
3458
3459     (setq message-reply-headers
3460           (vector 0 subject from date message-id references 0 0 ""))
3461
3462     (message-setup
3463      `((Subject . ,subject)
3464        ,@follow-to
3465        ,@(if (or references message-id)
3466              `((References . ,(concat (or references "") (and references " ")
3467                                       (or message-id ""))))
3468            nil))
3469      cur)))
3470
3471 ;;;###autoload
3472 (defun message-wide-reply (&optional to-address ignore-reply-to)
3473   "Make a \"wide\" reply to the message in the current buffer."
3474   (interactive)
3475   (message-reply to-address t ignore-reply-to))
3476
3477 ;;;###autoload
3478 (defun message-followup (&optional to-newsgroups)
3479   "Follow up to the message in the current buffer.
3480 If TO-NEWSGROUPS, use that as the new Newsgroups line."
3481   (interactive)
3482   (let ((cur (current-buffer))
3483         from subject date reply-to mct
3484         references message-id follow-to
3485         (inhibit-point-motion-hooks t)
3486         (message-this-is-news t)
3487         followup-to distribution newsgroups gnus-warning posted-to)
3488     (save-restriction
3489       (narrow-to-region
3490        (goto-char (point-min))
3491        (if (search-forward "\n\n" nil t)
3492            (1- (point))
3493          (point-max)))
3494       (when (message-functionp message-followup-to-function)
3495         (setq follow-to
3496               (funcall message-followup-to-function)))
3497       (setq from (message-fetch-field "from")
3498             date (message-fetch-field "date")
3499             subject (or (message-fetch-field "subject") "none")
3500             references (message-fetch-field "references")
3501             message-id (message-fetch-field "message-id" t)
3502             followup-to (message-fetch-field "followup-to")
3503             newsgroups (message-fetch-field "newsgroups")
3504             posted-to (message-fetch-field "posted-to")
3505             reply-to (message-fetch-field "reply-to")
3506             distribution (message-fetch-field "distribution")
3507             mct (message-fetch-field "mail-copies-to"))
3508       (when (and (setq gnus-warning (message-fetch-field "gnus-warning"))
3509                  (string-match "<[^>]+>" gnus-warning))
3510         (setq message-id (match-string 0 gnus-warning)))
3511       ;; Remove bogus distribution.
3512       (when (and (stringp distribution)
3513                  (let ((case-fold-search t))
3514                    (string-match "world" distribution)))
3515         (setq distribution nil))
3516       ;; Remove any (buggy) Re:'s that are present and make a
3517       ;; proper one.
3518       (when (string-match "^[ \t]*[Rr][Ee]:[ \t]*" subject)
3519         (setq subject (substring subject (match-end 0))))
3520       (setq subject (concat "Re: " subject))
3521       (widen))
3522
3523     (message-pop-to-buffer (message-buffer-name "followup" from newsgroups))
3524
3525     (message-setup
3526      `((Subject . ,subject)
3527        ,@(cond
3528           (to-newsgroups
3529            (list (cons 'Newsgroups to-newsgroups)))
3530           (follow-to follow-to)
3531           ((and followup-to message-use-followup-to)
3532            (list
3533             (cond
3534              ((equal (downcase followup-to) "poster")
3535               (if (or (eq message-use-followup-to 'use)
3536                       (message-y-or-n-p "Obey Followup-To: poster? " t "\
3537 You should normally obey the Followup-To: header.
3538
3539 `Followup-To: poster' sends your response via e-mail instead of news.
3540
3541 A typical situation where `Followup-To: poster' is used is when the poster
3542 does not read the newsgroup, so he wouldn't see any replies sent to it."))
3543                   (progn
3544                     (setq message-this-is-news nil)
3545                     (cons 'To (or reply-to from "")))
3546                 (cons 'Newsgroups newsgroups)))
3547              (t
3548               (if (or (equal followup-to newsgroups)
3549                       (not (eq message-use-followup-to 'ask))
3550                       (message-y-or-n-p
3551                        (concat "Obey Followup-To: " followup-to "? ") t "\
3552 You should normally obey the Followup-To: header.
3553
3554         `Followup-To: " followup-to "'
3555 directs your response to " (if (string-match "," followup-to)
3556                                "the specified newsgroups"
3557                              "that newsgroup only") ".
3558
3559 If a message is posted to several newsgroups, Followup-To is often
3560 used to direct the following discussion to one newsgroup only,
3561 because discussions that are spread over several newsgroup tend to
3562 be fragmented and very difficult to follow.
3563
3564 Also, some source/announcement newsgroups are not indented for discussion;
3565 responses here are directed to other newsgroups."))
3566                   (cons 'Newsgroups followup-to)
3567                 (cons 'Newsgroups newsgroups))))))
3568           (posted-to
3569            `((Newsgroups . ,posted-to)))
3570           (t
3571            `((Newsgroups . ,newsgroups))))
3572        ,@(and distribution (list (cons 'Distribution distribution)))
3573        ,@(if (or references message-id)
3574              `((References . ,(concat (or references "") (and references " ")
3575                                       (or message-id "")))))
3576        ,@(when (and mct
3577                     (not (equal (downcase mct) "never")))
3578            (list (cons 'Cc (if (equal (downcase mct) "always")
3579                                (or reply-to from "")
3580                              mct)))))
3581
3582      cur)
3583
3584     (setq message-reply-headers
3585           (vector 0 subject from date message-id references 0 0 ""))))
3586
3587
3588 ;;;###autoload
3589 (defun message-cancel-news ()
3590   "Cancel an article you posted."
3591   (interactive)
3592   (unless (message-news-p)
3593     (error "This is not a news article; canceling is impossible"))
3594   (when (yes-or-no-p "Do you really want to cancel this article? ")
3595     (let (from newsgroups message-id distribution buf sender)
3596       (save-excursion
3597         ;; Get header info. from original article.
3598         (save-restriction
3599           (message-narrow-to-head)
3600           (setq from (message-fetch-field "from")
3601                 sender (message-fetch-field "sender")
3602                 newsgroups (message-fetch-field "newsgroups")
3603                 message-id (message-fetch-field "message-id" t)
3604                 distribution (message-fetch-field "distribution")))
3605         ;; Make sure that this article was written by the user.
3606         (unless (string-equal
3607                  (downcase
3608                   (or sender (cadr (std11-extract-address-components from))))
3609                  (downcase (message-make-address)))
3610           (error "This article is not yours"))
3611         ;; Make control message.
3612         (setq buf (set-buffer (get-buffer-create " *message cancel*")))
3613         (buffer-disable-undo (current-buffer))
3614         (erase-buffer)
3615         (insert "Newsgroups: " newsgroups "\n"
3616                 "From: " (message-make-from) "\n"
3617                 "Subject: cmsg cancel " message-id "\n"
3618                 "Control: cancel " message-id "\n"
3619                 (if distribution
3620                     (concat "Distribution: " distribution "\n")
3621                   "")
3622                 mail-header-separator "\n"
3623                 message-cancel-message)
3624         (message "Canceling your article...")
3625         (if (let ((message-syntax-checks
3626                    'dont-check-for-anything-just-trust-me)
3627                   (message-encoding-buffer (current-buffer))
3628                   (message-edit-buffer (current-buffer)))
3629               (message-send-news))
3630             (message "Canceling your article...done"))
3631         (kill-buffer buf)))))
3632
3633 ;;;###autoload
3634 (defun message-supersede ()
3635   "Start composing a message to supersede the current message.
3636 This is done simply by taking the old article and adding a Supersedes
3637 header line with the old Message-ID."
3638   (interactive)
3639   (let ((cur (current-buffer)))
3640     ;; Check whether the user owns the article that is to be superseded.
3641     (unless (string-equal
3642              (downcase (or (message-fetch-field "sender")
3643                            (cadr (mail-extract-address-components
3644                                   (message-fetch-field "from")))))
3645              (downcase (message-make-sender)))
3646       (error "This article is not yours"))
3647     ;; Get a normal message buffer.
3648     (message-pop-to-buffer (message-buffer-name "supersede"))
3649     (insert-buffer-substring cur)
3650     (message-narrow-to-head)
3651     ;; Remove unwanted headers.
3652     (when message-ignored-supersedes-headers
3653       (message-remove-header message-ignored-supersedes-headers t))
3654     (goto-char (point-min))
3655     (if (not (re-search-forward "^Message-ID: " nil t))
3656         (error "No Message-ID in this article")
3657       (replace-match "Supersedes: " t t))
3658     (goto-char (point-max))
3659     (insert mail-header-separator)
3660     (widen)
3661     (forward-line 1)))
3662
3663 ;;;###autoload
3664 (defun message-recover ()
3665   "Reread contents of current buffer from its last auto-save file."
3666   (interactive)
3667   (let ((file-name (make-auto-save-file-name)))
3668     (cond ((save-window-excursion
3669              (if (not (eq system-type 'vax-vms))
3670                  (with-output-to-temp-buffer "*Directory*"
3671                    (buffer-disable-undo standard-output)
3672                    (let ((default-directory "/"))
3673                      (call-process
3674                       "ls" nil standard-output nil "-l" file-name))))
3675              (yes-or-no-p (format "Recover auto save file %s? " file-name)))
3676            (let ((buffer-read-only nil))
3677              (erase-buffer)
3678              (insert-file-contents file-name nil)))
3679           (t (error "message-recover cancelled")))))
3680
3681 ;;; Forwarding messages.
3682
3683 (defun message-make-forward-subject ()
3684   "Return a Subject header suitable for the message in the current buffer."
3685   (save-excursion
3686     (save-restriction
3687       (current-buffer)
3688       (message-narrow-to-head)
3689       (concat "[" (or (message-fetch-field
3690                        (if (message-news-p) "newsgroups" "from"))
3691                       "(nowhere)")
3692               "] " (or (eword-decode-unstructured-field-body
3693                         (message-fetch-field "Subject") ""))))))
3694
3695 ;;;###autoload
3696 (defun message-forward (&optional news)
3697   "Forward the current message via mail.
3698 Optional NEWS will use news to forward instead of mail."
3699   (interactive "P")
3700   (let ((cur (current-buffer))
3701         (subject (message-make-forward-subject))
3702         art-beg)
3703     (if news (message-news nil subject) (message-mail nil subject))
3704     ;; Put point where we want it before inserting the forwarded
3705     ;; message.
3706     (if message-signature-before-forwarded-message
3707         (goto-char (point-max))
3708       (message-goto-body))
3709     ;; Make sure we're at the start of the line.
3710     (unless (eolp)
3711       (insert "\n"))
3712     ;; Narrow to the area we are to insert.
3713     (narrow-to-region (point) (point))
3714     ;; Insert the separators and the forwarded buffer.
3715     (insert message-forward-start-separator)
3716     (setq art-beg (point))
3717     (insert-buffer-substring cur)
3718     (goto-char (point-max))
3719     (insert message-forward-end-separator)
3720     (set-text-properties (point-min) (point-max) nil)
3721     ;; Remove all unwanted headers.
3722     (goto-char art-beg)
3723     (narrow-to-region (point) (if (search-forward "\n\n" nil t)
3724                                   (1- (point))
3725                                 (point)))
3726     (goto-char (point-min))
3727     (message-remove-header message-included-forward-headers t nil t)
3728     (widen)
3729     (message-position-point)))
3730
3731 ;;;###autoload
3732 (defun message-resend (address)
3733   "Resend the current article to ADDRESS."
3734   (interactive "sResend message to: ")
3735   (message "Resending message to %s..." address)
3736   (save-excursion
3737     (let ((cur (current-buffer))
3738           beg)
3739       ;; We first set up a normal mail buffer.
3740       (set-buffer (get-buffer-create " *message resend*"))
3741       (buffer-disable-undo (current-buffer))
3742       (erase-buffer)
3743       ;; avoid to turn-on-mime-edit
3744       (let (message-setup-hook)
3745         (message-setup `((To . ,address)))
3746         )
3747       ;; Insert our usual headers.
3748       (message-generate-headers '(From Date To))
3749       (message-narrow-to-headers)
3750       ;; Rename them all to "Resent-*".
3751       (while (re-search-forward "^[A-Za-z]" nil t)
3752         (forward-char -1)
3753         (insert "Resent-"))
3754       (widen)
3755       (forward-line)
3756       (delete-region (point) (point-max))
3757       (setq beg (point))
3758       ;; Insert the message to be resent.
3759       (insert-buffer-substring cur)
3760       (goto-char (point-min))
3761       (search-forward "\n\n")
3762       (forward-char -1)
3763       (save-restriction
3764         (narrow-to-region beg (point))
3765         (message-remove-header message-ignored-resent-headers t)
3766         (goto-char (point-max)))
3767       (insert mail-header-separator)
3768       ;; Rename all old ("Also-")Resent headers.
3769       (while (re-search-backward "^\\(Also-\\)*Resent-" beg t)
3770         (beginning-of-line)
3771         (insert "Also-"))
3772       ;; Quote any "From " lines at the beginning.
3773       (goto-char beg)
3774       (when (looking-at "From ")
3775         (replace-match "X-From-Line: "))
3776       ;; Send it.
3777       (let ((message-encoding-buffer (current-buffer))
3778             (message-edit-buffer (current-buffer)))
3779         (message-send-mail))
3780       (kill-buffer (current-buffer)))
3781     (message "Resending message to %s...done" address)))
3782
3783 ;;;###autoload
3784 (defun message-bounce ()
3785   "Re-mail the current message.
3786 This only makes sense if the current message is a bounce message than
3787 contains some mail you have written which has been bounced back to
3788 you."
3789   (interactive)
3790   (let ((cur (current-buffer))
3791         boundary)
3792     (message-pop-to-buffer (message-buffer-name "bounce"))
3793     (insert-buffer-substring cur)
3794     (undo-boundary)
3795     (message-narrow-to-head)
3796     (if (and (message-fetch-field "Mime-Version")
3797              (setq boundary (message-fetch-field "Content-Type")))
3798         (if (string-match "boundary=\"\\([^\"]+\\)\"" boundary)
3799             (setq boundary (concat (match-string 1 boundary) " *\n"
3800                                    "Content-Type: message/rfc822"))
3801           (setq boundary nil)))
3802     (widen)
3803     (goto-char (point-min))
3804     (search-forward "\n\n" nil t)
3805     (or (and boundary
3806              (re-search-forward boundary nil t)
3807              (forward-line 2))
3808         (and (re-search-forward message-unsent-separator nil t)
3809              (forward-line 1))
3810         (re-search-forward "^Return-Path:.*\n" nil t))
3811     ;; We remove everything before the bounced mail.
3812     (delete-region
3813      (point-min)
3814      (if (re-search-forward "^[^ \n\t]+:" nil t)
3815          (match-beginning 0)
3816        (point)))
3817     (save-restriction
3818       (message-narrow-to-head)
3819       (message-remove-header message-ignored-bounced-headers t)
3820       (goto-char (point-max))
3821       (insert mail-header-separator))
3822     (message-position-point)))
3823
3824 ;;;
3825 ;;; Interactive entry points for new message buffers.
3826 ;;;
3827
3828 ;;;###autoload
3829 (defun message-mail-other-window (&optional to subject)
3830   "Like `message-mail' command, but display mail buffer in another window."
3831   (interactive)
3832   (let ((pop-up-windows t)
3833         (special-display-buffer-names nil)
3834         (special-display-regexps nil)
3835         (same-window-buffer-names nil)
3836         (same-window-regexps nil))
3837     (message-pop-to-buffer (message-buffer-name "mail" to)))
3838   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3839
3840 ;;;###autoload
3841 (defun message-mail-other-frame (&optional to subject)
3842   "Like `message-mail' command, but display mail buffer in another frame."
3843   (interactive)
3844   (let ((pop-up-frames t)
3845         (special-display-buffer-names nil)
3846         (special-display-regexps nil)
3847         (same-window-buffer-names nil)
3848         (same-window-regexps nil))
3849     (message-pop-to-buffer (message-buffer-name "mail" to)))
3850   (message-setup `((To . ,(or to "")) (Subject . ,(or subject "")))))
3851
3852 ;;;###autoload
3853 (defun message-news-other-window (&optional newsgroups subject)
3854   "Start editing a news article to be sent."
3855   (interactive)
3856   (let ((pop-up-windows t)
3857         (special-display-buffer-names nil)
3858         (special-display-regexps nil)
3859         (same-window-buffer-names nil)
3860         (same-window-regexps nil))
3861     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3862   (message-setup `((Newsgroups . ,(or newsgroups ""))
3863                    (Subject . ,(or subject "")))))
3864
3865 ;;;###autoload
3866 (defun message-news-other-frame (&optional newsgroups subject)
3867   "Start editing a news article to be sent."
3868   (interactive)
3869   (let ((pop-up-frames t)
3870         (special-display-buffer-names nil)
3871         (special-display-regexps nil)
3872         (same-window-buffer-names nil)
3873         (same-window-regexps nil))
3874     (message-pop-to-buffer (message-buffer-name "news" nil newsgroups)))
3875   (message-setup `((Newsgroups . ,(or newsgroups ""))
3876                    (Subject . ,(or subject "")))))
3877
3878 ;;; underline.el
3879
3880 ;; This code should be moved to underline.el (from which it is stolen).
3881
3882 ;;;###autoload
3883 (defun bold-region (start end)
3884   "Bold all nonblank characters in the region.
3885 Works by overstriking characters.
3886 Called from program, takes two arguments START and END
3887 which specify the range to operate on."
3888   (interactive "r")
3889   (save-excursion
3890     (let ((end1 (make-marker)))
3891       (move-marker end1 (max start end))
3892       (goto-char (min start end))
3893       (while (< (point) end1)
3894         (or (looking-at "[_\^@- ]")
3895             (insert (following-char) "\b"))
3896         (forward-char 1)))))
3897
3898 ;;;###autoload
3899 (defun unbold-region (start end)
3900   "Remove all boldness (overstruck characters) in the region.
3901 Called from program, takes two arguments START and END
3902 which specify the range to operate on."
3903   (interactive "r")
3904   (save-excursion
3905     (let ((end1 (make-marker)))
3906       (move-marker end1 (max start end))
3907       (goto-char (min start end))
3908       (while (re-search-forward "\b" end1 t)
3909         (if (eq (following-char) (char-after (- (point) 2)))
3910             (delete-char -2))))))
3911
3912 (defalias 'message-exchange-point-and-mark 'exchange-point-and-mark)
3913
3914 ;; Support for toolbar
3915 (when (string-match "XEmacs\\|Lucid" emacs-version)
3916   (require 'messagexmas))
3917
3918 ;;; Group name completion.
3919
3920 (defvar message-newgroups-header-regexp
3921   "^\\(Newsgroups\\|Followup-To\\|Posted-To\\|Gcc\\):"
3922   "Regexp that match headers that lists groups.")
3923
3924 (defun message-tab ()
3925   "Expand group names in Newsgroups and Followup-To headers.
3926 Do a `tab-to-tab-stop' if not in those headers."
3927   (interactive)
3928   (if (let ((mail-abbrev-mode-regexp message-newgroups-header-regexp))
3929         (mail-abbrev-in-expansion-header-p))
3930       (message-expand-group)
3931     (tab-to-tab-stop)))
3932
3933 (defvar gnus-active-hashtb)
3934 (defun message-expand-group ()
3935   "Expand the group name under point."
3936   (let* ((b (save-excursion
3937               (save-restriction
3938                 (narrow-to-region
3939                  (save-excursion
3940                    (beginning-of-line)
3941                    (skip-chars-forward "^:")
3942                    (1+ (point)))
3943                  (point))
3944                 (skip-chars-backward "^, \t\n") (point))))
3945          (completion-ignore-case t)
3946          (string (buffer-substring b (progn (skip-chars-forward "^,\t\n ")
3947                                             (point))))
3948          (hashtb (and (boundp 'gnus-active-hashtb) gnus-active-hashtb))
3949          (completions (all-completions string hashtb))
3950          (cur (current-buffer))
3951          comp)
3952     (delete-region b (point))
3953     (cond
3954      ((= (length completions) 1)
3955       (if (string= (car completions) string)
3956           (progn
3957             (insert string)
3958             (message "Only matching group"))
3959         (insert (car completions))))
3960      ((and (setq comp (try-completion string hashtb))
3961            (not (string= comp string)))
3962       (insert comp))
3963      (t
3964       (insert string)
3965       (if (not comp)
3966           (message "No matching groups")
3967         (save-selected-window
3968           (pop-to-buffer "*Completions*")
3969           (buffer-disable-undo (current-buffer))
3970           (let ((buffer-read-only nil))
3971             (erase-buffer)
3972             (let ((standard-output (current-buffer)))
3973               (display-completion-list (sort completions 'string<)))
3974             (goto-char (point-min))
3975             (delete-region (point) (progn (forward-line 3) (point))))))))))
3976
3977 ;;; Help stuff.
3978
3979 (defun message-talkative-question (ask question show &rest text)
3980   "Call FUNCTION with argument QUESTION; optionally display TEXT... args.
3981 If SHOW is non-nil, the arguments TEXT... are displayed in a temp buffer.
3982 The following arguments may contain lists of values."
3983   (if (and show
3984            (setq text (message-flatten-list text)))
3985       (save-window-excursion
3986         (save-excursion
3987           (with-output-to-temp-buffer " *MESSAGE information message*"
3988             (set-buffer " *MESSAGE information message*")
3989             (mapcar 'princ text)
3990             (goto-char (point-min))))
3991         (funcall ask question))
3992     (funcall ask question)))
3993
3994 (defun message-flatten-list (list)
3995   "Return a new, flat list that contains all elements of LIST.
3996
3997 \(message-flatten-list '(1 (2 3 (4 5 (6))) 7))
3998 => (1 2 3 4 5 6 7)"
3999   (cond ((consp list)
4000          (apply 'append (mapcar 'message-flatten-list list)))
4001         (list
4002          (list list))))
4003
4004 (defun message-generate-new-buffer-clone-locals (name &optional varstr)
4005   "Create and return a buffer with a name based on NAME using generate-new-buffer.
4006 Then clone the local variables and values from the old buffer to the
4007 new one, cloning only the locals having a substring matching the
4008 regexp varstr."
4009   (let ((oldbuf (current-buffer)))
4010     (save-excursion
4011       (set-buffer (generate-new-buffer name))
4012       (message-clone-locals oldbuf)
4013       (current-buffer))))
4014
4015 (defun message-clone-locals (buffer)
4016   "Clone the local variables from BUFFER to the current buffer."
4017   (let ((locals (save-excursion
4018                   (set-buffer buffer)
4019                   (buffer-local-variables)))
4020         (regexp "^gnus\\|^nn\\|^message"))
4021     (mapcar
4022      (lambda (local)
4023        (when (and (consp local)
4024                   (car local)
4025                   (string-match regexp (symbol-name (car local))))
4026          (ignore-errors
4027            (set (make-local-variable (car local))
4028                 (cdr local)))))
4029      locals)))
4030
4031
4032 ;;; @ for MIME Edit mode
4033 ;;;
4034
4035 (defun message-maybe-setup-default-charset ()
4036   (let ((charset
4037          (and (boundp 'gnus-summary-buffer)
4038               (buffer-live-p gnus-summary-buffer)
4039               (save-excursion
4040                 (set-buffer gnus-summary-buffer)
4041                 default-mime-charset))))
4042     (if charset
4043         (progn
4044           (make-local-variable 'default-mime-charset)
4045           (setq default-mime-charset charset)
4046           ))))
4047
4048 (defun message-maybe-encode ()
4049   (when message-mime-mode
4050     (run-hooks 'mime-edit-translate-hook)
4051     (if (catch 'mime-edit-error
4052           (save-excursion
4053             (mime-edit-translate-body)
4054             ))
4055         (error "Translation error!")
4056       )
4057     (end-of-invisible)
4058     (run-hooks 'mime-edit-exit-hook)
4059     ))
4060
4061 (defun message-mime-insert-article (&optional message)
4062   (interactive)
4063   (let ((message-cite-function 'mime-edit-inserted-message-filter)
4064         (message-reply-buffer gnus-original-article-buffer)
4065         )
4066     (message-yank-original nil)
4067     ))
4068
4069 (set-alist 'mime-edit-message-inserter-alist
4070            'message-mode (function message-mime-insert-article))
4071
4072 ;;; Miscellaneous functions
4073
4074 ;; stolen (and renamed) from nnheader.el
4075 (defun message-replace-chars-in-string (string from to)
4076   "Replace characters in STRING from FROM to TO."
4077   (let ((string (substring string 0))   ;Copy string.
4078         (len (length string))
4079         (idx 0))
4080     ;; Replace all occurrences of FROM with TO.
4081     (while (< idx len)
4082       (when (= (aref string idx) from)
4083         (aset string idx to))
4084       (setq idx (1+ idx)))
4085     string))
4086
4087 (run-hooks 'message-load-hook)
4088
4089 (provide 'message)
4090
4091 ;;; message.el ends here