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