Search code examples
emacsbufferevals-expression

emacs: Evaluate buffer contents as an s-expression?


Suppose I have an emacs buffer which contains the following text:

'(1 2 3)

I would like to evaluate the contents of this buffer as a lisp exprerssion (an s-expression). If I invoke (eval (buffer-string)), the result simply gets evaluated as the following string:

"'(1 2 3)"

I want the result to be evaluated as a lisp statement. In this example, I want the result to be a 3-element list, not a string.

I haven't figured out how to do this. Any ideas?

Thank you very much.


Solution

  • You can use (eval-buffer) to evaluate the entire buffer. eval-buffer is not the solution to this, because it always returns nil.

    If you want to go through a string, you can use read-from-string. Since that returns both what it parsed and the index where it stopped parsing, as a cons cell, you usually want to call car on its return value:

    (eval (car (read-from-string (buffer-string))))