lisp/desktop.el (desktop-clear): Fix previous change.
[emacs.git] / lisp / ielm.el
blob4280a49af6ebaceb48e5ffef78a4af76be026580
1 ;;; ielm.el --- interaction mode for Emacs Lisp
3 ;; Copyright (C) 1994, 2001-2013 Free Software Foundation, Inc.
5 ;; Author: David Smith <maa036@lancaster.ac.uk>
6 ;; Maintainer: FSF
7 ;; Created: 25 Feb 1994
8 ;; Keywords: lisp
10 ;; This file is part of GNU Emacs.
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 3 of the License, or
15 ;; (at your option) any later version.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Provides a nice interface to evaluating Emacs Lisp expressions.
28 ;; Input is handled by the comint package, and output is passed
29 ;; through the pretty-printer.
31 ;; To start: M-x ielm. Type C-h m in the *ielm* buffer for more info.
33 ;;; Code:
35 (require 'comint)
36 (require 'pp)
38 ;;; User variables
40 (defgroup ielm nil
41 "Interaction mode for Emacs Lisp."
42 :group 'lisp)
45 (defcustom ielm-noisy t
46 "If non-nil, IELM will beep on error."
47 :type 'boolean
48 :group 'ielm)
50 (defcustom ielm-prompt-read-only t
51 "If non-nil, the IELM prompt is read only.
52 The read only region includes the newline before the prompt.
53 Setting this variable does not affect existing IELM runs.
54 This works by setting the buffer-local value of `comint-prompt-read-only'.
55 Setting that value directly affects new prompts in the current buffer.
57 If this option is enabled, then the safe way to temporarily
58 override the read-only-ness of IELM prompts is to call
59 `comint-kill-whole-line' or `comint-kill-region' with no
60 narrowing in effect. This way you will be certain that none of
61 the remaining prompts will be accidentally messed up. You may
62 wish to put something like the following in your init file:
64 \(add-hook 'ielm-mode-hook
65 (lambda ()
66 (define-key ielm-map \"\\C-w\" 'comint-kill-region)
67 (define-key ielm-map [C-S-backspace]
68 'comint-kill-whole-line)))
70 If you set `comint-prompt-read-only' to t, you might wish to use
71 `comint-mode-hook' and `comint-mode-map' instead of
72 `ielm-mode-hook' and `ielm-map'. That will affect all comint
73 buffers, including IELM buffers. If you sometimes use IELM on
74 text-only terminals or with `emacs -nw', you might wish to use
75 another binding for `comint-kill-whole-line'."
76 :type 'boolean
77 :group 'ielm
78 :version "22.1")
80 (defcustom ielm-prompt "ELISP> "
81 "Prompt used in IELM.
82 Setting this variable does not affect existing IELM runs.
84 Interrupting the IELM process with \\<ielm-map>\\[comint-interrupt-subjob],
85 and then restarting it using \\[ielm], makes the then current
86 default value affect _new_ prompts. Unless the new prompt
87 differs only in text properties from the old one, IELM will no
88 longer recognize the old prompts. However, executing \\[ielm]
89 does not update the prompt of an *ielm* buffer with a running process.
90 For IELM buffers that are not called `*ielm*', you can execute
91 \\[inferior-emacs-lisp-mode] in that IELM buffer to update the value,
92 for new prompts. This works even if the buffer has a running process."
93 :type 'string
94 :group 'ielm)
96 (defvar ielm-prompt-internal "ELISP> "
97 "Stored value of `ielm-prompt' in the current IELM buffer.
98 This is an internal variable used by IELM. Its purpose is to
99 prevent a running IELM process from being messed up when the user
100 customizes `ielm-prompt'.")
102 (defcustom ielm-dynamic-return t
103 "Controls whether \\<ielm-map>\\[ielm-return] has intelligent behavior in IELM.
104 If non-nil, \\[ielm-return] evaluates input for complete sexps, or inserts a newline
105 and indents for incomplete sexps. If nil, always inserts newlines."
106 :type 'boolean
107 :group 'ielm)
109 (defcustom ielm-dynamic-multiline-inputs t
110 "Force multiline inputs to start from column zero?
111 If non-nil, after entering the first line of an incomplete sexp, a newline
112 will be inserted after the prompt, moving the input to the next line.
113 This gives more frame width for large indented sexps, and allows functions
114 such as `edebug-defun' to work with such inputs."
115 :type 'boolean
116 :group 'ielm)
118 (defcustom ielm-mode-hook nil
119 "Hooks to be run when IELM (`inferior-emacs-lisp-mode') is started."
120 :options '(turn-on-eldoc-mode)
121 :type 'hook
122 :group 'ielm)
123 (defvaralias 'inferior-emacs-lisp-mode-hook 'ielm-mode-hook)
125 (defvar * nil
126 "Most recent value evaluated in IELM.")
128 (defvar ** nil
129 "Second-most-recent value evaluated in IELM.")
131 (defvar *** nil
132 "Third-most-recent value evaluated in IELM.")
134 (defvar ielm-match-data nil
135 "Match data saved at the end of last command.")
137 (defvar *1 nil
138 "During IELM evaluation, most recent value evaluated in IELM.
139 Normally identical to `*'. However, if the working buffer is an IELM
140 buffer, distinct from the process buffer, then `*' gives the value in
141 the working buffer, `*1' the value in the process buffer.
142 The intended value is only accessible during IELM evaluation.")
144 (defvar *2 nil
145 "During IELM evaluation, second-most-recent value evaluated in IELM.
146 Normally identical to `**'. However, if the working buffer is an IELM
147 buffer, distinct from the process buffer, then `**' gives the value in
148 the working buffer, `*2' the value in the process buffer.
149 The intended value is only accessible during IELM evaluation.")
151 (defvar *3 nil
152 "During IELM evaluation, third-most-recent value evaluated in IELM.
153 Normally identical to `***'. However, if the working buffer is an IELM
154 buffer, distinct from the process buffer, then `***' gives the value in
155 the working buffer, `*3' the value in the process buffer.
156 The intended value is only accessible during IELM evaluation.")
158 ;;; System variables
160 (defvar ielm-working-buffer nil
161 "Buffer in which IELM sexps will be evaluated.
162 This variable is buffer-local.")
164 (defvar ielm-header
165 "*** Welcome to IELM *** Type (describe-mode) for help.\n"
166 "Message to display when IELM is started.")
168 (defvar ielm-map
169 (let ((map (make-sparse-keymap)))
170 (define-key map "\t" 'completion-at-point)
171 (define-key map "\C-m" 'ielm-return)
172 (define-key map "\C-j" 'ielm-send-input)
173 (define-key map "\e\C-x" 'eval-defun) ; for consistency with
174 (define-key map "\e\t" 'completion-at-point) ; lisp-interaction-mode
175 ;; These bindings are from `lisp-mode-shared-map' -- can you inherit
176 ;; from more than one keymap??
177 (define-key map "\e\C-q" 'indent-sexp)
178 (define-key map "\177" 'backward-delete-char-untabify)
179 ;; Some convenience bindings for setting the working buffer
180 (define-key map "\C-c\C-b" 'ielm-change-working-buffer)
181 (define-key map "\C-c\C-f" 'ielm-display-working-buffer)
182 (define-key map "\C-c\C-v" 'ielm-print-working-buffer)
183 map)
184 "Keymap for IELM mode.")
185 (defvaralias 'inferior-emacs-lisp-mode-map 'ielm-map)
187 (easy-menu-define ielm-menu ielm-map
188 "IELM mode menu."
189 '("IELM"
190 ["Change Working Buffer" ielm-change-working-buffer t]
191 ["Display Working Buffer" ielm-display-working-buffer t]
192 ["Print Working Buffer" ielm-print-working-buffer t]))
194 (defvar ielm-font-lock-keywords
195 '(("\\(^\\*\\*\\*[^*]+\\*\\*\\*\\)\\(.*$\\)"
196 (1 font-lock-comment-face)
197 (2 font-lock-constant-face)))
198 "Additional expressions to highlight in IELM buffers.")
200 ;;; Completion stuff
202 (defun ielm-tab nil
203 "Possibly indent the current line as Lisp code."
204 (interactive)
205 (when (or (eq (preceding-char) ?\n)
206 (eq (char-syntax (preceding-char)) ?\s))
207 (ielm-indent-line)
210 (defun ielm-complete-symbol nil
211 "Complete the Lisp symbol before point."
212 ;; A wrapper for completion-at-point that returns non-nil if
213 ;; completion has occurred
214 (let* ((btick (buffer-modified-tick))
215 (cbuffer (get-buffer "*Completions*"))
216 (ctick (and cbuffer (buffer-modified-tick cbuffer)))
217 (completion-at-point-functions '(lisp-completion-at-point)))
218 (completion-at-point)
219 ;; completion has occurred if:
221 ;; the buffer has been modified
222 (not (= btick (buffer-modified-tick)))
223 ;; a completions buffer has been modified or created
224 (if cbuffer
225 (not (= ctick (buffer-modified-tick cbuffer)))
226 (get-buffer "*Completions*")))))
228 (defun ielm-complete-filename nil
229 "Dynamically complete filename before point, if in a string."
230 (when (nth 3 (parse-partial-sexp comint-last-input-start (point)))
231 (comint-dynamic-complete-filename)))
233 (defun ielm-indent-line nil
234 "Indent the current line as Lisp code if it is not a prompt line."
235 (when (save-excursion (comint-bol) (bolp))
236 (lisp-indent-line)))
238 ;;; Working buffer manipulation
240 (defun ielm-print-working-buffer nil
241 "Print the current IELM working buffer's name in the echo area."
242 (interactive)
243 (message "The current working buffer is: %s" (buffer-name ielm-working-buffer)))
245 (defun ielm-display-working-buffer nil
246 "Display the current IELM working buffer.
247 Don't forget that selecting that buffer will change its value of `point'
248 to its value of `window-point'!"
249 (interactive)
250 (display-buffer ielm-working-buffer)
251 (ielm-print-working-buffer))
253 (defun ielm-change-working-buffer (buf)
254 "Change the current IELM working buffer to BUF.
255 This is the buffer in which all sexps entered at the IELM prompt are
256 evaluated. You can achieve the same effect with a call to
257 `set-buffer' at the IELM prompt."
258 (interactive "bSet working buffer to: ")
259 (let ((buffer (get-buffer buf)))
260 (if (and buffer (buffer-live-p buffer))
261 (setq ielm-working-buffer buffer)
262 (error "No such buffer: %S" buf)))
263 (ielm-print-working-buffer))
265 ;;; Other bindings
267 (defun ielm-return nil
268 "Newline and indent, or evaluate the sexp before the prompt.
269 Complete sexps are evaluated; for incomplete sexps inserts a newline
270 and indents. If however `ielm-dynamic-return' is nil, this always
271 simply inserts a newline."
272 (interactive)
273 (if ielm-dynamic-return
274 (let ((state
275 (save-excursion
276 (end-of-line)
277 (parse-partial-sexp (ielm-pm)
278 (point)))))
279 (if (and (< (car state) 1) (not (nth 3 state)))
280 (ielm-send-input)
281 (when (and ielm-dynamic-multiline-inputs
282 (save-excursion
283 (beginning-of-line)
284 (looking-at-p comint-prompt-regexp)))
285 (save-excursion
286 (goto-char (ielm-pm))
287 (newline 1)))
288 (newline-and-indent)))
289 (newline)))
291 (defvar ielm-input)
293 (defun ielm-input-sender (_proc input)
294 ;; Just sets the variable ielm-input, which is in the scope of
295 ;; `ielm-send-input's call.
296 (setq ielm-input input))
298 (defun ielm-send-input nil
299 "Evaluate the Emacs Lisp expression after the prompt."
300 (interactive)
301 (let (ielm-input) ; set by ielm-input-sender
302 (comint-send-input) ; update history, markers etc.
303 (ielm-eval-input ielm-input)))
305 ;;; Utility functions
307 (defun ielm-is-whitespace-or-comment (string)
308 "Return non-nil if STRING is all whitespace or a comment."
309 (or (string= string "")
310 (string-match-p "\\`[ \t\n]*\\(?:;.*\\)*\\'" string)))
312 ;;; Evaluation
314 (defvar ielm-string)
315 (defvar ielm-form)
316 (defvar ielm-pos)
317 (defvar ielm-result)
318 (defvar ielm-error-type)
319 (defvar ielm-output)
320 (defvar ielm-wbuf)
321 (defvar ielm-pmark)
323 (defun ielm-eval-input (input-string)
324 "Evaluate the Lisp expression INPUT-STRING, and pretty-print the result."
325 ;; This is the function that actually `sends' the input to the
326 ;; `inferior Lisp process'. All comint-send-input does is works out
327 ;; what that input is. What this function does is evaluates that
328 ;; input and produces `output' which gets inserted into the buffer,
329 ;; along with a new prompt. A better way of doing this might have
330 ;; been to actually send the output to the `cat' process, and write
331 ;; this as in output filter that converted sexps in the output
332 ;; stream to their evaluated value. But that would have involved
333 ;; more process coordination than I was happy to deal with.
335 ;; NOTE: all temporary variables in this function will be in scope
336 ;; during the eval, and so need to have non-clashing names.
337 (let ((ielm-string input-string) ; input expression, as a string
338 ielm-form ; form to evaluate
339 ielm-pos ; End posn of parse in string
340 ielm-result ; Result, or error message
341 ielm-error-type ; string, nil if no error
342 (ielm-output "") ; result to display
343 (ielm-wbuf ielm-working-buffer) ; current buffer after evaluation
344 (ielm-pmark (ielm-pm)))
345 (unless (ielm-is-whitespace-or-comment ielm-string)
346 (condition-case err
347 (let ((rout (read-from-string ielm-string)))
348 (setq ielm-form (car rout)
349 ielm-pos (cdr rout)))
350 (error (setq ielm-result (error-message-string err))
351 (setq ielm-error-type "Read error")))
352 (unless ielm-error-type
353 ;; Make sure working buffer has not been killed
354 (if (not (buffer-name ielm-working-buffer))
355 (setq ielm-result "Working buffer has been killed"
356 ielm-error-type "IELM Error"
357 ielm-wbuf (current-buffer))
358 (if (ielm-is-whitespace-or-comment (substring ielm-string ielm-pos))
359 ;; To correctly handle the ielm-local variables *,
360 ;; ** and ***, we need a temporary buffer to be
361 ;; current at entry to the inner of the next two let
362 ;; forms. We need another temporary buffer to exit
363 ;; that same let. To avoid problems, neither of
364 ;; these buffers should be alive during the
365 ;; evaluation of ielm-form.
366 (let ((*1 *)
367 (*2 **)
368 (*3 ***)
369 ielm-temp-buffer)
370 (set-match-data ielm-match-data)
371 (save-excursion
372 (with-temp-buffer
373 (condition-case err
374 (unwind-protect
375 ;; The next let form creates default
376 ;; bindings for *, ** and ***. But
377 ;; these default bindings are
378 ;; identical to the ielm-local
379 ;; bindings. Hence, during the
380 ;; evaluation of ielm-form, the
381 ;; ielm-local values are going to be
382 ;; used in all buffers except for
383 ;; other ielm buffers, which override
384 ;; them. Normally, the variables *1,
385 ;; *2 and *3 also have default
386 ;; bindings, which are not overridden.
387 (let ((* *1)
388 (** *2)
389 (*** *3))
390 (kill-buffer (current-buffer))
391 (set-buffer ielm-wbuf)
392 (setq ielm-result
393 (eval ielm-form lexical-binding))
394 (setq ielm-wbuf (current-buffer))
395 (setq
396 ielm-temp-buffer
397 (generate-new-buffer " *ielm-temp*"))
398 (set-buffer ielm-temp-buffer))
399 (when ielm-temp-buffer
400 (kill-buffer ielm-temp-buffer)))
401 (error (setq ielm-result (error-message-string err))
402 (setq ielm-error-type "Eval error"))
403 (quit (setq ielm-result "Quit during evaluation")
404 (setq ielm-error-type "Eval error")))))
405 (setq ielm-match-data (match-data)))
406 (setq ielm-error-type "IELM error")
407 (setq ielm-result "More than one sexp in input"))))
409 ;; If the eval changed the current buffer, mention it here
410 (unless (eq ielm-wbuf ielm-working-buffer)
411 (message "current buffer is now: %s" ielm-wbuf)
412 (setq ielm-working-buffer ielm-wbuf))
414 (goto-char ielm-pmark)
415 (unless ielm-error-type
416 (condition-case nil
417 ;; Self-referential objects cause loops in the printer, so
418 ;; trap quits here. May as well do errors, too
419 (setq ielm-output (concat ielm-output (pp-to-string ielm-result)))
420 (error (setq ielm-error-type "IELM Error")
421 (setq ielm-result "Error during pretty-printing (bug in pp)"))
422 (quit (setq ielm-error-type "IELM Error")
423 (setq ielm-result "Quit during pretty-printing"))))
424 (if ielm-error-type
425 (progn
426 (when ielm-noisy (ding))
427 (setq ielm-output (concat ielm-output "*** " ielm-error-type " *** "))
428 (setq ielm-output (concat ielm-output ielm-result)))
429 ;; There was no error, so shift the *** values
430 (setq *** **)
431 (setq ** *)
432 (setq * ielm-result))
433 (setq ielm-output (concat ielm-output "\n")))
434 (setq ielm-output (concat ielm-output ielm-prompt-internal))
435 (comint-output-filter (ielm-process) ielm-output)))
437 ;;; Process and marker utilities
439 (defun ielm-process nil
440 ;; Return the current buffer's process.
441 (get-buffer-process (current-buffer)))
443 (defun ielm-pm nil
444 ;; Return the process mark of the current buffer.
445 (process-mark (get-buffer-process (current-buffer))))
447 (defun ielm-set-pm (pos)
448 ;; Set the process mark in the current buffer to POS.
449 (set-marker (process-mark (get-buffer-process (current-buffer))) pos))
451 ;;; Major mode
453 (define-derived-mode inferior-emacs-lisp-mode comint-mode "IELM"
454 "Major mode for interactively evaluating Emacs Lisp expressions.
455 Uses the interface provided by `comint-mode' (which see).
457 * \\<ielm-map>\\[ielm-send-input] evaluates the sexp following the prompt. There must be at most
458 one top level sexp per prompt.
460 * \\[ielm-return] inserts a newline and indents, or evaluates a
461 complete expression (but see variable `ielm-dynamic-return').
462 Inputs longer than one line are moved to the line following the
463 prompt (but see variable `ielm-dynamic-multiline-inputs').
465 * \\[completion-at-point] completes Lisp symbols (or filenames, within strings),
466 or indents the line if there is nothing to complete.
468 The current working buffer may be changed (with a call to `set-buffer',
469 or with \\[ielm-change-working-buffer]), and its value is preserved between successive
470 evaluations. In this way, expressions may be evaluated in a different
471 buffer than the *ielm* buffer. By default, its name is shown on the
472 mode line; you can always display it with \\[ielm-print-working-buffer], or the buffer itself
473 with \\[ielm-display-working-buffer].
475 During evaluations, the values of the variables `*', `**', and `***'
476 are the results of the previous, second previous and third previous
477 evaluations respectively. If the working buffer is another IELM
478 buffer, then the values in the working buffer are used. The variables
479 `*1', `*2' and `*3', yield the process buffer values.
481 Expressions evaluated by IELM are not subject to `debug-on-quit' or
482 `debug-on-error'.
484 The behavior of IELM may be customized with the following variables:
485 * To stop beeping on error, set `ielm-noisy' to nil.
486 * If you don't like the prompt, you can change it by setting `ielm-prompt'.
487 * If you do not like that the prompt is (by default) read-only, set
488 `ielm-prompt-read-only' to nil.
489 * Set `ielm-dynamic-return' to nil for bindings like `lisp-interaction-mode'.
490 * Entry to this mode runs `comint-mode-hook' and `ielm-mode-hook'
491 (in that order).
493 Customized bindings may be defined in `ielm-map', which currently contains:
494 \\{ielm-map}"
495 :syntax-table emacs-lisp-mode-syntax-table
497 (setq comint-prompt-regexp (concat "^" (regexp-quote ielm-prompt)))
498 (set (make-local-variable 'paragraph-separate) "\\'")
499 (set (make-local-variable 'paragraph-start) comint-prompt-regexp)
500 (setq comint-input-sender 'ielm-input-sender)
501 (setq comint-process-echoes nil)
502 (set (make-local-variable 'completion-at-point-functions)
503 '(ielm-tab comint-replace-by-expanded-history
504 ielm-complete-filename ielm-complete-symbol))
505 (set (make-local-variable 'ielm-prompt-internal) ielm-prompt)
506 (set (make-local-variable 'comint-prompt-read-only) ielm-prompt-read-only)
507 (setq comint-get-old-input 'ielm-get-old-input)
508 (set (make-local-variable 'comint-completion-addsuffix) '("/" . ""))
509 (setq mode-line-process '(":%s on " (:eval (buffer-name ielm-working-buffer))))
510 ;; Useful for `hs-minor-mode'.
511 (setq-local comment-start ";")
512 (setq-local comment-use-global-state t)
514 (set (make-local-variable 'indent-line-function) 'ielm-indent-line)
515 (set (make-local-variable 'ielm-working-buffer) (current-buffer))
516 (set (make-local-variable 'fill-paragraph-function) 'lisp-fill-paragraph)
518 ;; Value holders
519 (set (make-local-variable '*) nil)
520 (set (make-local-variable '**) nil)
521 (set (make-local-variable '***) nil)
522 (set (make-local-variable 'ielm-match-data) nil)
524 ;; font-lock support
525 (set (make-local-variable 'font-lock-defaults)
526 '(ielm-font-lock-keywords nil nil ((?: . "w") (?- . "w") (?* . "w"))))
528 ;; A dummy process to keep comint happy. It will never get any input
529 (unless (comint-check-proc (current-buffer))
530 ;; Was cat, but on non-Unix platforms that might not exist, so
531 ;; use hexl instead, which is part of the Emacs distribution.
532 (condition-case nil
533 (start-process "ielm" (current-buffer) "hexl")
534 (file-error (start-process "ielm" (current-buffer) "cat")))
535 (set-process-query-on-exit-flag (ielm-process) nil)
536 (goto-char (point-max))
538 ;; Lisp output can include raw characters that confuse comint's
539 ;; carriage control code.
540 (set (make-local-variable 'comint-inhibit-carriage-motion) t)
542 ;; Add a silly header
543 (insert ielm-header)
544 (ielm-set-pm (point-max))
545 (unless comint-use-prompt-regexp
546 (let ((inhibit-read-only t))
547 (add-text-properties
548 (point-min) (point-max)
549 '(rear-nonsticky t field output inhibit-line-move-field-capture t))))
550 (comint-output-filter (ielm-process) ielm-prompt-internal)
551 (set-marker comint-last-input-start (ielm-pm))
552 (set-process-filter (get-buffer-process (current-buffer)) 'comint-output-filter)))
554 (defun ielm-get-old-input nil
555 ;; Return the previous input surrounding point
556 (save-excursion
557 (beginning-of-line)
558 (unless (looking-at-p comint-prompt-regexp)
559 (re-search-backward comint-prompt-regexp))
560 (comint-skip-prompt)
561 (buffer-substring (point) (progn (forward-sexp 1) (point)))))
563 ;;; User command
565 ;;;###autoload
566 (defun ielm nil
567 "Interactively evaluate Emacs Lisp expressions.
568 Switches to the buffer `*ielm*', or creates it if it does not exist."
569 (interactive)
570 (let (old-point)
571 (unless (comint-check-proc "*ielm*")
572 (with-current-buffer (get-buffer-create "*ielm*")
573 (unless (zerop (buffer-size)) (setq old-point (point)))
574 (inferior-emacs-lisp-mode)))
575 (switch-to-buffer "*ielm*")
576 (when old-point (push-mark old-point))))
578 (provide 'ielm)
580 ;;; ielm.el ends here