Initial Commit
[packages] / xemacs-packages / xemacs-devel / ielm.el
1 ;;; ielm.el --- interaction mode for Emacs Lisp
2
3 ;; Copyright (C) 1994 Free Software Foundation, Inc.
4
5 ;; Author: David Smith <maa036@lancaster.ac.uk>
6 ;; Maintainer: FSF
7 ;; Created: 25 Feb 1994
8 ;; Keywords: 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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; Provides a nice interface to evaluating Emacs Lisp expressions.
30 ;; Input is handled by the comint package, and output is passed
31 ;; through the pretty-printer.
32
33 ;; To install: copy this file to a directory in your load-path, and
34 ;; add the following line to your .emacs file:
35 ;;
36 ;;   (autoload 'ielm "ielm" "Start an inferior Emacs Lisp session" t)
37 ;;
38 ;; For completion to work, the comint.el from Emacs 19.23 is
39 ;; required.  If you do not have it, or if you are running Lemacs,
40 ;; also add the following code to your .emacs:
41 ;;
42 ;;    (setq ielm-mode-hook
43 ;;          '(lambda nil
44 ;;               (define-key ielm-map "\t"
45 ;;                  '(lambda nil (interactive) (or (ielm-tab) 
46 ;;                                                 (lisp-complete-symbol))))))
47
48 ;; To start: M-x ielm.  Type C-h m in the *ielm* buffer for more info.
49
50 ;; The latest version is available by WWW from 
51 ;;      http://mathssun5.lancs.ac.uk:2080/~maa036/elisp/dir.html
52 ;; or by anonymous FTP from
53 ;;      /anonymous@wingra.stat.wisc.edu:pub/src/emacs-lisp/ielm.el.gz
54 ;; or from the author: David M. Smith <maa036@lancaster.ac.uk>
55
56 ;;; Code:
57
58 (require 'comint)
59 (require 'pp)
60
61 ;;; User variables
62
63 (defgroup ielm nil
64   "Interaction mode for Emacs Lisp."
65   :group 'lisp)
66
67
68 (defcustom ielm-noisy t
69   "*If non-nil, IELM will beep on error."
70   :type 'boolean
71   :group 'ielm)
72
73 (defvar ielm-prompt "ELISP> "
74   "Prompt used in IELM.")
75
76 (defcustom ielm-dynamic-return t
77   "*Controls whether \\<ielm-map>\\[ielm-return] has intelligent behaviour in IELM.
78 If non-nil, \\[ielm-return] evaluates input for complete sexps, or inserts a newline
79 and indents for incomplete sexps.  If nil, always inserts newlines."
80   :type 'boolean
81   :group 'ielm)
82
83 (defcustom ielm-dynamic-multiline-inputs t
84   "*Force multiline inputs to start from column zero?
85 If non-nil, after entering the first line of an incomplete sexp, a newline
86 will be inserted after the prompt, moving the input to the next line.
87 This gives more frame width for large indented sexps, and allows functions
88 such as `edebug-defun' to work with such inputs."
89   :type 'boolean
90   :group 'ielm)
91
92 (defcustom ielm-mode-hook nil
93   "*Hooks to be run when IELM (`inferior-emacs-lisp-mode') is started."
94   :type 'hook
95   :group 'ielm)
96
97 ;;; System variables
98
99 (defvar ielm-working-buffer nil
100   "Buffer in which IELM sexps will be evaluated.
101 This variable is buffer-local.")
102
103 (defvar ielm-header 
104   "*** Welcome to IELM ***  Type (describe-mode) for help.\n"
105   "Message to display when IELM is started.")
106
107 (defvar ielm-map nil)
108 (if ielm-map nil
109   (if (string-match "Lucid" emacs-version)
110       ;; Lemacs
111       (progn
112         (setq ielm-map (make-sparse-keymap))
113         (set-keymap-parent ielm-map comint-mode-map))
114     ;; FSF
115     (setq ielm-map (cons 'keymap comint-mode-map)))
116   (define-key ielm-map "\t" 'comint-dynamic-complete)
117   (define-key ielm-map "\C-m" 'ielm-return)
118   (define-key ielm-map "\C-j" 'ielm-send-input)
119   (define-key ielm-map "\e\C-x" 'eval-defun)         ; for consistency with
120   (define-key ielm-map "\e\t" 'lisp-complete-symbol) ; lisp-interaction-mode
121   ;; These bindings are from shared-lisp-mode-map -- can you inherit
122   ;; from more than one keymap??
123   (define-key ielm-map "\e\C-q" 'indent-sexp)      
124   (define-key ielm-map "\177" 'backward-delete-char-untabify)
125   ;; Some convenience bindings for setting the working buffer
126   (define-key ielm-map "\C-c\C-b" 'ielm-change-working-buffer)
127   (define-key ielm-map "\C-c\C-f" 'ielm-display-working-buffer)
128   (define-key ielm-map "\C-c\C-v" 'ielm-print-working-buffer))
129
130 (defvar ielm-font-lock-keywords
131   (list 
132    (cons (concat "^" (regexp-quote ielm-prompt)) 'font-lock-keyword-face)
133    '("\\(^\\*\\*\\*[^*]+\\*\\*\\*\\)\\(.*$\\)" (1 font-lock-comment-face) (2 font-lock-reference-face)))
134   "Additional expressions to highlight in ielm buffers.")
135         
136 ;;; Completion stuff
137
138 (defun ielm-tab nil
139   "Possibly indent the current line as lisp code."
140   (interactive)
141   (if (or (eq (preceding-char) ?\n)
142           (eq (char-syntax (preceding-char)) ? ))
143       (progn
144         (ielm-indent-line)
145         t)))
146   
147 (defun ielm-complete-symbol nil
148   "Complete the lisp symbol before point."
149   ;; A wrapper for lisp-complete symbol that returns non-nil if
150   ;; completion has occurred
151   (let* ((btick (buffer-modified-tick))
152          (cbuffer (get-buffer "*Completions*"))
153          (ctick (and cbuffer (buffer-modified-tick cbuffer))))
154     (lisp-complete-symbol)
155      ;; completion has occurred if:
156     (or 
157      ;; the buffer has been modified
158      (not (= btick (buffer-modified-tick))) 
159      ;; a completions buffer has been modified or created
160      (if cbuffer
161          (not (= ctick (buffer-modified-tick cbuffer)))
162        (get-buffer "*Completions*")))))
163
164 (defun ielm-complete-filename nil
165   "Dynamically complete filename before point, if in a string."
166   (if (nth 3 (parse-partial-sexp comint-last-input-start (point)))
167       (comint-dynamic-complete-filename)))
168      
169 (defun ielm-indent-line nil
170   "Indent the current line as Lisp code if it is not a prompt line."
171   (if (save-excursion
172         (beginning-of-line)
173         (looking-at comint-prompt-regexp)) nil
174     (lisp-indent-line)))
175
176 ;;; Working buffer manipulation
177
178 (defun ielm-print-working-buffer nil
179   "Print the current IELM working buffer's name in the echo area."
180   (interactive)
181   (message "The current working buffer is: %s" (buffer-name ielm-working-buffer)))
182
183 (defun ielm-display-working-buffer nil
184   "Display the current IELM working buffer.
185 Don't forget that selecting that buffer will change its value of `point'
186 to its value of `window-point'!"
187   (interactive)
188   (display-buffer ielm-working-buffer)
189   (ielm-print-working-buffer))
190
191 (defun ielm-change-working-buffer (buf)
192   "Change the current IELM working buffer to BUF.
193 This is the buffer in which all sexps entered at the IELM prompt are
194 evaluated.  You can achieve the same effect with a call to
195 `set-buffer' at the IELM prompt."
196   (interactive "bSet working buffer to: ")
197   (setq ielm-working-buffer (or (get-buffer buf) (error "No such buffer")))
198   (ielm-print-working-buffer))
199
200 ;;; Other bindings
201
202 (defun ielm-return nil
203   "Newline and indent, or evaluate the sexp before the prompt.
204 Complete sexps are evaluated; for incomplete sexps inserts a newline
205 and indents.  If however `ielm-dynamic-return' is nil, this always
206 simply inserts a newline."
207   (interactive)
208   (if ielm-dynamic-return 
209       (let ((state       
210              (save-excursion
211                (end-of-line)
212                (parse-partial-sexp (ielm-pm)
213                                    (point)))))
214         (if (and (< (car state) 1) (not (nth 3 state)))
215             (ielm-send-input)
216           (if (and ielm-dynamic-multiline-inputs
217                    (save-excursion
218                      (beginning-of-line)
219                      (looking-at comint-prompt-regexp)))
220               (save-excursion
221                 (goto-char (ielm-pm))
222                 (newline 1)))
223           (newline-and-indent)))
224     (newline)))
225
226 (defvar ielm-input)
227
228 (defun ielm-input-sender (proc input)
229   ;; Just sets the variable ielm-input, which is in the scope of 
230   ;; `ielm-send-input's call.
231   (setq ielm-input input))
232
233 (defun ielm-send-input nil
234   "Evaluate the Emacs Lisp expression after the prompt."
235   (interactive)
236   (let ((buf (current-buffer))
237         ielm-input)                     ; set by ielm-input-sender
238     (comint-send-input)                 ; update history, markers etc.
239     (ielm-eval-input ielm-input)))
240
241 ;;; Utility functions
242
243 (defun ielm-is-whitespace (string)
244   "Return non-nil if STRING is all whitespace."
245   (or (string= string "") (string-match "\\`[ \t\n]+\\'" string)))
246
247 (defun ielm-format-errors (errlist)
248   (let ((result ""))
249     (while errlist
250       (setq result (concat result (prin1-to-string (car errlist)) ", "))
251       (setq errlist (cdr errlist)))
252     (substring result 0 -2)))
253
254
255 (defun ielm-format-error (err)
256   ;; Return a string form of the error ERR.
257   (format "%s%s"
258           (or (get (car err) 'error-message) "Peculiar error")
259           (if (cdr err)
260               (format ": %s" (ielm-format-errors (cdr err)))
261             "")))
262
263 ;;; Evaluation
264
265 (defun ielm-eval-input (ielm-string)
266   "Evaluate the Lisp expression IELM-STRING, and pretty-print the result."
267   ;; This is the function that actually `sends' the input to the
268   ;; `inferior Lisp process'. All comint-send-input does is works out
269   ;; what that input is.  What this function does is evaluates that
270   ;; input and produces `output' which gets inserted into the buffer,
271   ;; along with a new prompt.  A better way of doing this might have
272   ;; been to actually send the output to the `cat' process, and write
273   ;; this as in output filter that converted sexps in the output
274   ;; stream to their evaluated value.  But that would have involved
275   ;; more process coordination than I was happy to deal with.
276   ;;
277   ;; NOTE: all temporary variables in this function will be in scope
278   ;; during the eval, and so need to have non-clashing names.
279   (let (ielm-form                       ; form to evaluate
280         ielm-pos                        ; End posn of parse in string
281         ielm-result                     ; Result, or error message
282         ielm-error-type                 ; string, nil if no error
283         (ielm-output    "")             ; result to display
284         (ielm-wbuf ielm-working-buffer) ; current buffer after evaluation
285         (ielm-pmark (ielm-pm)))
286     (if (and (not (null ielm-string))
287              (not (ielm-is-whitespace ielm-string)))
288         (progn
289           (condition-case err
290               (let (rout)
291                 (setq rout (read-from-string ielm-string))
292                 (setq ielm-form (car rout))
293                 (setq ielm-pos (cdr rout)))
294             (error (setq ielm-result (ielm-format-error err))
295                    (setq ielm-error-type "Read error")))
296           (if ielm-error-type nil
297             ;; Make sure working buffer has not been killed
298             (if (not (buffer-name ielm-working-buffer))
299                 (setq ielm-result "Working buffer has been killed"
300                       ielm-error-type "IELM Error"
301                       ielm-wbuf (current-buffer))
302               (if (ielm-is-whitespace (substring ielm-string ielm-pos))
303                   ;; need this awful let convolution to work around
304                   ;; an Emacs bug involving local vbls and let binding
305                   (let ((!save !)
306                         (!!save !!)
307                         (!!!save !!!))
308                     (save-excursion
309                       (set-buffer ielm-working-buffer)
310                       (condition-case err
311                           (let ((! !save)
312                                 (!! !!save)
313                                 (!!! !!!save)
314                                 (ielm-obuf (current-buffer)))
315                             (setq ielm-result (eval ielm-form))
316                             (setq ielm-wbuf (current-buffer))
317                             ;; The eval may have changed current-buffer;
318                             ;; need to set it back here to avoid a bug
319                             ;; in let.  Don't want to use save-excursion
320                             ;; because we want to allow changes in point.
321                             (set-buffer ielm-obuf))
322                         (error (setq ielm-result (ielm-format-error err))
323                                (setq ielm-error-type "Eval error"))
324                         (quit (setq ielm-result "Quit during evaluation")
325                               (setq ielm-error-type "Eval error")))))
326                 (setq ielm-error-type "IELM error")
327                 (setq ielm-result "More than one sexp in input"))))
328
329           ;; If the eval changed the current buffer, mention it here
330           (if (eq ielm-wbuf ielm-working-buffer) nil
331             (message "current buffer is now: %s" ielm-wbuf)
332             (setq ielm-working-buffer ielm-wbuf))
333
334           (goto-char ielm-pmark)
335           (if (not ielm-error-type)
336               (condition-case err
337                   ;; Self-referential objects cause loops in the printer, so
338                   ;; trap quits here. May as well do errors, too
339                   (setq ielm-output (concat ielm-output (pp-to-string ielm-result)))
340                 (error (setq ielm-error-type "IELM Error")
341                        (setq ielm-result  "Error during pretty-printing (bug in pp)"))
342                 (quit  (setq ielm-error-type "IELM Error")
343                        (setq ielm-result "Quit during pretty-printing"))))
344           (if ielm-error-type
345               (progn
346                 (if ielm-noisy (ding))
347                 (setq ielm-output (concat ielm-output "*** " ielm-error-type " ***  "))
348                 (setq ielm-output (concat ielm-output ielm-result)))
349             ;; There was no error, so shift the !!! values
350             (setq !!! !!)
351             (setq !! !)
352             (setq ! ielm-result))
353           (setq ielm-output (concat ielm-output "\n"))))
354     (if (not (null ielm-string))
355         (setq ielm-output (concat ielm-output ielm-prompt)))
356     (comint-output-filter (ielm-process) ielm-output)))
357
358 ;;; Process and marker utilities
359
360 (defun ielm-process nil
361   ;; Return the current buffer's process.
362   (get-buffer-process (current-buffer)))
363
364 (defun ielm-pm nil
365   ;; Return the process mark of the current buffer.
366   (process-mark (get-buffer-process (current-buffer))))
367
368 (defun ielm-set-pm (pos)
369   ;; Set the process mark in the current buffer to POS.
370   (set-marker (process-mark (get-buffer-process (current-buffer))) pos))
371
372 ;;; Major mode
373
374 (put 'inferior-emacs-lisp-mode 'mode-class 'special)
375
376 (defun inferior-emacs-lisp-mode nil
377   "Major mode for interactively evaluating Emacs Lisp expressions.
378 Uses the interface provided by `comint-mode' (which see).
379
380 * \\<ielm-map>\\[ielm-send-input] evaluates the sexp following the prompt. There must be at most
381   one top-level sexp per prompt.
382
383 * \\[ielm-return] inserts a newline and indents, or evaluates a
384   complete expression (but see variable `ielm-dynamic-return').
385   Inputs longer than one line are moved to the line following the
386   prompt (but see variable `ielm-dynamic-multiline-inputs').
387
388 * \\[comint-dynamic-complete] completes Lisp symbols (or filenames, within strings), 
389   or indents the line if there is nothing to complete.
390
391 During evaluations, the values of the variables `!', `!!', and `!!!'
392 are the results of the previous, second previous and third previous
393 evaluations respectively.
394
395 The current working buffer may be changed (with a call to
396 `set-buffer', or with \\[ielm-change-working-buffer]), and its value
397 is preserved between successive evaluations.  In this way, expressions
398 may be evaluated in a different buffer than the *ielm* buffer.
399 Display the name of the working buffer with \\[ielm-print-working-buffer],
400 or the buffer itself with \\[ielm-display-working-buffer].
401
402 Expressions evaluated by IELM are not subject to `debug-on-quit' or
403 `debug-on-error'.
404
405 The behaviour of IELM may be customised with the following variables:
406 * To stop beeping on error, set `ielm-noisy' to nil
407 * If you don't like the prompt, you can change it by setting `ielm-prompt'.
408 * Set `ielm-dynamic-return' to nil for bindings like `lisp-interaction-mode'
409 * Entry to this mode runs `comint-mode-hook' and `ielm-mode-hook'
410  (in that order).
411
412 Customised bindings may be defined in `ielm-map', which currently contains:
413 \\{ielm-map}"
414   (interactive)
415   (comint-mode)
416   (setq comint-prompt-regexp (concat "^" (regexp-quote ielm-prompt)))
417   (make-local-variable 'paragraph-start)
418   (setq paragraph-start comint-prompt-regexp)
419   (setq comint-input-sender 'ielm-input-sender)
420   (setq comint-process-echoes nil)
421   (setq comint-dynamic-complete-functions 
422         '(ielm-tab comint-replace-by-expanded-history ielm-complete-filename ielm-complete-symbol))
423   (setq comint-get-old-input 'ielm-get-old-input)
424   (make-local-variable 'comint-completion-addsuffix)
425   (setq comint-completion-addsuffix
426         (cons (char-to-string directory-sep-char) ""))
427
428   (setq major-mode 'inferior-emacs-lisp-mode)
429   (setq mode-name "IELM")
430   (use-local-map ielm-map)
431   (set-syntax-table emacs-lisp-mode-syntax-table)
432
433   (make-local-variable 'indent-line-function)
434   (make-local-variable 'ielm-working-buffer)
435   (setq ielm-working-buffer (current-buffer))
436   (setq indent-line-function 'ielm-indent-line)
437   (make-local-variable 'fill-paragraph-function)
438   (setq fill-paragraph-function 'lisp-fill-paragraph)
439
440   ;; Value holders
441   (setq ! nil)
442   (make-local-variable '!)
443   (setq !! nil)
444   (make-local-variable '!!)
445   (setq !!! nil)
446   (make-local-variable '!!!)
447
448   ;; font-lock support
449   (make-local-variable 'font-lock-defaults)
450   (setq font-lock-defaults 
451         '(ielm-font-lock-keywords nil nil ((?! . "w") (?- . "w") (?* . "w"))))
452   
453   ;; A dummy process to keep comint happy. It will never get any input
454   (if (comint-check-proc (current-buffer)) nil
455     (start-process "ielm" (current-buffer) "cat")
456     (process-kill-without-query (ielm-process))
457     (goto-char (point-max))
458     ;; Add a silly header
459     (insert ielm-header)
460     (ielm-set-pm (point-max))
461     (comint-output-filter (ielm-process) ielm-prompt)
462     (set-marker comint-last-input-start (ielm-pm))
463     (set-process-filter (get-buffer-process (current-buffer)) 'comint-output-filter))
464   (run-hooks 'ielm-mode-hook))
465
466 (defun ielm-get-old-input nil
467   ;; Return the previous input surrounding point
468   (save-excursion
469     (beginning-of-line)
470     (if (looking-at comint-prompt-regexp) nil
471       (re-search-backward comint-prompt-regexp))
472     (comint-skip-prompt)
473     (buffer-substring (point) (progn (forward-sexp 1) (point)))))
474
475 ;;; User command
476
477 ;;;###autoload (add-hook 'same-window-buffer-names "*ielm*")
478
479 ;;;###autoload
480 (defun ielm nil
481   "Interactively evaluate Emacs Lisp expressions.
482 Switches to the buffer `*ielm*', or creates it if it does not exist."
483   (interactive)
484   (if (comint-check-proc "*ielm*")
485       nil
486     (save-excursion
487       (set-buffer (get-buffer-create "*ielm*"))
488       (inferior-emacs-lisp-mode)))
489   (pop-to-buffer "*ielm*"))
490
491 (provide 'ielm)
492
493 ;;; ielm.el ends here