Basic Formatting

Now you’re ready to look at specific directives. I’ll start with several of the most commonly used directives, including some you’ve seen in previous chapters.

The most general-purpose directive is ~A, which consumes one format argument of any type and outputs it in aesthetic (human-readable) form. For example, strings are output without quotation marks or escape characters, and numbers are output in a natural way for the type of number. If you just want to emit a value for human consumption, this directive is your best bet.

  1. (format nil "The value is: ~a" 10) ==> "The value is: 10"
  2. (format nil "The value is: ~a" "foo") ==> "The value is: foo"
  3. (format nil "The value is: ~a" (list 1 2 3)) ==> "The value is: (1 2 3)"

A closely related directive, ~S, likewise consumes one format argument of any type and outputs it. However, ~S tries to generate output that can be read back in with **READ**. Thus, strings will be enclosed in quotation marks, symbols will be package-qualified when necessary, and so on. Objects that don’t have a **READ**able representation are printed with the unreadable object syntax, #<>. With a colon modifier, both the ~A and ~S directives emit **NIL** as () rather than **NIL**. Both the ~A and ~S directives also take up to four prefix parameters, which can be used to control whether padding is added after (or before with the at-sign modifier) the value, but those parameters are only really useful for generating tabular data.

The other two most frequently used directives are ~%, which emits a newline, and ~&, which emits a fresh line. The difference between the two is that ~% always emits a newline, while ~& emits one only if it’s not already at the beginning of a line. This is handy when writing loosely coupled functions that each generate a piece of output and that need to be combined in different ways. For instance, if one function generates output that ends with a newline (~%) and another function generates some output that starts with a fresh line (~&), you don’t have to worry about getting an extra blank line if you call them one after the other. Both of these directives can take a single prefix parameter that specifies the number of newlines to emit. The ~% directive will simply emit that many newline characters, while the ~& directive will emit either n - 1 or n newlines, depending on whether it starts at the beginning of a line.

Less frequently used is the related ~~ directive, which causes **FORMAT** to emit a literal tilde. Like the ~% and ~& directives, it can be parameterized with a number that controls how many tildes to emit.