First, in case you weren't aware, there's eval-print-last-sexp
, bound to C-j
in lisp-interaction-mode
(for instance in the *scratch*
buffer), which will print the result after the sexp (instead of displaying it in the echo area, like eval-last-sexp
, but without deleting the sexp, like you want).
The following function should also delete the sexp, giving the desired effect of replacing the sexp with its desired value.
(defun eval-replace-last-sexp ()
"Evaluate sexp before point; replace sexp with value.
The point will be at the end of the inserted value. The replaced
sexp will be added to the kill-ring. If the latter is not
desired, use `delete-region' instead of `kill-region', below."
(interactive)
(let ((beg (progn
(backward-sexp)
(point)))
(end (progn
(forward-sexp)
(point))))
;; the argument of t means that result is printed into the buffer,
;; as we want
(eval-last-sexp t)
(kill-region beg end)))
Now you can call the function directly with M-x eval-replace-last-sexp
or by binding it to a convenient keyboard short-cut.