I was watching another of Tim Visher's VimGolf videos in which he builds a multiplication table by the clever use of keyboard macros. What got my attention, however, was his use of the function
eval-and-replace that evaluates the sexp preceding the point and replaces it with its value. This seemed like a useful thing to be able to do but as Visher explained,
eval-and-replace is part of the Emacs Starter Kit and not part of Emacs itself.
I have a fairly large
init.el that I've developed over time and therefore never installed the starter kit even though I've heard good things about it. Rather than hunt up the starter kit to get the function, I just rolled my own:
(defun eval-and-replace (value) "Evaluate the sexp at point and replace it with its value" (interactive (list (eval-last-sexp nil))) (kill-sexp -1) (insert (format "%S" value)))
eval-last-sexp in the
interactive declaration evaluates the sexp and passes its value to
eval-and-replace. Then the
(kill-sexp -1) deletes the sexp from the buffer. Finally the value is inserted into the buffer with the
I originally wrote the function using a
let to capture the value of the sexp instead of using the
interactive declaration but this seemed a bit shorter and I wanted to use an expression in the
interactive declaration, as I wrote about here, to fix the idea in my mind.
I can see all sorts of uses for
eval-and-replace. As a trivial example, suppose I want to say 223=8388608 but I don't remember the value of 223. I could switch over to my calculator buffer to make the calculation and then cut and paste it to my text or I can just write
2^23=(expt 2 23)
eval-and-replace to put the value in the text for me.
eval-and-replace to my
init.el so that I'll have it available the next time I have a need for it.