justinhj
justinhj

Reputation: 11316

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

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

Upvotes: 26

Views: 5761

Answers (7)

Sean
Sean

Reputation: 29800

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))))

Upvotes: 43

perfectayush
perfectayush

Reputation: 21

If you are using emacs starter kit by technomancy there is "esk-eval-and-replace" function which evaluates the elisp sexp and replace them. Its bind to C-c e by default.

Upvotes: 2

phils
phils

Reputation: 73410

replace-regex functions can execute lisp to generate the replacements.

In the trivial instance where the sexp in question is on a single line, and is the only thing containing parenthesis, then you could match "(.+)" and replace with "\,(eval (read \&))".

Upvotes: 3

sanityinc
sanityinc

Reputation: 15242

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.

Upvotes: 9

kjfletch
kjfletch

Reputation: 5494

I was having a go at a solution for this when I came across one in a Google search result.

(defun fc-eval-and-replace ()
  "Replace the preceding sexp with its value."
  (interactive)
  (backward-kill-sexp)
  (prin1 (eval (read (current-kill 0)))
         (current-buffer)))

http://emacs.wordpress.com/2007/01/17/eval-and-replace-anywhere/

Upvotes: 8

Craig Citro
Craig Citro

Reputation: 6635

My emacs-fu isn't so strong, so I don't know if there's a single command to do this, but you can make yourself a (somewhat fragile) macro for it ... drop these lines in your .emacs:

(fset 'eval-sexp-in-place
      [?\M-x ?e ?v ?a ?l ?- ?p ?r ?i ?n tab return ?\M-^ ?\M-^ ?\C-\M-b ?\C-\M-k ?\C-d])
(global-set-key [(control x) (control a)] 'eval-sexp-in-place)

This works fine, but there's one issue with it: you need to be at the end of the sexp (i.e. after the last right paren) to get it to work.

Also, I picked a random unbound key (C-x C-a) -- feel free to change that to something more to your liking.

Upvotes: 0

Alex Ott
Alex Ott

Reputation: 87369

look to the function eval-print-last-sexp, you can build something using it

Upvotes: 1

Related Questions