原文地址:http://blog.csdn.net/csfreebird/article/details/7465978
自己开发或者修改emacs的扩展模块就需要掌握ELisp,而且Lisp既然是人工智能语言,学会它会让自己的思维上一个层次。有这么多好处,还等什么呢?立刻行动起来吧。
执行最后一个S表达式
从最简单的如何在Emacs上执行加法开始:
输入M-x:shell进入shell终端,然后输入
(+ 2 3)
将光标放在最后一个括号后面,按下C-x C-e ,可以看到Mini-buffer上面显示结果5。函数实际上是这个
M-x:
eval-last-sexp
如果有多个元素的话,写法可以换行,写成如下形式:
'(rose
violet
daisy
buttercup)
注意前面的' 符号是告诉Emacs不要执行这个list,仅仅是原样输出'符号后面的list,因此C-x C-e的结果就是
(rose
violet
daisy
buttercup)
运行buffer中所有的lisp
eval-buffer函数
可以通过M-x运行无参的eval-buffer函数,但是很遗憾,什么也不显示,因为这个函数的可选参数如果不设置,就不会输出任何东西。
所以可以这么改
运行指定buffer的lisp,输出到指定buffer
在*shell*中用C-x C-e执行这个语句
(eval-buffer "add.el" (get-buffer-create "output"))
add.el是一个buffer,里面包含了代码:
(defun add2 (x)
(+ 2 x))
(print (add2 8))
c-h f查看eval-buffer函数, 可以看到,这里PRINTFLAG我们传递是期望输出到的buffer名称,当然这个output buffer是创建的。
eval-buffer is an interactive built-in function in `C source code'.
(eval-buffer &optional BUFFER PRINTFLAG FILENAME UNIBYTE
DO-ALLOW-PRINT)
Execute the current buffer as Lisp code.
When called from a Lisp program (i.e., not interactively), this
function accepts up to five optional arguments:
BUFFER is the buffer to evaluate (nil means use current buffer).
PRINTFLAG controls printing of output:
A value of nil means discard it; anything else is stream for print.
FILENAME specifies the file name to use for `load-history'.
UNIBYTE, if non-nil, specifies `load-convert-to-unibyte' for this
invocation.
DO-ALLOW-PRINT, if non-nil, specifies that `print' and related
functions should work normally even if PRINTFLAG is nil.
This function preserves the position of point.
[back] [forward]
运行当前buffer的lisp代码,并输出到output buffer
上面的方式还是用起来不方面,在init.el中添加一个函数eval-buffer2,就可以执行当前buffer的elisp,并输出到output buffer中
;; elisp
(defun eval-buffer2 ()
(interactive)
(eval-buffer nil (get-buffer-create "output")))
运行el文件
如何像执行shell脚本一样运行el文件呢?
这是一个很实用的功能,实际上也是我的一个主要目的,这么强大的语言,用好了,比shell脚本方便多了,而且性能也搞。甚至可以代替Java编写程序。
现在我的test.el文件内容如下:
(defun add2 (x)
(+ 2 x))
(print (add2 8))
然后执行下面的命令:
emacs --no-site-file --script /home/chenshu/test.el
结果显示10
注意上面的命令在服务器上运行没有问题,
在Ubuntu Desktop上需要安装并使用emacs24-nox
apt-get install emacs24-nox