如何在Emacs中调用交互式elisp解释器?

时间:2020-03-06 14:50:21  来源:igfitidea点击:

现在,我在" * scratch *"缓冲区中编写表达式,并通过用" C-x"和" C-e"求值来测试它们。我非常感谢拥有像SLIME或者irb这样的交互式解释器,可以在其中解释Emacs Lisp表达式。

解决方案

* scratch *缓冲区中,只需键入C-j即可计算出point之前的表达式。

好吧,如果我们真的对emacs的文字REPL感兴趣,则可以使用emacs的-batch模式编写一个:

(require 'cl)

(defun read-expression ()
  (condition-case
      err
      (read-string "> ")
    (error
     (message "Error reading '%s'" form)
     (message (format "%s" err)))))

(defun read-expression-from-string (str)
  (condition-case
      err
      (read-from-string str)
    (error
     (message "Error parsing '%s'" str)
     (message (format "%s" err))
     nil)))

(defun repl ()
  (loop for expr = (read-string "> ") then (read-expression)
        do
        (let ((form (car (read-expression-from-string expr))))
          (condition-case
              err
              (message " => %s" (eval form))
            (error
             (message "Error evaluating '%s'" form)
             (message (format "%s" err)))))))

(repl)

我们可以从命令行调用此函数,也可以根据需要在运行shell的emacs缓冲区中调用此函数:

kburton@hypothesis:~/projects/elisp$ emacs -batch -l test.el
Loading 00debian-vars...
> (defvar x '(lambda (y) (* y 100)))
 => x
> (funcall x 0.25)
 => 25.0
> 
kburton@hypothesis:~/projects/elisp$

最好的选择是* scratch *缓冲区。我们可以先打开调试器,使其更像REPL:

M-x set-variable debug-on-error t

然后使用" C-j"代替" C-x C-e",这会将对表达式求值的结果插入到表达式后一行的缓冲区中。代替命令历史记录,* * *之类的东西,我们只需在* scratch *缓冲区中移动并进行编辑。

如果我们希望像* * *之类的东西能够正常工作,更像是常规的REPL,请尝试ielm

M-x ielm

在劣等的Emacs-Lisp模式下评估Lisp表达式很容易:

M-x ielm

我们可以在" Lisp交互"的Emacs手册部分中阅读有关此功能的更多信息。

要只运行一个elisp表达式,可以使用M-:快捷方式,然后在mini-buffer中输入表达式。对于其他情况,我们可以使用暂存缓冲区

Eshell是交互式Elisp解释器的另一个选项。

M-x eshell

它不仅是像bash(如果在Windows上为cmd.exe)这样的命令外壳,还可以交互方式编写和执行Elisp代码。

~ $ ls
foo.txt
bar.txt
~ $ (+ 1 1)
2