1;;; cmuscheme.el --- Scheme process in a buffer. Adapted from tea.el
2
3;; Copyright (C) 1988, 1994, 1997, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6;; Author: Olin Shivers <olin.shivers@cs.cmu.edu>
7;; Maintainer: FSF
8;; Keywords: processes, lisp
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING.  If not, write to the
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
26
27;;; Commentary:
28
29;;    This is a customization of comint-mode (see comint.el)
30;;
31;; Written by Olin Shivers (olin.shivers@cs.cmu.edu). With bits and pieces
32;; lifted from scheme.el, shell.el, clisp.el, newclisp.el, cobol.el, et al..
33;; 8/88
34;;
35;; Please send me bug reports, bug fixes, and extensions, so that I can
36;; merge them into the master source.
37;;
38;; The changelog is at the end of this file.
39;;
40;; NOTE: MIT Cscheme, when invoked with the -emacs flag, has a special user
41;; interface that communicates process state back to the superior emacs by
42;; outputting special control sequences. The gnumacs package, xscheme.el, has
43;; lots and lots of special purpose code to read these control sequences, and
44;; so is very tightly integrated with the cscheme process. The cscheme
45;; interrupt handler and debugger read single character commands in cbreak
46;; mode; when this happens, xscheme.el switches to special keymaps that bind
47;; the single letter command keys to emacs functions that directly send the
48;; character to the scheme process.  Cmuscheme mode does *not* provide this
49;; functionality. If you are a cscheme user, you may prefer to use the
50;; xscheme.el/cscheme -emacs interaction.
51;;
52;; Here's a summary of the pros and cons, as I see them.
53;; xscheme: Tightly integrated with inferior cscheme process!  A few commands
54;;	     not in cmuscheme. But. Integration is a bit of a hack.  Input
55;;	     history only keeps the immediately prior input. Bizarre
56;;	     keybindings.
57;;
58;; cmuscheme: Not tightly integrated with inferior cscheme process.  But.
59;;            Carefully integrated functionality with the entire suite of
60;;            comint-derived CMU process modes. Keybindings reminiscent of
61;;            Zwei and Hemlock. Good input history. A few commands not in
62;;            xscheme.
63;;
64;; It's a tradeoff. Pay your money; take your choice. If you use a Scheme
65;; that isn't Cscheme, of course, there isn't a choice. Xscheme.el is *very*
66;; Cscheme-specific; you must use cmuscheme.el.  Interested parties are
67;; invited to port xscheme functionality on top of comint mode...
68
69;;; CHANGE LOG
70;;; ===========================================================================
71;;; 8/88 Olin
72;;; Created.
73;;;
74;;; 2/15/89 Olin
75;;; Removed -emacs flag from process invocation. It's only useful for
76;;; cscheme, and makes cscheme assume it's running under xscheme.el,
77;;; which messes things up royally. A bug.
78;;;
79;;; 5/22/90 Olin
80;;; - Upgraded to use comint-send-string and comint-send-region.
81;;; - run-scheme now offers to let you edit the command line if
82;;;   you invoke it with a prefix-arg. M-x scheme is redundant, and
83;;;   has been removed.
84;;; - Explicit references to process "scheme" have been replaced with
85;;;   (scheme-proc). This allows better handling of multiple process bufs.
86;;; - Added scheme-send-last-sexp, bound to C-x C-e. A gnu convention.
87;;; - Have not added process query facility a la cmulisp.el's lisp-show-arglist
88;;;   and friends, but interested hackers might find a useful application
89;;;   of this facility.
90;;;
91;;; 3/12/90 Olin
92;;; - scheme-load-file and scheme-compile-file no longer switch-to-scheme.
93;;;   Tale suggested this.
94
95;;; Code:
96
97(require 'scheme)
98(require 'comint)
99
100
101(defgroup cmuscheme nil
102  "Run a scheme process in a buffer."
103  :group 'scheme)
104
105;;; INFERIOR SCHEME MODE STUFF
106;;;============================================================================
107
108(defcustom inferior-scheme-mode-hook nil
109  "*Hook for customizing inferior-scheme mode."
110  :type 'hook
111  :group 'cmuscheme)
112
113(defvar inferior-scheme-mode-map
114  (let ((m (make-sparse-keymap)))
115    (define-key m "\M-\C-x" 'scheme-send-definition) ;gnu convention
116    (define-key m "\C-x\C-e" 'scheme-send-last-sexp)
117    (define-key m "\C-c\C-l" 'scheme-load-file)
118    (define-key m "\C-c\C-k" 'scheme-compile-file)
119    (scheme-mode-commands m)
120    m))
121
122;; Install the process communication commands in the scheme-mode keymap.
123(define-key scheme-mode-map "\M-\C-x" 'scheme-send-definition);gnu convention
124(define-key scheme-mode-map "\C-x\C-e" 'scheme-send-last-sexp);gnu convention
125(define-key scheme-mode-map "\C-c\C-e" 'scheme-send-definition)
126(define-key scheme-mode-map "\C-c\M-e" 'scheme-send-definition-and-go)
127(define-key scheme-mode-map "\C-c\C-r" 'scheme-send-region)
128(define-key scheme-mode-map "\C-c\M-r" 'scheme-send-region-and-go)
129(define-key scheme-mode-map "\C-c\M-c" 'scheme-compile-definition)
130(define-key scheme-mode-map "\C-c\C-c" 'scheme-compile-definition-and-go)
131(define-key scheme-mode-map "\C-c\C-t" 'scheme-trace-procedure)
132(define-key scheme-mode-map "\C-c\C-x" 'scheme-expand-current-form)
133(define-key scheme-mode-map "\C-c\C-z" 'switch-to-scheme)
134(define-key scheme-mode-map "\C-c\C-l" 'scheme-load-file)
135(define-key scheme-mode-map "\C-c\C-k" 'scheme-compile-file) ;k for "kompile"
136
137(let ((map (lookup-key scheme-mode-map [menu-bar scheme])))
138  (define-key map [separator-eval] '("--"))
139  (define-key map [compile-file]
140    '("Compile Scheme File" . scheme-compile-file))
141  (define-key map [load-file]
142    '("Load Scheme File" . scheme-load-file))
143  (define-key map [switch]
144    '("Switch to Scheme" . switch-to-scheme))
145  (define-key map [com-def-go]
146    '("Compile Definition & Go" . scheme-compile-definition-and-go))
147  (define-key map [com-def]
148    '("Compile Definition" . scheme-compile-definition))
149  (define-key map [exp-form]
150    '("Expand current form" . scheme-expand-current-form))
151  (define-key map [trace-proc]
152    '("Trace procedure" . scheme-trace-procedure))
153  (define-key map [send-def-go]
154    '("Evaluate Last Definition & Go" . scheme-send-definition-and-go))
155  (define-key map [send-def]
156    '("Evaluate Last Definition" . scheme-send-definition))
157  (define-key map [send-region-go]
158    '("Evaluate Region & Go" . scheme-send-region-and-go))
159  (define-key map [send-region]
160    '("Evaluate Region" . scheme-send-region))
161  (define-key map [send-sexp]
162    '("Evaluate Last S-expression" . scheme-send-last-sexp))
163  )
164
165(defvar scheme-buffer)
166
167(define-derived-mode inferior-scheme-mode comint-mode "Inferior Scheme"
168  "Major mode for interacting with an inferior Scheme process.
169
170The following commands are available:
171\\{inferior-scheme-mode-map}
172
173A Scheme process can be fired up with M-x run-scheme.
174
175Customization: Entry to this mode runs the hooks on comint-mode-hook and
176inferior-scheme-mode-hook (in that order).
177
178You can send text to the inferior Scheme process from other buffers containing
179Scheme source.
180    switch-to-scheme switches the current buffer to the Scheme process buffer.
181    scheme-send-definition sends the current definition to the Scheme process.
182    scheme-compile-definition compiles the current definition.
183    scheme-send-region sends the current region to the Scheme process.
184    scheme-compile-region compiles the current region.
185
186    scheme-send-definition-and-go, scheme-compile-definition-and-go,
187        scheme-send-region-and-go, and scheme-compile-region-and-go
188        switch to the Scheme process buffer after sending their text.
189For information on running multiple processes in multiple buffers, see
190documentation for variable scheme-buffer.
191
192Commands:
193Return after the end of the process' output sends the text from the
194    end of process to point.
195Return before the end of the process' output copies the sexp ending at point
196    to the end of the process' output, and sends it.
197Delete converts tabs to spaces as it moves back.
198Tab indents for Scheme; with argument, shifts rest
199    of expression rigidly with the current line.
200C-M-q does Tab on each line starting within following expression.
201Paragraphs are separated only by blank lines.  Semicolons start comments.
202If you accidentally suspend your process, use \\[comint-continue-subjob]
203to continue it."
204  ;; Customize in inferior-scheme-mode-hook
205  (setq comint-prompt-regexp "^[^>\n]*>+ *") ; OK for cscheme, oaklisp, T,...
206  (scheme-mode-variables)
207  (setq mode-line-process '(":%s"))
208  (setq comint-input-filter (function scheme-input-filter))
209  (setq comint-get-old-input (function scheme-get-old-input)))
210
211(defcustom inferior-scheme-filter-regexp "\\`\\s *\\S ?\\S ?\\s *\\'"
212  "*Input matching this regexp are not saved on the history list.
213Defaults to a regexp ignoring all inputs of 0, 1, or 2 letters."
214  :type 'regexp
215  :group 'cmuscheme)
216
217(defun scheme-input-filter (str)
218  "Don't save anything matching `inferior-scheme-filter-regexp'."
219  (not (string-match inferior-scheme-filter-regexp str)))
220
221(defun scheme-get-old-input ()
222  "Snarf the sexp ending at point."
223  (save-excursion
224    (let ((end (point)))
225      (backward-sexp)
226      (buffer-substring (point) end))))
227
228(defun scheme-args-to-list (string)
229  (let ((where (string-match "[ \t]" string)))
230    (cond ((null where) (list string))
231	  ((not (= where 0))
232	   (cons (substring string 0 where)
233		 (scheme-args-to-list (substring string (+ 1 where)
234						 (length string)))))
235	  (t (let ((pos (string-match "[^ \t]" string)))
236	       (if (null pos)
237		   nil
238		 (scheme-args-to-list (substring string pos
239						 (length string)))))))))
240
241;;;###autoload
242(defun run-scheme (cmd)
243  "Run an inferior Scheme process, input and output via buffer `*scheme*'.
244If there is a process already running in `*scheme*', switch to that buffer.
245With argument, allows you to edit the command line (default is value
246of `scheme-program-name').
247If the file `~/.emacs_SCHEMENAME' or `~/.emacs.d/init_SCHEMENAME.scm' exists,
248it is given as initial input.
249Note that this may lose due to a timing error if the Scheme processor
250discards input when it starts up.
251Runs the hook `inferior-scheme-mode-hook' \(after the `comint-mode-hook'
252is run).
253\(Type \\[describe-mode] in the process buffer for a list of commands.)"
254
255  (interactive (list (if current-prefix-arg
256			 (read-string "Run Scheme: " scheme-program-name)
257			 scheme-program-name)))
258  (if (not (comint-check-proc "*scheme*"))
259      (let ((cmdlist (scheme-args-to-list cmd)))
260	(set-buffer (apply 'make-comint "scheme" (car cmdlist)
261			   (scheme-start-file (car cmdlist)) (cdr cmdlist)))
262	(inferior-scheme-mode)))
263  (setq scheme-program-name cmd)
264  (setq scheme-buffer "*scheme*")
265  (pop-to-buffer "*scheme*"))
266;;;###autoload (add-hook 'same-window-buffer-names "*scheme*")
267
268(defun scheme-start-file (prog)
269  "Return the name of the start file corresponding to PROG.
270Search in the directories \"~\" and \"~/.emacs.d\", in this
271order.  Return nil if no start file found."
272  (let* ((progname (file-name-nondirectory prog))
273	 (start-file (concat "~/.emacs_" progname))
274	 (alt-start-file (concat "~/.emacs.d/init_" progname ".scm")))
275    (if (file-exists-p start-file)
276        start-file
277      (and (file-exists-p alt-start-file) alt-start-file))))
278
279(defun scheme-send-region (start end)
280  "Send the current region to the inferior Scheme process."
281  (interactive "r")
282  (comint-send-region (scheme-proc) start end)
283  (comint-send-string (scheme-proc) "\n"))
284
285(defun scheme-send-definition ()
286  "Send the current definition to the inferior Scheme process."
287  (interactive)
288  (save-excursion
289   (end-of-defun)
290   (let ((end (point)))
291     (beginning-of-defun)
292     (scheme-send-region (point) end))))
293
294(defun scheme-send-last-sexp ()
295  "Send the previous sexp to the inferior Scheme process."
296  (interactive)
297  (scheme-send-region (save-excursion (backward-sexp) (point)) (point)))
298
299(defcustom scheme-compile-exp-command "(compile '%s)"
300  "*Template for issuing commands to compile arbitrary Scheme expressions."
301  :type 'string
302  :group 'cmuscheme)
303
304(defun scheme-compile-region (start end)
305  "Compile the current region in the inferior Scheme process.
306\(A BEGIN is wrapped around the region: (BEGIN <region>))"
307  (interactive "r")
308  (comint-send-string (scheme-proc) (format scheme-compile-exp-command
309					    (format "(begin %s)"
310						    (buffer-substring start end))))
311  (comint-send-string (scheme-proc) "\n"))
312
313(defun scheme-compile-definition ()
314  "Compile the current definition in the inferior Scheme process."
315  (interactive)
316  (save-excursion
317   (end-of-defun)
318   (let ((end (point)))
319     (beginning-of-defun)
320     (scheme-compile-region (point) end))))
321
322(defcustom scheme-trace-command "(trace %s)"
323  "*Template for issuing commands to trace a Scheme procedure.
324Some Scheme implementations might require more elaborate commands here.
325For PLT-Scheme, e.g., one should use
326
327   (setq scheme-trace-command \"(begin (require (lib \\\"trace.ss\\\")) (trace %s))\")
328
329For Scheme 48 and Scsh use \",trace %s\"."
330  :type 'string
331  :group 'cmuscheme)
332
333(defcustom scheme-untrace-command "(untrace %s)"
334  "*Template for switching off tracing of a Scheme procedure.
335Scheme 48 and Scsh users should set this variable to \",untrace %s\"."
336
337  :type 'string
338  :group 'cmuscheme)
339
340(defun scheme-trace-procedure (proc &optional untrace)
341  "Trace procedure PROC in the inferior Scheme process.
342With a prefix argument switch off tracing of procedure PROC."
343  (interactive
344   (list (let ((current (symbol-at-point))
345               (action (if current-prefix-arg "Untrace" "Trace")))
346           (if current
347               (read-string (format "%s procedure [%s]: " action current) nil nil (symbol-name current))
348             (read-string (format "%s procedure: " action))))
349         current-prefix-arg))
350  (when (= (length proc) 0)
351    (error "Invalid procedure name"))
352  (comint-send-string (scheme-proc)
353                      (format
354                       (if untrace scheme-untrace-command scheme-trace-command)
355                       proc))
356  (comint-send-string (scheme-proc) "\n"))
357
358(defcustom scheme-macro-expand-command "(expand %s)"
359  "*Template for macro-expanding a Scheme form.
360For Scheme 48 and Scsh use \",expand %s\"."
361  :type 'string
362  :group 'cmuscheme)
363
364(defun scheme-expand-current-form ()
365  "Macro-expand the form at point in the inferior Scheme process."
366  (interactive)
367  (let ((current-form (scheme-form-at-point)))
368    (if current-form
369        (progn
370          (comint-send-string (scheme-proc)
371                              (format
372                               scheme-macro-expand-command
373                               current-form))
374          (comint-send-string (scheme-proc) "\n"))
375      (error "Not at a form"))))
376
377(defun scheme-form-at-point ()
378  (let ((next-sexp (thing-at-point 'sexp)))
379    (if (and next-sexp (string-equal (substring next-sexp 0 1) "("))
380        next-sexp
381      (save-excursion
382        (backward-up-list)
383        (scheme-form-at-point)))))
384
385(defun switch-to-scheme (eob-p)
386  "Switch to the scheme process buffer.
387With argument, position cursor at end of buffer."
388  (interactive "P")
389  (if (or (and scheme-buffer (get-buffer scheme-buffer))
390          (scheme-interactively-start-process))
391      (pop-to-buffer scheme-buffer)
392    (error "No current process buffer.  See variable `scheme-buffer'"))
393  (when eob-p
394    (push-mark)
395    (goto-char (point-max))))
396
397(defun scheme-send-region-and-go (start end)
398  "Send the current region to the inferior Scheme process.
399Then switch to the process buffer."
400  (interactive "r")
401  (scheme-send-region start end)
402  (switch-to-scheme t))
403
404(defun scheme-send-definition-and-go ()
405  "Send the current definition to the inferior Scheme.
406Then switch to the process buffer."
407  (interactive)
408  (scheme-send-definition)
409  (switch-to-scheme t))
410
411(defun scheme-compile-definition-and-go ()
412  "Compile the current definition in the inferior Scheme.
413Then switch to the process buffer."
414  (interactive)
415  (scheme-compile-definition)
416  (switch-to-scheme t))
417
418(defun scheme-compile-region-and-go (start end)
419  "Compile the current region in the inferior Scheme.
420Then switch to the process buffer."
421  (interactive "r")
422  (scheme-compile-region start end)
423  (switch-to-scheme t))
424
425(defcustom scheme-source-modes '(scheme-mode)
426  "*Used to determine if a buffer contains Scheme source code.
427If it's loaded into a buffer that is in one of these major modes, it's
428considered a scheme source file by `scheme-load-file' and `scheme-compile-file'.
429Used by these commands to determine defaults."
430  :type '(repeat function)
431  :group 'cmuscheme)
432
433(defvar scheme-prev-l/c-dir/file nil
434  "Caches the last (directory . file) pair.
435Caches the last pair used in the last `scheme-load-file' or
436`scheme-compile-file' command.  Used for determining the default
437in the next one.")
438
439(defun scheme-load-file (file-name)
440  "Load a Scheme file FILE-NAME into the inferior Scheme process."
441  (interactive (comint-get-source "Load Scheme file: " scheme-prev-l/c-dir/file
442				  scheme-source-modes t)) ; t because `load'
443                                                          ; needs an exact name
444  (comint-check-source file-name) ; Check to see if buffer needs saved.
445  (setq scheme-prev-l/c-dir/file (cons (file-name-directory    file-name)
446				       (file-name-nondirectory file-name)))
447  (comint-send-string (scheme-proc) (concat "(load \""
448					    file-name
449					    "\"\)\n")))
450
451(defun scheme-compile-file (file-name)
452  "Compile a Scheme file FILE-NAME in the inferior Scheme process."
453  (interactive (comint-get-source "Compile Scheme file: "
454				  scheme-prev-l/c-dir/file
455				  scheme-source-modes
456				  nil)) ; nil because COMPILE doesn't
457                                        ; need an exact name.
458  (comint-check-source file-name) ; Check to see if buffer needs saved.
459  (setq scheme-prev-l/c-dir/file (cons (file-name-directory    file-name)
460				       (file-name-nondirectory file-name)))
461  (comint-send-string (scheme-proc) (concat "(compile-file \""
462					    file-name
463					    "\"\)\n")))
464
465
466(defvar scheme-buffer nil "*The current scheme process buffer.
467
468MULTIPLE PROCESS SUPPORT
469===========================================================================
470Cmuscheme.el supports, in a fairly simple fashion, running multiple Scheme
471processes.  To run multiple Scheme processes, you start the first up with
472\\[run-scheme].  It will be in a buffer named *scheme*.  Rename this buffer
473with \\[rename-buffer].  You may now start up a new process with another
474\\[run-scheme].  It will be in a new buffer, named *scheme*.  You can
475switch between the different process buffers with \\[switch-to-buffer].
476
477Commands that send text from source buffers to Scheme processes --
478like `scheme-send-definition' or `scheme-compile-region' -- have to choose a
479process to send to, when you have more than one Scheme process around.  This
480is determined by the global variable `scheme-buffer'.  Suppose you
481have three inferior Schemes running:
482    Buffer	Process
483    foo		scheme
484    bar		scheme<2>
485    *scheme*    scheme<3>
486If you do a \\[scheme-send-definition-and-go] command on some Scheme source
487code, what process do you send it to?
488
489- If you're in a process buffer (foo, bar, or *scheme*),
490  you send it to that process.
491- If you're in some other buffer (e.g., a source file), you
492  send it to the process attached to buffer `scheme-buffer'.
493This process selection is performed by function `scheme-proc'.
494
495Whenever \\[run-scheme] fires up a new process, it resets `scheme-buffer'
496to be the new process's buffer.  If you only run one process, this will
497do the right thing.  If you run multiple processes, you can change
498`scheme-buffer' to another process buffer with \\[set-variable].
499
500More sophisticated approaches are, of course, possible.  If you find yourself
501needing to switch back and forth between multiple processes frequently,
502you may wish to consider ilisp.el, a larger, more sophisticated package
503for running inferior Lisp and Scheme processes.  The approach taken here is
504for a minimal, simple implementation.  Feel free to extend it.")
505
506(defun scheme-proc ()
507  "Return the current Scheme process, starting one if necessary.
508See variable `scheme-buffer'."
509  (unless (and scheme-buffer
510               (get-buffer scheme-buffer)
511               (comint-check-proc scheme-buffer))
512    (scheme-interactively-start-process))
513  (or (scheme-get-process)
514      (error "No current process.  See variable `scheme-buffer'")))
515
516(defun scheme-get-process ()
517  "Return the current Scheme process or nil if none is running."
518  (get-buffer-process (if (eq major-mode 'inferior-scheme-mode)
519                          (current-buffer)
520                        scheme-buffer)))
521
522(defun scheme-interactively-start-process (&optional cmd)
523  "Start an inferior Scheme process.  Return the process started.
524Since this command is run implicitly, always ask the user for the
525command to run."
526  (save-window-excursion
527    (run-scheme (read-string "Run Scheme: " scheme-program-name))))
528
529;;; Do the user's customization...
530
531(defcustom cmuscheme-load-hook nil
532  "This hook is run when cmuscheme is loaded in.
533This is a good place to put keybindings."
534  :type 'hook
535  :group 'cmuscheme)
536
537(run-hooks 'cmuscheme-load-hook)
538
539(provide 'cmuscheme)
540
541;; arch-tag: e8795f4a-c496-45a2-97b4-8e0f2a2c57d2
542;;; cmuscheme.el ends here
543