Chris Gregory

Home Blog LinkedIn Github

eval-and-replace for evil mode

5/8/2016

Emacs allows for you to evaluate s-expressions and print them out on the status bar. This is really cool, and many people have made a function that evaluates it in-place. The problem I have with these implementations are that evil mode treats parenthesis as matching when you are on the closing parenthesis, instead of after the closing parenthesis. To get this behavior to work properly I implemented eval-and-replace as follows:

(defun eval-and-replace ()
  "Replace the preceding sexp with its value."
  (interactive)
  (if (and evil-mode (eq (following-char) ?\))) (forward-char 1))
  (let ((value (eval (preceding-sexp))))
    (backward-kill-sexp)
    (insert (format "%s" value))))

Binding this to a key is simple enough:

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

Now if you input (/ 1000 20) then press C-c e, it is replace with 50. Putting your cursor on or after the closing parenthesis in normal mode then pressing C-c e yields the same result.