Mickey from Mastering Emacs has an excellent post on the various ways of evaluating Elisp in Emacs. As Mickey says, there are several ways of doing it depending on the context and it pays to be familiar with them all.
The most familiar way is probably eval-last-sexp
(Ctrl+x Ctrl+e). It’s really useful because it will evaluate almost anything: s-expressions (of course) but also numbers, strings, and most special forms. The situation for special forms has improved a bit in Emacs 28 so be sure to take a look at Mickey’s post to get the details.
There’s also eval-buffer
and eval-region
, which do as their names suggest. These commands generally don’t evaluate special forms such as devar
, defface
, and defcustom
. That’s generally what you want so it’s a feature instead of a bug. Again, see the post for the details.
The method that I always tend to forget about is eval-defun
, bound to Ctrl+Meta+x. It’s especially handy for evaluating functions because, unlike eval-last-sexp
, you can call it from anywhere within the function instead of needing to be at the end. If you call it with the universal argument, it will turn on debugging for the function. It’s worth reading Mickey’s article just for the section on this command.
Finally, there’s Eshell and IELM. Most Eshell users know you can evaluate many Elisp expressions there but when you want a real Elisp REPL, IELM is what you want. It’s perfect for experimenting with code that’s longer than a single expression. I use it fairly often and love it.
Like all of Mickey’s posts, this one is definitely worth your time and effort.