For some time, I found Common Lisp’s pretty printer to be
intimidating, obscure, and complex, and, for as long as I’ve been
comfortable with the basics of FORMAT
I felt able to ignore it, as
irrelevant to my interests.
However, I often find it convenient to arrange lisp data in aligned columns. For small tables, this isn’t so bad, but I end up doing it a lot and it would be nice to figure out how to make the lisp printer do that for me, and so I’ve recently found myself digging into the lisp pretty printer.
Here’s what I’ve learned.
As usual, the first place to look for information on this subject is
the Common Lisp Hyperspec. If you’ve been programming in Common Lisp
for almost any length of time, you’ve probably already got bookmarks
to sections in the Hyperspec like, http://l1sp.org/cl/22.3 on
“Formatted Output” and perhaps deeper links in there, like to the
subsection on “Control Flow”. If you’re like me you also regularly
browse through “The Printer Dictionary” at http://l1sp.org/cl/22.4
where you refresh yourself in *print-readably*
verses
*print-escape*
, and/or the options on the print-unreadable-object
method.
To acquaint yourself with the pretty-printer options you’ll want to keep these handy:
- 22.2.1 Pretty Printer Concepts
- 22.2.2 Examples of using the Pretty Printer
- Macro =PPRINT-LOGICAL-BLOCK=
- 22.3.5
FORMAT
Pretty Printer Operations
of course:
also:
Looking at it from one the upper links you might first think that 22.3.5.1 Tilde Underscore: Conditional Newline would be handy, and it kind of is. It would be nice if it had a link though, like this:
Without any modifiers,
~_
is the same as([[http://l1sp.org/cl/pprint-newline][pprint-newline]] :linear)
.~@_
is the same as(pprint-newline :miser)
.~:_
is the same as(pprint-newline :fill)
.~:@_
is the same as(pprint-newline :mandatory)
.
The pretty-printer is used for printing lisp forms in a standard
fashion. There are pretty printing functions for printing LET
forms,
DEFUN
and DEFMACRO
, as well as lisp standard data objects. One
reason you might want to use it is to pretty-print a lisp form of a
custom object you’ve been working on, which can be expressed in a lisp
form. You use it by printing anything with *PRINT-PRETTY*
set to
T
, typically with PPRINT
or perhaps with (WRITE foo :PRETTY T)
.
There’s two ways of working with a custom pretty print settings. One
way is to use PPRINT-LOGICAL-BLOCK
and attendant functions,
PPRINT-NEWLINE
, PPRINT-INDENT
, etc. The other way is to use the
much more compact FORMAT
control string ~<...~:>
. Since they
inform each other, we’re go over both.
One note, you might recognize the control string the format control used for text justification described in 22.3.6.2 Tilde Less-Than-Sign: Justification. To this I can only say, “good eye”, because that it is.
(format t "~:@<~:{~
~:@<~A~12T~A~:>~:^~:@_~
~}~:>"
'((foo bar)
(baz qux)))