Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Emacs can you evaluate an Emacs Lisp expression and replace it with the result?

Tags:

For example if I have the text:

Sum of items is (+ 1 2 3) 

I want to move to the end of the line, evaluate the expression and replace it with the result, so that it reads:

Sum of items is 6 
like image 749
justinhj Avatar asked Jun 14 '10 06:06

justinhj


People also ask

How do you evaluate a Lisp in emacs?

Typing C-x C-e in any buffer evaluates the Lisp form immediately before point and prints its value in the echo area. Typing M-: or M-x eval-expression allows you to type a Lisp form in the minibuffer which will be evaluated once you press RET.

How do you evaluate a Lisp expression?

The most general command for evaluating Lisp expressions from a buffer is eval-region. M-x eval-region parses the text of the region as one or more Lisp expressions, evaluating them one by one. M-x eval-current-buffer is similar but evaluates the entire buffer.

What is Emacs Lisp used for?

Emacs Lisp is a dialect of the Lisp programming language used as a scripting language by Emacs (a text editor family most commonly associated with GNU Emacs and XEmacs). It is used for implementing most of the editing functionality built into Emacs, the remainder being written in C, as is the Lisp interpreter.

Is Emacs functional Lisp?

Emacs Lisp supports multiple programming styles or paradigms, including functional and object-oriented. Emacs Lisp is not a purely functional programming language since side effects are common. Instead, Emacs Lisp is considered an early functional flavored language.


2 Answers

With the cursor at the end of the line, C-u C-x C-e will insert the value of the preceding parenthesized expression into the buffer. You could do that, then manually back up and delete the original expression. If that's too much work, here's a command that evaluates the preceding expression and replaces it with its value:

  (defun replace-last-sexp ()     (interactive)     (let ((value (eval (preceding-sexp))))       (kill-sexp -1)       (insert (format "%S" value)))) 
like image 182
Sean Avatar answered Oct 28 '22 09:10

Sean


Related to this, you might like Luke Gorrie's "lively.el", which provides live replacement of emacs lisp expressions within a text buffer. It's a neat hack.

like image 25
sanityinc Avatar answered Oct 28 '22 09:10

sanityinc