2014-10-10 Pretty printing Emacs Lisp code

Typing (E)lisp code in Emacs is great – the editor takes care of proper indentation etc. Sometimes, however, when debugging, you need to print a long and/or deeply nested list. This is the kind of situation when the pretty printer in pp.el comes handy.

There are quite a few functions defined there. C-h f pp- TAB is a good idea to learn about them. I’m going to write about two of them here.

pp-eval-expression takes one parameter: a (quoted) expression, for instance

(pp-eval-expression '(list "hello" "world"))

(If you tried (pp-eval-expression '("hello" "world")), you would obviously get an error, since Emacs would try to evaluate that list, and there is no function whose name would be the string (not symbol!) "hello". However, (pp-eval-expression ''("hello" "world")) works as expected.)

This function puts its output into a special (emacs-lisp-mode) buffer called *Pp Eval Output*, and is useful to get the result of calling some function pretty-printed. In order to display some fixed expression, one can either use the abovementioned double-quote trick, or employ another function from pp.el, namely pp-display-expression. It takes an expression and the name of the output buffer, so e.g. (pp-display-expression '("hello" "world") "tmp") pretty-prints this list in a "tmp" buffer (it gets created when nonexistent).

One caveat: this works all well for “hello world” examples, but for really complicated lists, it might be a good idea to set

(setq eval-expression-print-level nil)
(setq eval-expression-print-length nil)

The default values (4 and 12 respectively) put rather a tight limit on the displayed lists, and instead of nicely formatted content of some complicated data structure, you get annoying ellipsis. With nils as their values, there is no limit, so you get everything.

CategoryEnglish, CategoryBlog, CategoryEmacs