[ eval and replace ] - Thu 16 April 2020

Often when working with Lisp, you want to evaluate expressions. This is easily done in Emacs by leaving the cursor after the expression, and hitting C-x C-e to see the value in the minibuffer.

However, sometimes you want to replace the value of an expression directly with its evaluation. The following function does just that:

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

Now, you want to define a keymap:

(global-set-key (kbd "C-c C-e") 'my-eval-and-replace)

Now if the cursor is on an expression like

(+ 5 5)

and you press C-c C-e at the end, the result will replace the expression:

10