Nothing Special   »   [go: up one dir, main page]

Programming Language - Common Lisp 22. Printer

Download as ps, pdf, or txt
Download as ps, pdf, or txt
You are on page 1of 41

Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.

Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Programming Language|Common Lisp

22. Printer

Printer i ii Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.1 The Lisp Printer In addition to the printer control variables , the following additional de ned names relate to or
a ect the behavior of the Lisp printer :
22.1.1 Overview of The Lisp Printer *package*
*read-default- oat-format*
*read-eval*
*readtable*
readtable-case
Common Lisp provides a representation of most objects in the form of printed text called the
printed representation. Functions such as print take an object and send the characters of its Figure 22{2. Additional In uences on the Lisp printer.
printed representation to a stream . The collection of routines that does this is known as the
(Common Lisp) printer.
Reading a printed representation typically produces an object that is equal to the originally 22.1.1.1.1 Printer Escaping
printed object . The variable *print-escape* controls whether the Lisp printer tries to produce notations such as
escape characters and package pre xes.
22.1.1.1 Multiple Possible Textual Representations The variable *print-readably* can be used to override many of the individual aspects controlled
Most objects have more than one possible textual representation. For example, the positive by the other printer control variables when program-readable output is especially important.
integer with a magnitude of twenty-seven can be textually expressed in any of these ways:
One of the many e ects of making the value of *print-readably* be true is that the Lisp printer
27 27. #o33 #x1B #b11011 #.(* 3 3 3) 81/3 behaves as if *print-escape* were also true . For notational convenience, we say that if the value
of either *print-readably* or *print-escape* is true , then printer escaping is \enabled"; and
A list containing the two symbols A and B can also be textually expressed in a variety of ways: we say that if the values of both *print-readably* and *print-escape* are false , then printer
(A B) (a b) ( a b ) (\A |B|)
escaping is \disabled".

22.1.2 Printer Dispatching


(|\A|
B
)
The Lisp printer makes its determination of how to print an object as follows:
In general, from the point of view of the Lisp reader , wherever whitespace is permissible in a
textual representation, any number of spaces and newlines can appear in standard syntax . If the value of *print-pretty* is true , printing is controlled by the current pprint dispatch table ;
see Section 22.2.1.4 (Pretty Print Dispatch Tables).
When a function such as print produces a printed representation, it must choose from among
many possible textual representations. In most cases, it chooses a program readable representa- Otherwise (if the value of *print-pretty* is false ), the object's print-object method is used; see
tion, but in certain cases it might use a more compact notation that is not program-readable. Section 22.1.3 (Default Print-Object Methods).
A number of option variables, called printer control variables , are provided to permit control
of individual aspects of the printed representation of objects . Figure 22{1 shows the standardized 22.1.3 Default Print-Object Methods
printer control variables ; there might also be implementation-de ned printer control variables . This section describes the default behavior of print-object methods for the standardized types .
*print-array* *print-gensym* *print-pprint-dispatch*
*print-base* *print-length* *print-pretty* 22.1.3.1 Printing Numbers
*print-case* *print-level* *print-radix*
*print-circle* *print-lines* *print-readably*
*print-escape* *print-miser-width* *print-right-margin*
Figure 22{1. Standardized Printer Control Variables

Printer 22{1 22{2 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.1.3.1.1 Printing Integers 22.1.3.1.4 Printing Complexes


Integers are printed in the radix speci ed by the current output base in positional notation, most A complex is printed as #C, an open parenthesis, the printed representation of its real part, a
signi cant digit rst. If appropriate, a radix speci er can be printed; see *print-radix*. If an space, the printed representation of its imaginary part, and nally a close parenthesis.
integer is negative, a minus sign is printed and then the absolute value of the integer is printed.
The integer zero is represented by the single digit 0 and never has a sign. A decimal point might For related information about the syntax of a complex , see Section 2.3.2.3 (Syntax of a Complex)
be printed, depending on the value of *print-radix*. and Section 2.4.8.11 (Sharpsign C).
For related information about the syntax of an integer , see Section 2.3.2.1.1 (Syntax of an Inte- 22.1.3.1.5 Note about Printing Numbers
ger).
The printed representation of a number must not contain escape characters ; see Section 2.3.1.1.1
22.1.3.1.2 Printing Ratios (Escape Characters and Potential Numbers).
Ratios are printed as follows: the absolute value of the numerator is printed, as for an integer ;
then a /; then the denominator. The numerator and denominator are both printed in the radix 22.1.3.2 Printing Characters
speci ed by the current output base ; they are obtained as if by numerator and denominator, When printer escaping is disabled, a character prints as itself; it is sent directly to the output
and so ratios are printed in reduced form (lowest terms). If appropriate, a radix speci er can be stream . When printer escaping is enabled, then #\ syntax is used.
printed; see *print-radix*. If the ratio is negative, a minus sign is printed before the numerator.
When the printer types out the name of a character , it uses the same table as the #\ reader
For related information about the syntax of a ratio , see Section 2.3.2.1.2 (Syntax of a Ratio). macro would use; therefore any character name that is typed out is acceptable as input (in that
implementation ). If a non-graphic character has a standardized name 5 , that name is preferred
22.1.3.1.3 Printing Floats over non-standard names for printing in #\ notation. For the graphic standard characters , the
character itself is always used for printing in #\ notation|even if the character also has a name 5 .
If the magnitude of the oat is either zero or between 10 3 (inclusive) and 107 (exclusive), it is
printed as the integer part of the number, then a decimal point, followed by the fractional part of For details about the #\ reader macro , see Section 2.4.8.1 (Sharpsign Backslash).
the number; there is always at least one digit on each side of the decimal point. If the sign of the
number (as determined by oat-sign) is negative, then a minus sign is printed before the number.
If the format of the number does not match that speci ed by *read-default- oat-format*, then 22.1.3.3 Printing Symbols
the exponent marker for that format and the digit 0 are also printed. For example, the base of the When printer escaping is disabled, only the characters of the symbol 's name are output (but the
natural logarithms as a short oat might be printed as 2.71828S0. case in which to print characters in the name is controlled by *print-case*; see Section 22.1.3.3.2
(E ect of Readtable Case on the Lisp Printer)).
For non-zero magnitudes outside of the range 10 3 to 107, a oat is printed in computerized
scienti c notation. The representation of the number is scaled to be between 1 (inclusive) and The remainder of this section applies only when printer escaping is enabled.
10 (exclusive) and then printed, with one digit before the decimal point and at least one digit
after the decimal point. Next the exponent marker for the format is printed, except that if the When printing a symbol , the printer inserts enough single escape and/or multiple escape charac-
format of the number matches that speci ed by *read-default- oat-format*, then the exponent ters (backslashes and/or vertical-bars ) so that if read were called with the same *readtable* and
marker E is used. Finally, the power of ten by which the fraction must be multiplied to equal the with *read-base* bound to the current output base , it would return the same symbol (if it is not
original number is printed as a decimal integer. For example, Avogadro's number as a short oat apparently uninterned ) or an uninterned symbol with the same print name (otherwise).
is printed as 6.02S23. For example, if the value of *print-base* were 16 when printing the symbol face, it would have
For related information about the syntax of a oat , see Section 2.3.2.2 (Syntax of a Float). to be printed as \FACE or \Face or |FACE|, because the token face would be read as a hexadecimal
number (decimal value 64206) if the value of *read-base* were 16.
For additional restrictions concerning characters with nonstandard syntax types in the current
readtable , see the variable *print-readably*
For information about how the Lisp reader parses symbols , see Section 2.3.4 (Symbols as Tokens)
and Section 2.4.8.5 (Sharpsign Colon).

Printer 22{3 22{4 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

nil might be printed as () when *print-pretty* is true and printer escaping is enabled. 22.1.3.3.2 E ect of Readtable Case on the Lisp Printer
22.1.3.3.1 Package Pre xes for Symbols When printer escaping is disabled, or the characters under consideration are not already quoted
speci cally by single escape or multiple escape syntax, the readtable case of the current readtable
Package pre xes are printed if necessary. The rules for package pre xes are as follows. When a ects the way the Lisp printer writes symbols in the following ways:
the symbol is printed, if it is in the KEYWORD package , then it is printed with a preceding colon ;
otherwise, if it is accessible in the current package , it is printed without any package pre x ; :upcase
otherwise, it is printed with a package pre x . When the readtable case is :upcase, uppercase characters are printed in the case speci ed
A symbol that is apparently uninterned is printed preceded by \#:" if *print-gensym* is true and by *print-case*, and lowercase characters are printed in their own case.
printer escaping is enabled; if *print-gensym* is false or printer escaping is disabled, then the
symbol is printed without a pre x, as if it were in the current package . :downcase

Because the #: syntax does not intern the following symbol, it is necessary to use circular-list When the readtable case is :downcase, uppercase characters are printed in their own case,
syntax if *print-circle* is true and the same uninterned symbol appears several times in an and lowercase characters are printed in the case speci ed by *print-case*.
expression to be printed. For example, the result of :preserve
(let ((x (make-symbol "FOO"))) (list x x))
When the readtable case is :preserve, all alphabetic characters are printed in their own
would be printed as (#:foo #:foo) if *print-circle* were false , but as (#1=#:foo #1#) if case.
*print-circle* were true .
:invert
A summary of the preceding package pre x rules follows:
When the readtable case is :invert, the case of all alphabetic characters in single case
foo:bar symbol names is inverted. Mixed-case symbol names are printed as is.
foo:bar is printed when symbol bar is external in its home package foo and is not accessi- The rules for escaping alphabetic characters in symbol names are a ected by the readtable-case if
ble in the current package . printer escaping is enabled. Alphabetic characters are escaped as follows:
foo::bar :upcase

foo::bar is printed when bar is internal in its home package foo and is not accessible in When the readtable case is :upcase, all lowercase characters must be escaped.
the current package .
:downcase
:bar
When the readtable case is :downcase, all uppercase characters must be escaped.
:bar is printed when the home package of bar is the KEYWORD package . :preserve
#:bar When the readtable case is :preserve, no alphabetic characters need be escaped.
#:bar is printed when bar is apparently uninterned , even in the pathological case that bar
has no home package but is nevertheless somehow accessible in the current package . :invert

When the readtable case is :invert, no alphabetic characters need be escaped.

Printer 22{5 22{6 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.1.3.3.2.1 Examples of E ect of Readtable Case on the Lisp Printer :PRESERVE :DOWNCASE Zebra Zebra
:PRESERVE :DOWNCASE zebra zebra
:PRESERVE :CAPITALIZE ZEBRA ZEBRA
(defun test-readtable-case-printing () :PRESERVE :CAPITALIZE Zebra Zebra
(let ((*readtable* (copy-readtable nil)) :PRESERVE :CAPITALIZE zebra zebra
(*print-case* *print-case*)) :INVERT :UPCASE ZEBRA zebra
(format t "READTABLE-CASE *PRINT-CASE* Symbol-name Output~ :INVERT :UPCASE Zebra Zebra
~%--------------------------------------------------~ :INVERT :UPCASE zebra ZEBRA
~%") :INVERT :DOWNCASE ZEBRA zebra
(dolist (readtable-case '(:upcase :downcase :preserve :invert)) :INVERT :DOWNCASE Zebra Zebra
(setf (readtable-case *readtable*) readtable-case) :INVERT :DOWNCASE zebra ZEBRA
(dolist (print-case '(:upcase :downcase :capitalize)) :INVERT :CAPITALIZE ZEBRA zebra
(dolist (symbol '(|ZEBRA| |Zebra| |zebra|)) :INVERT :CAPITALIZE Zebra Zebra
(setq *print-case* print-case) :INVERT :CAPITALIZE zebra ZEBRA
(format t "~&:~A~15T:~A~29T~A~42T~A"
(string-upcase readtable-case)
(string-upcase print-case)
22.1.3.4 Printing Strings
(symbol-name symbol)
The characters of the string are output in order. If printer escaping is enabled, a double-quote is
(prin1-to-string symbol)))))))
output before and after, and all double-quotes and single escapes are preceded by backslash . The
The output from (test-readtable-case-printing) should be as follows: printing of strings is not a ected by *print-array*. Only the active elements of the string are
printed.
READTABLE-CASE *PRINT-CASE* Symbol-name Output
-------------------------------------------------- For information on how the Lisp reader parses strings , see Section 2.4.5 (Double-Quote).
:UPCASE :UPCASE ZEBRA ZEBRA
:UPCASE
:UPCASE
:UPCASE
:UPCASE
Zebra
zebra
|Zebra|
|zebra|
22.1.3.5 Printing Lists and Conses
:UPCASE :DOWNCASE ZEBRA zebra Wherever possible, list notation is preferred over dot notation. Therefore the following algorithm
:UPCASE :DOWNCASE Zebra |Zebra| is used to print a cons x:
:UPCASE :DOWNCASE zebra |zebra|
:UPCASE :CAPITALIZE ZEBRA Zebra 1. A left-parenthesis is printed.
:UPCASE :CAPITALIZE Zebra |Zebra|
:UPCASE :CAPITALIZE zebra |zebra|
:DOWNCASE :UPCASE ZEBRA |ZEBRA| 2. The car of x is printed.
:DOWNCASE :UPCASE Zebra |Zebra|
:DOWNCASE :UPCASE zebra ZEBRA
:DOWNCASE :DOWNCASE ZEBRA |ZEBRA| 3. If the cdr of x is itself a cons , it is made to be the current cons (i.e., x becomes that cons ), a
:DOWNCASE :DOWNCASE Zebra |Zebra| space is printed, and step 2 is re-entered.
:DOWNCASE :DOWNCASE zebra zebra
:DOWNCASE :CAPITALIZE ZEBRA |ZEBRA|
:DOWNCASE :CAPITALIZE Zebra |Zebra| 4. If the cdr of x is not null , a space , a dot , a space , and the cdr of x are printed.
:DOWNCASE :CAPITALIZE zebra Zebra
:PRESERVE :UPCASE ZEBRA ZEBRA
:PRESERVE :UPCASE Zebra Zebra 5. A right-parenthesis is printed.
:PRESERVE :UPCASE zebra zebra
Actually, the above algorithm is only used when *print-pretty* is false . When *print-pretty* is
:PRESERVE :DOWNCASE ZEBRA ZEBRA
true (or when pprint is used), additional whitespace 1 may replace the use of a single space , and a

Printer 22{7 22{8 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

more elaborate algorithm with similar goals but more presentational exibility is used; see Section element of the vector is printed. If there are any other elements, they are printed in turn, with
22.1.2 (Printer Dispatching). each such additional element preceded by a space if *print-pretty* is false , or whitespace 1 if
*print-pretty* is true . A right-parenthesis after the last element terminates the printed represen-
Although the two expressions below are equivalent, and the reader accepts either one and pro- tation of the vector . The printing of vectors is a ected by *print-level* and *print-length*. If
duces the same cons , the printer always prints such a cons in the second form. the vector has a ll pointer , then only those elements below the ll pointer are printed.
(a . (b . ((c . (d . nil)) . (e . nil)))) If both *print-array* and *print-readably* are false , the vector is not printed as described
(a b (c d) e) above, but in a format (using #<) that is concise but not readable.
The printing of conses is a ected by *print-level*, *print-length*, and *print-circle*. If *print-readably* is true , the vector prints in an implementation-de ned manner; see the
Following are examples of printed representations of lists : variable *print-readably*.
(a . b) ;A dotted pair of a and b For information on how the Lisp reader parses these \other vectors ," see Section 2.4.8.3 (Sharp-
(a.b) ;A list of one element, the symbol named a.b sign Left-Parenthesis).
(a. b) ;A list of two elements a. and b
(a .b)
(a b . c)
;A list of two elements a and .b
;A dotted list of a and b with c at the end; two conses
22.1.3.8 Printing Other Arrays
.iot ;The symbol whose name is .iot If *print-array* is true and *print-readably* is false , any array other than a vector is printed
(. b) ;Invalid -- an error is signaled if an attempt is made to read using #nA format. Let n be the rank of the array . Then # is printed, then n as a decimal integer,
;this syntax. then A, then n open parentheses. Next the elements are scanned in row-major order, using
(a .) ;Invalid -- an error is signaled. write on each element , and separating elements from each other with whitespace 1. The array's
(a .. b) ;Invalid -- an error is signaled. dimensions are numbered 0 to n-1 from left to right, and are enumerated with the rightmost index
(a . . b) ;Invalid -- an error is signaled. changing fastest. Every time the index for dimension j is incremented, the following actions are
(a b c ...) ;Invalid -- an error is signaled. taken:
(a \. b) ;A list of three elements a, ., and b
(a |.| b) ;A list of three elements a, ., and b  If j < n-1, then a close parenthesis is printed.
(a \... b) ;A list of three elements a, ..., and b
(a |...| b) ;A list of three elements a, ..., and b  If incrementing the index for dimension j caused it to equal dimension j, that index is
reset to zero and the index for dimension j-1 is incremented (thereby performing these
For information on how the Lisp reader parses lists and conses , see Section 2.4.1 (Left- three steps recursively), unless j=0, in which case the entire algorithm is terminated.
Parenthesis). If incrementing the index for dimension j did not cause it to equal dimension j, then a
space is printed.
22.1.3.6 Printing Bit Vectors
 If j < n-1, then an open parenthesis is printed.
A bit vector is printed as #* followed by the bits of the bit vector in order. If *print-array* is
false , then the bit vector is printed in a format (using #<) that is concise but not readable. Only This causes the contents to be printed in a format suitable for :initial-contents to make-array .
the active elements of the bit vector are printed. The lists e ectively printed by this procedure are subject to truncation by *print-level* and
*print-length*.
For information on Lisp reader parsing of bit vectors , see Section 2.4.8.4 (Sharpsign Asterisk).
If the array is of a specialized type , containing bits or characters, then the innermost lists gen-
22.1.3.7 Printing Other Vectors erated by the algorithm given above can instead be printed using bit-vector or string syntax,
provided that these innermost lists would not be subject to truncation by *print-length*.
If *print-array* is true and *print-readably* is false , any vector other than a string or bit If both *print-array* and *print-readably* are false , then the array is printed in a format
vector is printed using general-vector syntax; this means that information about specialized vec- (using #<) that is concise but not readable.
tor representations does not appear. The printed representation of a zero-length vector is #().
The printed representation of a non-zero-length vector begins with #(. Following that, the rst If *print-readably* is true , the array prints in an implementation-de ned manner; see the vari-
able *print-readably*. In particular, this may be important for arrays having some dimension

Printer 22{9 22{10 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

0. 22.1.3.12 Printing Structures


For information on how the Lisp reader parses these \other arrays ," see Section 2.4.8.12 (Sharp- By default, a structure of type S is printed using #S syntax. This behavior can be customized by
sign A). specifying a :print-function or :print-object option to the defstruct form that de nes S , or by
writing a print-object method that is specialized for objects of type S .
22.1.3.9 Examples of Printing Arrays Di erent structures might print out in di erent ways; the default notation for structures is:
#S(structure-name fslot-key slot-value g*)
(let ((a (make-array '(3 3)))
(*print-pretty* t) where #S indicates structure syntax, structure-name is a structure name , each slot-key is an
(*print-array* t)) initialization argument name for a slot in the structure , and each corresponding slot-value is a
(dotimes (i 3) (dotimes (j 3) (setf (aref a i j) (format nil "<~D,~D>" i j)))) representation of the object in that slot .
(print a)
(print (make-array 9 :displaced-to a))) For information on how the Lisp reader parses structures , see Section 2.4.8.13 (Sharpsign S).
. #2A(("<0,0>" "<0,1>" "<0,2>")
.
.
("<1,0>" "<1,1>" "<1,2>")
("<2,0>" "<2,1>" "<2,2>"))
22.1.3.13 Printing Other Objects
. #("<0,0>" "<0,1>" "<0,2>" "<1,0>" "<1,1>" "<1,2>" "<2,0>" "<2,1>" "<2,2>") Other objects are printed in an implementation-dependent manner. It is not required that an
! #<ARRAY 9 indirect 36363476> implementation print those objects readably .
For example, hash tables , readtables , packages , streams , and functions might not print readably .
22.1.3.10 Printing Random States
A common notation to use in this circumstance is #<...>. Since #< is not readable by the Lisp
A speci c syntax for printing objects of type random-state is not speci ed. However, every reader , the precise format of the text which follows is not important, but a common format to use
implementation must arrange to print a random state object in such a way that, within the same is that provided by the print-unreadable-object macro .
implementation, read can construct from the printed representation a copy of the random state
object as if the copy had been made by make-random-state . For information on how the Lisp reader treats this notation, see Section 2.4.8.20 (Sharpsign
Less-Than-Sign). For information on how to notate objects that cannot be printed readably , see
If the type random state is e ectively implemented by using the machinery for defstruct, the Section 2.4.8.6 (Sharpsign Dot).
usual structure syntax can then be used for printing random state objects; one might look some-
thing like
#S(RANDOM-STATE :DATA #(14 49 98436589 786345 8734658324 ... ))
22.1.4 Examples of Printer Behavior
where the components are implementation-dependent . (let ((*print-escape* t)) (fresh-line) (write #\a))
. #\a
22.1.3.11 Printing Pathnames ! #\a
(let ((*print-escape* nil) (*print-readably* nil))
When printer escaping is enabled, the syntax #P"..." is how a pathname is printed by write and (fresh-line)
the other functions herein described. The "..." is the namestring representation of the pathname. (write #\a))
. a
When printer escaping is disabled, write writes a pathname P by writing (namestring P) instead. ! #\a
For information on how the Lisp reader parses pathnames , see Section 2.4.8.14 (Sharpsign P). (progn (fresh-line) (prin1 #\a))
. #\a
! #\a
(progn (fresh-line) (print #\a))
.

Printer 22{11 22{12 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

. #\a
! #\a
22.2 The Lisp Pretty Printer
(progn (fresh-line) (princ #\a))
.
!
a
#\a
22.2.1 Pretty Printer Concepts
The facilities provided by the pretty printer permit programs to rede ne the way in which code
is displayed, and allow the full power of pretty printing to be applied to complex combinations of
(dolist (val '(t nil)) data structures.
(let ((*print-escape* val) (*print-readably* val))
Whether any given style of output is in fact \pretty" is inherently a somewhat subjective issue.
(print '#\a)
However, since the e ect of the pretty printer can be customized by conforming programs , the
(prin1 #\a) (write-char #\Space)
necessary exibility is provided for individual programs to achieve an arbitrary degree of aesthetic
(princ #\a) (write-char #\Space)
(write #\a)))
control.
. #\a #\a a #\a By providing direct access to the mechanisms within the pretty printer that make dynamic
. #\a #\a a a decisions about layout, the macros and functions pprint-logical-block, pprint-newline, and
! NIL pprint-indent make it possible to specify pretty printing layout rules as a part of any function
that produces output. They also make it very easy for the detection of circularity and sharing,
and abbreviation based on length and nesting depth to be supported by the function.
.
(progn (fresh-line) (write '(let ((a 1) (b 2)) (+ a b))))
The pretty printer is driven entirely by dispatch based on the value of *print-pprint-dispatch*.
!
(LET ((A 1) (B 2)) (+ A B))
The function set-pprint-dispatch makes it possible for conforming programs to associate new
(LET ((A 1) (B 2)) (+ A B))
pretty printing functions with a type .

(progn (fresh-line) (pprint '(let ((a 1) (b 2)) (+ a b))))


22.2.1.1 Dynamic Control of the Arrangement of Output
. (LET ((A 1) The actions of the pretty printer when a piece of output is too large to t in the space available
. (B 2)) can be precisely controlled. Three concepts underlie the way these operations work|logical
. (+ A B)) blocks, conditional newlines , and sections . Before proceeding further, it is important to
! (LET ((A 1) (B 2)) (+ A B)) de ne these terms.
The rst line of Figure 22{3 shows a schematic piece of output. Each of the characters in the
output is represented by \-". The positions of conditional newlines are indicated by digits. The
(progn (fresh-line) beginnings and ends of logical blocks are indicated by \<" and \>" respectively.
(write '(let ((a 1) (b 2)) (+ a b)) :pretty t))
. (LET ((A 1) The output as a whole is a logical block and the outermost section. This section is indicated
. (B 2)) by the 0's on the second line of Figure 1. Logical blocks nested within the output are speci-
. (+ A B)) ed by the macro pprint-logical-block. Conditional newline positions are speci ed by calls to
! (LET ((A 1) (B 2)) (+ A B)) pprint-newline. Each conditional newline de nes two sections (one before it and one after it) and
is associated with a third (the section immediately containing it).
The section after a conditional newline consists of: all the output up to, but not including, (a)
(with-output-to-string (s) the next conditional newline immediately contained in the same logical block; or if (a) is not
(write 'write :stream s) applicable, (b) the next newline that is at a lesser level of nesting in logical blocks; or if (b) is not
(prin1 'prin1 s)) applicable, (c) the end of the output.
! "WRITEPRIN1"
The section before a conditional newline consists of: all the output back to, but not including,
(a) the previous conditional newline that is immediately contained in the same logical block; or if

Printer 22{13 22{14 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

(a) is not applicable, (b) the beginning of the immediately containing logical block. The last four 22.2.1.3 Compiling Format Strings
lines in Figure 1 indicate the sections before and after the four conditional newlines.
A format string is essentially a program in a special-purpose language that performs printing,
The section immediately containing a conditional newline is the shortest section that contains the and that is interpreted by the function format. The formatter macro provides the eciency of
conditional newline in question. In Figure 22{3, the rst conditional newline is immediately con- using a compiled function to do that same printing but without losing the textual compactness of
tained in the section marked with 0's, the second and third conditional newlines are immediately format strings .
contained in the section before the fourth conditional newline, and the fourth conditional newline
is immediately contained in the section after the rst conditional newline. A format control is either a format string or a function that was returned by the the formatter
macro .
<-1---<--<--2---3->--4-->->
000000000000000000000000000
11 111111111111111111111111
22.2.1.4 Pretty Print Dispatch Tables
22 222 A pprint dispatch table is a mapping from keys to pairs of values. Each key is a type speci er .
333 3333 The values associated with a key are a \function" (speci cally, a function designator or nil) and a
44444444444444 44444 \numerical priority" (speci cally, a real ). Basic insertion and retrieval is done based on the keys
with the equality of keys being tested by equal.
Figure 22{3. Example of Logical Blocks, Conditional Newlines, and Sections When *print-pretty* is true , the current pprint dispatch table (in *print-pprint-dispatch*)
controls how objects are printed. The information in this table takes precedence over all other
Whenever possible, the pretty printer displays the entire contents of a section on a single line. mechanisms for specifying how to print objects . In particular, it has priority over user-de ned
However, if the section is too long to t in the space available, line breaks are inserted at condi- print-object methods because the current pprint dispatch table is consulted rst.
tional newline positions within the section.
The function is chosen from the current pprint dispatch table by nding the highest priority
22.2.1.2 Format Directive Interface function that is associated with a type speci er that matches the object ; if there is more than one
such function, it is implementation-dependent which is used.
The primary interface to operations for dynamically determining the arrangement of output is However, if there is no information in the table about how to pretty print a particular kind
provided through the functions and macros of the pretty printer. Figure 22{4 shows the de ned of object , a function is invoked which uses print-object to print the object . The value of
names related to pretty printing . *print-pretty* is still true when this function is called , and individual methods for print-object
*print-lines* pprint-dispatch pprint-pop might still elect to produce output in a special format conditional on the value of *print-pretty*.
*print-miser-width* pprint-exit-if-list-exhausted pprint-tab
*print-pprint-dispatch* pprint- ll pprint-tabular
*print-right-margin* pprint-indent set-pprint-dispatch 22.2.1.5 Pretty Printer Margins
copy-pprint-dispatch pprint-linear write A primary goal of pretty printing is to keep the output between a pair of margins. The column
format pprint-logical-block where the output begins is taken as the left margin. If the current column cannot be determined
formatter pprint-newline at the time output begins, the left margin is assumed to be zero. The right margin is controlled
by *print-right-margin*.
Figure 22{4. De ned names related to pretty printing.
Figure 22{5 identi es a set of format directives which serve as an alternate interface to the same
pretty printing operations in a more textually compact form.
~I ~W ~<...~:>
~:T ~/.../ ~

Figure 22{5. Format directives related to Pretty Printing

Printer 22{15 22{16 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.2.2 Examples of using the Pretty Printer (X Y)


(* X Y))
As an example of the interaction of logical blocks, conditional newlines, and indentation, consider
the function simple-pprint-defun below. This function prints out lists whose cars are defun in As an example of a per-line pre x, consider that evaluating the following produces the output
the standard way assuming that the list has exactly length 4. shown with a line width of 20 and *print-miser-width* of nil.
(defun simple-pprint-defun (*standard-output* list) (pprint-logical-block (*standard-output* nil :per-line-prefix ";;; ")
(pprint-logical-block (*standard-output* list :prefix "(" :suffix ")") (simple-pprint-defun *standard-output* '(defun prod (x y) (* x y))))
(write (first list))
(write-char #\Space) ;;; (DEFUN PROD
(pprint-newline :miser) ;;; (X Y)
(pprint-indent :current 0) ;;; (* X Y))
(write (second list))
(write-char #\Space) As a more complex (and realistic) example, consider the function pprint-let below. This speci-
(pprint-newline :fill) es how to print a let form in the traditional style. It is more complex than the example above,
(write (third list)) because it has to deal with nested structure. Also, unlike the example above it contains com-
(pprint-indent :block 1) plete code to readably print any possible list that begins with the symbol let. The outermost
(write-char #\Space) pprint-logical-block form handles the printing of the input list as a whole and speci es that
(pprint-newline :linear) parentheses should be printed in the output. The second pprint-logical-block form handles the
(write (fourth list)))) list of binding pairs. Each pair in the list is itself printed by the innermost pprint-logical-block.
(A loop form is used instead of merely decomposing the pair into two objects so that readable
Suppose that one evaluates the following: output will be produced no matter whether the list corresponding to the pair has one element,
two elements, or (being malformed) has more than two elements.) A space and a ll-style con-
(simple-pprint-defun *standard-output* '(defun prod (x y) (* x y)))
ditional newline are placed after each pair except the last. The loop at the end of the topmost
If the line width available is greater than or equal to 26, then all of the output appears on pprint-logical-block form prints out the forms in the body of the let form separated by spaces
one line. If the line width available is reduced to 25, a line break is inserted at the linear- and linear-style conditional newlines.
style conditional newline before the expression (* x y), producing the output shown. The (defun pprint-let (*standard-output* list)
(pprint-indent :block 1) causes (* x y) to be printed at a relative indentation of 1 in the (pprint-logical-block (nil list :prefix "(" :suffix ")")
logical block. (write (pprint-pop))
(DEFUN PROD (X Y) (pprint-exit-if-list-exhausted)
(* X Y)) (write-char #\Space)
(pprint-logical-block (nil (pprint-pop) :prefix "(" :suffix ")")
If the line width available is 15, a line break is also inserted at the ll style conditional newline (pprint-exit-if-list-exhausted)
before the argument list. The call on (pprint-indent :current 0) causes the argument list to line (loop (pprint-logical-block (nil (pprint-pop) :prefix "(" :suffix ")")
up under the function name. (pprint-exit-if-list-exhausted)
(loop (write (pprint-pop))
(DEFUN PROD (pprint-exit-if-list-exhausted)
(X Y) (write-char #\Space)
(* X Y)) (pprint-newline :linear)))
If *print-miser-width* were greater than or equal to 14, the example output above would have (pprint-exit-if-list-exhausted)
been as follows, because all indentation changes are ignored in miser mode and line breaks are (write-char #\Space)
inserted at miser-style conditional newlines. (pprint-newline :fill)))
(pprint-indent :block 1)
(DEFUN (loop (pprint-exit-if-list-exhausted)
PROD (write-char #\Space)

Printer 22{17 22{18 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

(pprint-newline :linear) (let ((end (length v)) (i 0))


(write (pprint-pop))))) (when (plusp end)
(loop (pprint-pop)
Suppose that one evaluates the following with *print-level* being 4, and *print-circle* being (write (aref v i))
true . (if (= (incf i) end) (return nil))
(write-char #\Space)
(pprint-let *standard-output*
(pprint-newline :fill))))))
'#1=(let (x (*print-length* (f (g 3)))
(z . 2) (k (car y))) Evaluating the following with a line length of 15 produces the output shown.
(setq x (sqrt z)) #1#))
(pprint-vector *standard-output* '#(12 34 567 8 9012 34 567 89 0 1 23))
If the line length is greater than or equal to 77, the output produced appears on one line. How-
ever, if the line length is 76, line breaks are inserted at the linear-style conditional newlines #(12 34 567 8
separating the forms in the body and the output below is produced. Note that, the degenerate 9012 34 567
binding pair x is printed readably even though it fails to be a list; a depth abbreviation marker 89 0 1 23)
is printed in place of (g 3); the binding pair (z . 2) is printed readably even though it is not a
proper list; and appropriate circularity markers are printed. As examples of the convenience of specifying pretty printing with format strings , consider that
the functions simple-pprint-defun and pprint-let used as examples above can be compactly
#1=(LET (X (*PRINT-LENGTH* (F #)) (Z . 2) (K (CAR Y))) de ned as follows. (The function pprint-vector cannot be de ned using format because the data
(SETQ X (SQRT Z))
#1#)
structure it traverses is not a list.)
(defun simple-pprint-defun (*standard-output* list)
If the line length is reduced to 35, a line break is inserted at one of the ll-style conditional (format T "~:<~W ~@ ~:I~W ~: ~W~1I ~ ~W~:>" list))
newlines separating the binding pairs.
(defun pprint-let (*standard-output* list)
#1=(LET (X (*PRINT-PRETTY* (F #))
(format T "~:<~W~^~:<~@{~:<~@{~W~^~ ~}~:>~^~: ~}~:>~1I~@{~^~ ~W~}~:>" list))
(Z . 2) (K (CAR Y)))
(SETQ X (SQRT Z)) In the following example, the rst form restores *print-pprint-dispatch* to the equivalent of its
#1#) initial value. The next two forms then set up a special way to pretty print ratios. Note that the
Suppose that the line length is further reduced to 22 and *print-length* is set to 3. In this more speci c type speci er has to be associated with a higher priority.
situation, line breaks are inserted after both the rst and second binding pairs. In addition, the (setq *print-pprint-dispatch* (copy-pprint-dispatch nil))
second binding pair is itself broken across two lines. Clause (b) of the description of ll-style
conditional newlines (see the function pprint-newline) prevents the binding pair (z . 2) from (set-pprint-dispatch 'ratio
being printed at the end of the third line. Note that the length abbreviation hides the circularity #'(lambda (s obj)
from view and therefore the printing of circularity markers disappears. (format s "#.(/ ~W ~W)"
(numerator obj) (denominator obj))))
(LET (X
(*PRINT-LENGTH*
(set-pprint-dispatch '(and ratio (satisfies minusp))
(F #))
#'(lambda (s obj)
(Z . 2) ...)
(format s "#.(- (/ ~W ~W))"
(SETQ X (SQRT Z))
(- (numerator obj)) (denominator obj)))
...)
5)
The next function prints a vector using \#(...)" notation.
(pprint '(1/3 -2/3))
(defun pprint-vector (*standard-output* v) (#.(/ 1 3) #.(- (/ 2 3)))
(pprint-logical-block (nil nil :prefix "#(" :suffix ")")

Printer 22{19 22{20 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

The following two forms illustrate the de nition of pretty printing functions for types of code . (write (list 'principal-family
The rst form illustrates how to specify the traditional method for printing quoted objects using (make-family :mom "Lucy"
single-quote . Note the care taken to ensure that data lists that happen to begin with quote will :kids '("Mark" "Bob" . "Dan")))
be printed readably. The second form speci es that lists beginning with the symbol my-let should :right-margin 25 :pretty T :escape nil :miser-width nil)
print the same way that lists beginning with let print when the initial pprint dispatch table is in (PRINCIPAL-FAMILY
e ect. #<Lucy and
Mark Bob . Dan>)
(set-pprint-dispatch '(cons (member quote)) ()
#'(lambda (s list) Note that a pretty printing function for a structure is di erent from the structure's print-object
(if (and (consp (cdr list)) (null (cddr list))) method . While print-object methods are permanently associated with a structure, pretty printing
(funcall (formatter "'~W") s (cadr list)) functions are stored in pprint dispatch tables and can be rapidly changed to re ect di erent
(pprint-fill s list)))) printing needs. If there is no pretty printing function for a structure in the current pprint dispatch
table , its print-object method is used instead.
(set-pprint-dispatch '(cons (member my-let))
(pprint-dispatch '(let) nil))
22.2.3 Notes about the Pretty Printer's Background
The next example speci es a default method for printing lists that do not correspond to function For a background reference to the abstract concepts detailed in this section, see XP: A Common
calls. Note that the functions pprint-linear, pprint- ll, and pprint-tabular are all de ned with Lisp Pretty Printing System . The details of that paper are not binding on this document, but
optional colon-p and at-sign-p arguments so that they can be used as pprint dispatch functions may be helpful in establishing a conceptual basis for understanding this material.
as well as ~/.../ functions.
(set-pprint-dispatch '(cons (not (and symbol (satisfies fboundp))))
#'pprint-fill -5)

;; Assume a line length of 9


(pprint '(0 b c d e f g h i j k))
(0 b c d
e f g h
i j k)

This nal example shows how to de ne a pretty printing function for a user de ned data struc-
ture.
(defstruct family mom kids)

(set-pprint-dispatch 'family
#'(lambda (s f)
(funcall (formatter "~@<#<~;~W and ~2I~ ~/pprint-fill/~;>~:>")
s (family-mom f) (family-kids f))))

The pretty printing function for the structure family speci es how to adjust the layout of the out-
put so that it can t aesthetically into a variety of line widths. In addition, it obeys the printer
control variables *print-level*, *print-length*, *print-lines*, *print-circle* and *print-escape*,
and can tolerate several di erent kinds of malformity in the data structure. The output below
shows what is printed out with a right margin of 25, *print-pretty* being true , *print-escape*
being false , and a malformed kids list.

Printer 22{21 22{22 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3 Formatted Output containing the output from control-string . If destination is non-nil , it must be a string with a
ll pointer , a stream , or the symbol t. If destination is a string with a ll pointer , the output is
format is useful for producing nicely formatted text, producing good-looking messages, and so on. added to the end of the string . If destination is a stream , the output is sent to that stream . If
format can generate and return a string or output to destination. destination is t, the output is sent to standard output .
The control-string argument to format is actually a format control . That is, it can be either a In the description of the directives that follows, the term arg in general refers to the next item
format string or a function , for example a function returned by the formatter macro . of the set of args to be processed. The word or phrase at the beginning of each description is a
If it is a function , the function is called with the appropriate output stream as its rst argument mnemonic for the directive. format directives do not bind any of the printer control variables
and the data arguments to format as its remaining arguments. The function should perform (*print-...*) except as speci ed in the following descriptions. Implementations may specify
whatever output is necessary and return the unused tail of the arguments (if any). the binding of new, implementation-speci c printer control variables for each format directive,
but they may neither bind any standard printer control variables not speci ed in description
The compilation process performed by formatter produces a function that would do with its of a format directive nor fail to bind any standard printer control variables as speci ed in the
arguments as the format interpreter would do with those arguments . description.
The remainder of this section describes what happens if the control-string is a format string . 22.3.1 FORMAT Basic Output
Control-string is composed of simple text (characters ) and embedded directives.
format writes the simple text as is; each embedded directive speci es further text output that 22.3.1.1 Tilde C: Character
is to appear at the corresponding point within the simple text. Most directives use one or more
elements of args to create their output. The next arg should be a character ; it is printed according to the modi er ags.
A directive consists of a tilde , optional pre x parameters separated by commas, optional colon ~C prints the character as if by using write-char if it is a simple character . Characters
and at-sign modi ers, and a single character indicating what kind of directive this is. There is that are not simple are not necessarily printed as if by write-char, but are displayed in an
no required ordering between the at-sign and colon modi er. The case of the directive character implementation-de ned , abbreviated format. For example,
is ignored. Pre x parameters are notated as signed (sign is optional) decimal numbers, or as
a single-quote followed by a character. For example, ~5,'0d can be used to print an integer in (format nil "~C" #\A) !
"A"
decimal radix in ve columns with leading zeros, or ~5,'*d to get leading asterisks. (format nil "~C" #\Space) !
" "

In place of a pre x parameter to a directive, V (or v) can be used. In this case, format takes ~:C is the same as ~C for printing characters , but other characters are \spelled out." The intent is
an argument from args as a parameter to the directive. The argument should be an integer or that this is a \pretty" format for printing characters. For simple characters that are not printing ,
character . If the arg used by a V parameter is nil, the e ect is as if the parameter had been what is spelled out is the name of the character (see char-name). For characters that are not
omitted. # can be used in place of a pre x parameter; it represents the number of args remaining simple and not printing , what is spelled out is implementation-de ned . For example,
to be processed. When used within a recursive format, in the context of ~? or ~{, the # pre x !
parameter represents the number of format arguments remaining within the recursive call. (format nil "~:C" #\A)
(format nil "~:C" #\Space)
"A"
!
"Space"
Examples of format strings : ;; This next example assumes an implementation-defined "Control" attribute.
(format nil "~:C" #\Control-Space)
"~S" ;This is an S directive with no parameters or modi ers. !
or
"Control-Space"
"~3,-4:@s" ;This is an S directive with two parameters, 3 and -4, ! "c-Space"
; and both the colon and at-sign ags.
"~,+4S" ;Here the rst pre x parameter is omitted and takes ~:@C prints what ~:C would, and then if the character requires unusual shift keys on the keyboard
; on its default value, while the second parameter is 4. to type it, this fact is mentioned. For example,
(format nil "~:@C" #\Control-Partial) ! "Control-@ (Top-F)"
Figure 22{6. Examples of format control strings
format sends the output to destination. If destination is nil, format creates and returns a string This is the format used for telling the user about a key he is expected to type, in prompts, for

Printer 22{23 22{24 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

instance. The precise output may depend not only on the implementation, but on the particular  ~:@R prints arg as an old Roman numeral: IIII.
I/O devices in use.
For example:
~@C prints the character in a way that the Lisp reader can understand, using #\ syntax.
(format nil "~,,' ,4:B" 13) ! "1101"
~@C binds *print-escape* to t. (format nil "~,,' ,4:B" 17) ! "1 0001"
(format nil "~19,0,' ,4:B" 3333)! "0000 1101 0000 0101"

22.3.1.2 Tilde Percent: Newline (format nil "~3,,,' ,2:R" 17) ! "1 22"
(format nil "~,,'|,2:D" #xFFFF)! "6|55|35"
This outputs a #\Newline character, thereby terminating the current output line and beginning a If and only if the rst parameter, n , is supplied, ~R binds *print-escape* to false , *print-radix*
new one. ~n % outputs n newlines. No arg is used. to false , *print-base* to n , and *print-readably* to false .
22.3.1.3 Tilde Ampersand: Fresh-Line If and only if no parameters are supplied, ~R binds *print-base* to 10.
Unless it can be determined that the output stream is already at the beginning of a line, this 22.3.2.2 Tilde D: Decimal
outputs a newline. ~n & calls fresh-line and then outputs n 1 newlines. ~0& does nothing.
An arg , which should be an integer , is printed in decimal radix. ~D will never put a decimal point
22.3.1.4 Tilde Vertical-Bar: Page after the number.
This outputs a page separator character, if possible. ~n | does this n times. ~mincol D uses a column width of mincol ; spaces are inserted on the left if the number requires
fewer than mincol columns for its digits and sign. If the number doesn't t in mincol columns,
22.3.1.5 Tilde Tilde: Tilde additional columns are used as needed.
~mincol ,padchar D uses padchar as the pad character instead of space.
This outputs a tilde . ~n ~ outputs n tildes.
If arg is not an integer , it is printed in ~A format and decimal base.
22.3.2 FORMAT Radix Control The @ modi er causes the number's sign to be printed always; the default is to print it only if
the number is negative. The : modi er causes commas to be printed between groups of digits;
commachar may be used to change the character used as the comma. comma-interval must be an
22.3.2.1 Tilde R: Radix integer and defaults to 3. When the : modi er is given to any of these directives, the commachar
is printed between groups of comma-interval digits.
n prints arg in radix n . The modi er ags and any remaining parameters are used as for the ~D
~ R
directive. ~D is the same as ~10R. The full form is ~radix ,mincol ,padchar ,commachar ,comma-interval R. Thus the most general form of ~D is ~mincol ,padchar ,commachar ,comma-interval D.
If no pre x parameters are given to ~R, then a di erent interpretation is given. The argument ~D binds *print-escape* to false , *print-radix* to false , *print-base* to 10, and
should be an integer . For example, if arg is 4: *print-readably* to false .
 ~R prints arg as a cardinal English number: four. 22.3.2.3 Tilde B: Binary
 ~:R prints arg as an ordinal English number: fourth. This is just like ~D but prints in binary radix (radix 2) instead of decimal. The full form is
therefore ~mincol ,padchar ,commachar ,comma-interval B.
 ~@R prints arg as a Roman numeral: IV. ~B binds *print-escape* to false , *print-radix* to false , *print-base* to 2, and
*print-readably* to false .

Printer 22{25 22{26 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3.2.4 Tilde O: Octal If the parameter d is omitted, then there is no constraint on the number of digits to appear
after the decimal point. A value is chosen for d in such a way that as many digits as possible
This is just like ~D but prints in octal radix (radix 8) instead of decimal. The full form is therefore may be printed subject to the width constraint imposed by the parameter w and the constraint
~mincol ,padchar ,commachar ,comma-interval O. that no trailing zero digits may appear in the fraction, except that if the fraction to be printed
~O binds *print-escape* to false , *print-radix* to false , *print-base* to 8, and
is zero, then a single zero digit should appear after the decimal point if permitted by the width
*print-readably* to false . constraint.
If both w and d are omitted, then the e ect is to print the value using ordinary free-format
22.3.2.5 Tilde X: Hexadecimal output; prin1 uses this format for any number whose magnitude is either zero or between 10 3
(inclusive) and 107 (exclusive).
This is just like ~D but prints in hexadecimal radix (radix 16) instead of decimal. The full form is
therefore ~mincol ,padchar ,commachar ,comma-interval X. If w is omitted, then if the magnitude of arg is so large (or, if d is also omitted, so small) that
more than 100 digits would have to be printed, then an implementation is free, at its discre-
~X binds *print-escape* to false , *print-radix* to false , *print-base* to 16, and tion, to print the number using exponential notation instead, as if by the directive ~E (with all
*print-readably* to false . parameters to ~E defaulted, not taking their values from the ~F directive).
22.3.3 FORMAT Floating-Point Printers If arg is a rational number, then it is coerced to be a single oat and then printed. Alternatively,
an implementation is permitted to process a rational number by any other method that has
essentially the same behavior but avoids loss of precision or over ow because of the coercion. If
w and d are not supplied and the number has no exact decimal representation, for example 1/3,
22.3.3.1 Tilde F: Fixed-Format Floating-Point some precision cuto must be chosen by the implementation since only a nite number of digits
may be printed.
The next arg is printed as a oat .
If arg is a complex number or some non-numeric object , then it is printed using the format
The full form is ~w ,d ,k ,over owchar ,padchar F. The parameter w is the width of the eld to be directive ~w D, thereby printing it in decimal radix and a minimum eld width of w .
printed; d is the number of digits to print after the decimal point; k is a scale factor that defaults
to zero. ~F binds *print-escape* to false and *print-readably* to false .

Exactly w characters will be output. First, leading copies of the character padchar (which de-
faults to a space) are printed, if necessary, to pad the eld on the left. If the arg is negative, then 22.3.3.2 Tilde E: Exponential Floating-Point
a minus sign is printed; if the arg is not negative, then a plus sign is printed if and only if the @ The next arg is printed as a oat in exponential notation.
modi er was supplied. Then a sequence of digits, containing a single embedded decimal point,
is printed; this represents the magnitude of the value of arg times 10k , rounded to d fractional The full form is ~w ,d ,e ,k ,over owchar ,padchar ,exponentchar E . The parameter w is the width
digits. When rounding up and rounding down would produce printed values equidistant from the of the eld to be printed; d is the number of digits to print after the decimal point; e is the
scaled value of arg , then the implementation is free to use either one. For example, printing the number of digits to use when printing the exponent; k is a scale factor that defaults to one (not
argument 6.375 using the format ~4,2F may correctly produce either 6.37 or 6.38. Leading zeros zero).
are not permitted, except that a single zero digit is output before the decimal point if the printed Exactly w characters will be output. First, leading copies of the character padchar (which de-
value is less than one, and this single zero digit is not output at all if w =d +1.
faults to a space) are printed, if necessary, to pad the eld on the left. If the arg is negative, then
If it is impossible to print the value in the required format in a eld of width w , then one of two a minus sign is printed; if the arg is not negative, then a plus sign is printed if and only if the
actions is taken. If the parameter over owchar is supplied, then w copies of that parameter are @ modi er was supplied. Then a sequence of digits containing a single embedded decimal point
printed instead of the scaled value of arg . If the over owchar parameter is omitted, then the is printed. The form of this sequence of digits depends on the scale factor k . If k is zero, then
scaled value is printed using more than w characters, as many more as may be needed. d digits are printed after the decimal point, and a single zero digit appears before the decimal
point if the total eld width will permit it. If k is positive, then it must be strictly less than d +2;
If the w parameter is omitted, then the eld is of variable width. In e ect, a value is chosen for k signi cant digits are printed before the decimal point, and d k +1 digits are printed after the
w in such a way that no leading pad characters need to be printed and exactly d characters will decimal point. If k is negative, then it must be strictly greater than d ; a single zero digit ap-
follow the decimal point. For example, the directive ~,2F will print exactly two digits after the pears before the decimal point if the total eld width will permit it, and after the decimal point
decimal point and as many as necessary before the decimal point.

Printer 22{27 22{28 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

are printed rst k zeros and then d +k signi cant digits. The printed fraction must be properly ~E binds *print-escape* to false and *print-readably* to false .
rounded. When rounding up and rounding down would produce printed values equidistant from
the scaled value of arg , then the implementation is free to use either one. For example, printing
the argument 637.5 using the format ~8,2E may correctly produce either 6.37E+2 or 6.38E+2. 22.3.3.3 Tilde G: General Floating-Point
Following the digit sequence, the exponent is printed. First the character parameter exponentchar The next arg is printed as a oat in either xed-format or exponential notation as appropriate.
is printed; if this parameter is omitted, then the exponent marker that prin1 would use is printed, The full form is ~w ,d ,e ,k ,over owchar ,padchar ,exponentchar G . The format in which to print
as determined from the type of the oat and the current value of *read-default- oat-format*. arg depends on the magnitude (absolute value) of the arg . Let n be an integer such that 10n 1
Next, either a plus sign or a minus sign is printed, followed by e digits representing the power of  jarg j < 10n . Let ee equal e +2, or 4 if e is omitted. Let ww equal w ee , or nil if w is omitted.
ten by which the printed fraction must be multiplied to properly represent the rounded value of If d is omitted, rst let q be the number of digits needed to print arg with no loss of information
arg . and without leading or trailing zeros; then let d equal (max q (min n 7)). Let dd equal d n .
If it is impossible to print the value in the required format in a eld of width w , possibly because If 0  dd  d , then arg is printed as if by the format directives
k is too large or too small or because the exponent cannot be printed in e character positions,
then one of two actions is taken. If the parameter over owchar is supplied, then w copies of ~ww ,dd ,,over owchar ,padchar F~ee @T
that parameter are printed instead of the scaled value of arg . If the over owchar parameter is Note that the scale factor k is not passed to the ~F directive. For all other values of dd , arg is
omitted, then the scaled value is printed using more than w characters, as many more as may printed as if by the format directive
be needed; if the problem is that d is too small for the supplied k or that e is too small, then a
larger value is used for d or e as may be needed. w d e k over owchar ,padchar ,exponentchar E
~ , , , ,
If the w parameter is omitted, then the eld is of variable width. In e ect a value is chosen for w In either case, an @ modi er is supplied to the ~F or ~E directive if and only if one was supplied to
in such a way that no leading pad characters need to be printed. the ~G directive.
If the parameter d is omitted, then there is no constraint on the number of digits to appear. A ~G binds *print-escape* to false and *print-readably* to false .
value is chosen for d in such a way that as many digits as possible may be printed subject to
the width constraint imposed by the parameter w , the constraint of the scale factor k , and the
constraint that no trailing zero digits may appear in the fraction, except that if the fraction to be 22.3.3.4 Tilde Dollarsign: Monetary Floating-Point
printed is zero then a single zero digit should appear after the decimal point. The next arg is printed as a oat in xed-format notation.
If the parameter e is omitted, then the exponent is printed using the smallest number of digits The full form is ~d ,n ,w ,padchar $. The parameter d is the number of digits to print after the
necessary to represent its value. decimal point (default value 2); n is the minimum number of digits to print before the decimal
If all of w , d , and e are omitted, then the e ect is to print the value using ordinary free-format point (default value 1); w is the minimum total width of the eld to be printed (default value 0).
exponential-notation output; prin1 uses a similar format for any non-zero number whose magni- First padding and the sign are output. If the arg is negative, then a minus sign is printed; if the
tude is less than 10 3 or greater than or equal to 107. The only di erence is that the ~E directive arg is not negative, then a plus sign is printed if and only if the @ modi er was supplied. If the
always prints a plus or minus sign in front of the exponent, while prin1 omits the plus sign if the : modi er is used, the sign appears before any padding, and otherwise after the padding. If w is
exponent is non-negative. supplied and the number of other characters to be output is less than w , then copies of padchar
If arg is a rational number, then it is coerced to be a single oat and then printed. Alternatively, (which defaults to a space) are output to make the total eld width equal w . Then n digits are
an implementation is permitted to process a rational number by any other method that has printed for the integer part of arg , with leading zeros if necessary; then a decimal point; then d
essentially the same behavior but avoids loss of precision or over ow because of the coercion. If w digits of fraction, properly rounded.
and d are unsupplied and the number has no exact decimal representation, for example 1/3, some If the magnitude of arg is so large that more than m digits would have to be printed, where m
precision cuto must be chosen by the implementation since only a nite number of digits may be is the larger of w and 100, then an implementation is free, at its discretion, to print the number
printed. using exponential notation instead, as if by the directive ~w ,q ,,,,padchar E, where w and padchar
If arg is a complex number or some non-numeric object , then it is printed using the format are present or omitted according to whether they were present or omitted in the ~$ directive, and
directive ~w D, thereby printing it in decimal radix and a minimum eld width of w . where q =d +n 1, where d and n are the (possibly default) values given to the ~$ directive.

Printer 22{29 22{30 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

If arg is a rational number, then it is coerced to be a single oat and then printed. Alternatively, 22.3.4.3 Tilde W: Write
an implementation is permitted to process a rational number by any other method that has
essentially the same behavior but avoids loss of precision or over ow because of the coercion. An argument, any object , is printed obeying every printer control variable (as by write). In
addition, ~W interacts correctly with depth abbreviation, by not resetting the depth counter to
If arg is a complex number or some non-numeric object , then it is printed using the format zero. ~W does not accept parameters. If given the colon modi er, ~W binds *print-pretty* to true .
directive ~w D, thereby printing it in decimal radix and a minimum eld width of w . If given the at-sign modi er, ~W binds *print-level* and *print-length* to nil.
~$ binds *print-escape* to false and *print-readably* to false . ~W provides automatic support for the detection of circularity and sharing. If the value of
*print-circle* is not nil and ~W is applied to an argument that is a circular (or shared) refer-
22.3.4 FORMAT Printer Operations ence, an appropriate #n# marker is inserted in the output instead of printing the argument.
22.3.5 FORMAT Pretty Printer Operations
22.3.4.1 Tilde A: Aesthetic The following constructs provide access to the pretty printer :
An arg , any object , is printed without escape characters (as by princ). If arg is a string , its
characters will be output verbatim. If arg is nil it will be printed as nil; the colon modi er (~:A) 22.3.5.1 Tilde Underscore: Conditional Newline
will cause an arg of nil to be printed as (), but if arg is a composite structure, such as a list or Without any modi ers, ~ is the same as (pprint-newline :linear). ~@ is the same as
vector , any contained occurrences of nil will still be printed as nil.
(pprint-newline :miser). ~: is the same as (pprint-newline :fill). ~:@ is the same as
~mincol A inserts spaces on the right, if necessary, to make the width at least mincol columns. The (pprint-newline :mandatory).
@ modi er causes the spaces to be inserted on the left rather than the right.

~mincol ,colinc ,minpad ,padchar A is the full form of ~A, which allows control of the padding. The
22.3.5.2 Tilde Less-Than-Sign: Logical Block
string is padded on the right (or on the left if the @ modi er is used) with at least minpad copies ~<...~:>
of padchar ; padding characters are then inserted colinc characters at a time until the total width
is at least mincol . The defaults are 0 for mincol and minpad , 1 for colinc , and the space character If ~:> is used to terminate a ~<...~>, the directive is equivalent to a call to pprint-logical-block.
for padchar . The argument corresponding to the ~<...~:> directive is treated in the same way as the list
argument to pprint-logical-block, thereby providing automatic support for non-list arguments
~A binds *print-escape* to false , and *print-readably* to false . and the detection of circularity, sharing, and depth abbreviation. The portion of the control-string
nested within the ~<...~:> speci es the :prefix (or :per-line-prefix), :suffix, and body of the
22.3.4.2 Tilde S: Standard pprint-logical-block.
This is just like ~A, but arg is printed with escape characters (as by prin1 rather than princ). The control-string portion enclosed by ~<...~:> can be divided into segments
The output is therefore suitable for input to read. ~S accepts all the arguments and modi ers ~<pre x ~;body ~;sux ~:> by ~; directives. If the rst section is terminated by ~@;, it speci es
that ~A does. a per-line pre x rather than a simple pre x. The pre x and sux cannot contain format di-
rectives. An error is signaled if either the pre x or sux fails to be a constant string or if the
~S binds *print-escape* to t. enclosed portion is divided into more than three segments.
If the enclosed portion is divided into only two segments, the sux defaults to the null string. If
the enclosed portion consists of only a single segment, both the pre x and the sux default to the
null string. If the colon modi er is used (i.e., ~:<...~:>), the pre x and sux default to "(" and
")" (respectively) instead of the null string.

The body segment can be any arbitrary format string . This format string is applied to the
elements of the list corresponding to the ~<...~:> directive as a whole. Elements are extracted
from this list using pprint-pop, thereby providing automatic support for malformed lists, and the

Printer 22{31 22{32 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

detection of circularity, sharing, and length abbreviation. Within the body segment, ~^ acts like boolean that is true if the at-sign modi er was used. The remaining arguments consist of any
pprint-exit-if-list-exhausted. parameters speci ed with the directive. The function should print the argument appropriately.
Any values returned by the function are ignored.
~<...~:> supports a feature not supported by pprint-logical-block. If ~:@> is used to terminate
the directive (i.e., ~<...~:@>), then a ll-style conditional newline is automatically inserted after The three functions pprint-linear, pprint- ll, and pprint-tabular are speci cally de-
each group of blanks immediately contained in the body (except for blanks after a hNewline i signed so that they can be called by ~/.../ (i.e., ~/pprint-linear/, ~/pprint-fill/, and
directive). This makes it easy to achieve the equivalent of paragraph lling. ~/pprint-tabular/). In particular they take colon and at-sign arguments.

If the at-sign modi er is used with ~<...~:>, the entire remaining argument list is passed to the
directive as its argument. All of the remaining arguments are always consumed by ~@<...~:>, 22.3.6 FORMAT Layout Control
even if they are not all used by the format string nested in the directive. Other than the di er-
ence in its argument, ~@<...~:> is exactly the same as ~<...~:> except that circularity detection
is not applied if ~@<...~:> is encountered at top level in a format string . This ensures that circu-
larity detection is applied only to data lists, not to format argument lists .
22.3.6.1 Tilde T: Tabulate
This spaces over to a given column. ~colnum ,colinc T will output sucient spaces to move the
" . #n #" is printed if circularity or sharing has to be indicated for its argument as a whole. cursor to column colnum . If the cursor is already at or beyond column colnum , it will output
To a considerable extent, the basic form of the directive ~<...~> is incompatible with the dynamic spaces to move it to column colnum +k *colinc for the smallest positive integer k possible, unless
control of the arrangement of output by ~W, ~ , ~<...~:>, ~I, and ~:T. As a result, an error is colinc is zero, in which case no spaces are output if the cursor is already at or beyond column
signaled if any of these directives is nested within ~<...~>. Beyond this, an error is also signaled if colnum . colnum and colinc default to 1.
the ~<...~:;...~> form of ~<...~> is used in the same format string with ~W, ~ , ~<...~:>, ~I, or If for some reason the current absolute column position cannot be determined by direct inquiry,
~:T. format may be able to deduce the current column position by noting that certain directives
See also Section 22.3.6.2 (Tilde Less-Than-Sign: Justi cation). (such as ~%, or ~&, or ~A with the argument being a string containing a newline) cause the column
position to be reset to zero, and counting the number of characters emitted since that point. If
that fails, format may attempt a similar deduction on the riskier assumption that the destination
22.3.5.3 Tilde I: Indent was at column zero when format was invoked. If even this heuristic fails or is implementationally
n is the same as (pprint-indent :block n).
~ I
inconvenient, at worst the ~T operation will simply output two spaces.
~@T performs relative tabulation. ~colrel ,colinc @T outputs colrel spaces and then outputs the
~n :I is the same as (pprint-indent :current n). In both cases, n defaults to zero, if it is omitted.
smallest non-negative number of additional spaces necessary to move the cursor to a column that
is a multiple of colinc . For example, the directive ~3,8@T outputs three spaces and then moves
22.3.5.4 Tilde Slash: Call Function the cursor to a \standard multiple-of-eight tab stop" if not at one already. If the current output
name /
column cannot be determined, however, then colinc is ignored, and exactly colrel spaces are
~/
output.
User de ned functions can be called from within a format string by using the directive ~/name /. If the colon modi er is used with the ~T directive, the tabbing computation is done relative to
The colon modi er, the at-sign modi er, and arbitrarily many parameters can be speci ed with the horizontal position where the section immediately containing the directive begins, rather than
the ~/name / directive. name can be any arbitrary string that does not contain a "/". All of the with respect to a horizontal position of zero. The numerical parameters are both interpreted as
characters in name are treated as if they were upper case. If name contains a single colon (:) or being in units of ems and both default to 1. ~n,m:T is the same as (pprint-tab :section n m).
double colon (::), then everything up to but not including the rst ":" or "::" is taken to be a ~n ,m:@T is the same as (pprint-tab :section-relative n m).
string that names a package . Everything after the rst ":" or "::" (if any) is taken to be a string
that names a symbol. The function corresponding to a ~/name/ directive is obtained by looking up
the symbol that has the indicated name in the indicated package . If name does not contain a ":"
or "::", then the whole name string is looked up in the COMMON-LISP-USER package .
When a ~/name/ directive is encountered, the indicated function is called with four or more argu-
ments. The rst four arguments are: the output stream, the format argument corresponding to
the directive, a generalized boolean that is true if the colon modi er was used, and a generalized

Printer 22{33 22{34 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3.6.2 Tilde Less-Than-Sign: Justi cation See also Section 22.3.5.2 (Tilde Less-Than-Sign: Logical Block).
mincol ,colinc ,minpad ,padchar <str ~>
~
22.3.6.3 Tilde Greater-Than-Sign: End of Justi cation
This justi es the text produced by processing str within a eld at least mincol columns wide. str terminates a ~<. The consequences of using it elsewhere are unde ned.
may be divided up into segments with ~;, in which case the spacing is evenly divided between the ~>
text segments.
With no modi ers, the leftmost text segment is left justi ed in the eld, and the rightmost text 22.3.7 FORMAT Control-Flow Operations
segment is right justi ed. If there is only one text element, as a special case, it is right justi ed.
The : modi er causes spacing to be introduced before the rst text segment; the @ modi er
causes spacing to be added after the last. The minpad parameter (default 0) is the minimum 22.3.7.1 Tilde Asterisk: Go-To
number of padding characters to be output between each segment. The padding character is
supplied by padchar , which defaults to the space character. If the total width needed to satisfy The next arg is ignored. ~n * ignores the next n arguments.
these constraints is greater than mincol , then the width used is mincol +k *colinc for the smallest ~:* backs up in the list of arguments so that the argument last processed will be processed again.
possible non-negative integer value k . colinc defaults to 1, and mincol defaults to 0. ~n :* backs up n arguments.
Note that str may include format directives. All the clauses in str are processed in order; it is the When within a ~{ construct (see below), the ignoring (in either direction) is relative to the list of
resulting pieces of text that are justi ed. arguments being processed by the iteration.
The ~^ directive may be used to terminate processing of the clauses prematurely, in which case ~n @* goes to the n th arg , where 0 means the rst one; n defaults to 0, so ~@* goes back to the
only the completely processed clauses are justi ed. rst arg . Directives after a ~n @* will take arguments in sequence beginning with the one gone to.
If the rst clause of a ~< is terminated with ~:; instead of ~;, then it is used in a special way. All When within a ~{ construct, the \goto" is relative to the list of arguments being processed by the
of the clauses are processed (subject to ~^, of course), but the rst one is not used in performing iteration.
the spacing and padding. When the padded result has been determined, then if it will t on the
current line of output, it is output, and the text for the rst clause is discarded. If, however, the
padded text will not t on the current line, then the text segment for the rst clause is output
22.3.7.2 Tilde Left-Bracket: Conditional Expression
before the padded text. The rst clause ought to contain a newline (such as a ~% directive). The ~[ str0 ~;str1 ~;...~;strn ~]
rst clause is always processed, and so any arguments it refers to will be used; the decision is This is a set of control strings, called clauses , one of which is chosen and used. The clauses are
whether to use the resulting segment of text, not whether to process the rst clause. If the ~:; separated by ~; and the construct is terminated by ~]. For example,
has a pre x parameter n , then the padded text must t on the current line with n character
positions to spare to avoid outputting the rst clause's text. For example, the control string "~[Siamese~;Manx~;Persian~] Cat"
"~%;; ~{~<~%;; ~1:; ~S~>~^,~}.~%" The arg th clause is selected, where the rst clause is number 0. If a pre x parameter is given (as
can be used to print a list of items separated by commas without breaking items over line bound- n ), then the parameter is used instead of an argument. If arg is out of range then no clause is
~ [
aries, beginning each line with ;; . The pre x parameter 1 in ~1:; accounts for the width of the selected and no error is signaled. After the selected alternative has been processed, the control
comma that will follow the justi ed item if it is not the last element in the list, or the period if it string continues after the ~].
is. If ~:; has a second pre x parameter, then it is used as the width of the line, thus overriding ~[str0 ~;str1 ~;...~;strn ~:;default ~] has a default case. If the last ~; used to separate clauses is
the natural line width of the output stream. To make the preceding example use a line width of ~:; instead, then the last clause is an else clause that is performed if no other clause is selected.
50, one would write For example:
"~%;; ~{~<~%;; ~1,50:; ~S~>~^,~} .~%" "~[Siamese~;Manx~;Persian~:;Alley~] Cat"
If the second argument is not supplied, then format uses the line width of the destination output ~:[alternative ~;consequent ~] selects the alternative control string if arg is false , and selects the
stream. If this cannot be determined (for example, when producing a string result), then format consequent control string otherwise.
uses 72 as the line length.

Printer 22{35 22{36 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

~@[ consequent ~] tests the argument. If it is true , then the argument is not used up by the ~[ '(fred harry jill))
command but remains as the next one to be processed, and the one clause consequent is pro- ! "The winners are: FRED HARRY JILL."
cessed. If the arg is false , then the argument is used up, and the clause is not processed. The (format nil "Pairs:~{ <~S,~S>~}."
clause therefore should normally use exactly one argument, and may expect it to be non-nil . For '(a 1 b 2 c 3))
example: ! "Pairs: <A,1> <B,2> <C,3>."

(setq *print-level* nil *print-length* 5) ~:{str ~} is similar, but the argument should be a list of sublists. At each repetition step, one
(format nil sublist is used as the set of arguments for processing str ; on the next repetition, a new sublist is
"~@[ print level = ~D~]~@[ print length = ~D~]" used, whether or not all of the last sublist had been processed. For example:
*print-level* *print-length*)
! " print length = 5" (format nil "Pairs:~:{ <~S,~S>~}."
'((a 1) (b 2) (c 3)))
Note also that ! "Pairs: <A,1> <B,2> <C,3>."

(format stream "...~@[str ~]..." ...) ~@{str ~} is similar to ~{str ~}, but instead of using one argument that is a list, all the remaining
 (format stream "...~:[~;~:*str ~]..." ...) arguments are used as the list of arguments for the iteration. Example:
The combination of ~[ and # is useful, for example, for dealing with English conventions for (format nil "Pairs:~@{ <~S,~S>~}." 'a 1 'b 2 'c 3)
printing lists: ! "Pairs: <A,1> <B,2> <C,3>."
(setq foo "Items:~#[ none~; ~S~; ~S and ~S~ If the iteration is terminated before all the remaining arguments are consumed, then any ar-
~:;~@{~#[~; and~] ~S~^,~}~].") guments not processed by the iteration remain to be processed by any directives following the
(format nil foo) !
"Items: none." iteration construct.
(format nil foo 'foo) !
"Items: FOO."
(format nil foo 'foo 'bar) !
"Items: FOO and BAR." ~:@{str ~} combines the features of ~:{str ~} and ~@{str ~}. All the remaining arguments are used,
(format nil foo 'foo 'bar 'baz) !
"Items: FOO, BAR, and BAZ." and each one must be a list . On each iteration, the next argument is used as a list of arguments
(format nil foo 'foo 'bar 'baz 'quux) !
"Items: FOO, BAR, BAZ, and QUUX." to str . Example:
22.3.7.3 Tilde Right-Bracket: End of Conditional Expression
(format nil "Pairs:~:@{ <~S,~S>~}."
'(a 1) '(b 2) '(c 3))

~] terminates a ~[. The consequences of using it elsewhere are unde ned. ! "Pairs: <A,1> <B,2> <C,3>."

Terminating the repetition construct with ~:} instead of ~} forces str to be processed at least
22.3.7.4 Tilde Left-Brace: Iteration once, even if the initial list of arguments is null. However, this will not override an explicit pre x
parameter of zero.
~{ str ~}
If str is empty, then an argument is used as str . It must be a format control and precede any
This is an iteration construct. The argument should be a list , which is used as a set of arguments arguments processed by the iteration. As an example, the following are equivalent:
as if for a recursive call to format. The string str is used repeatedly as the control string. Each
iteration can absorb as many elements of the list as it likes as arguments; if str uses up two 
(apply #'format stream string arguments)
arguments by itself, then two elements of the list will get used up each time around the loop. (format stream "~1{~:}" string arguments)
If before any iteration step the list is empty, then the iteration is terminated. Also, if a pre x This will use string as a formatting string. The ~1{ says it will be processed at most once,
parameter n is given, then there will be at most n repetitions of processing of str . Finally, the ~^ and the ~:} says it will be processed at least once. Therefore it is processed exactly once, using
directive can be used to terminate the iteration prematurely. arguments as the arguments. This case may be handled more clearly by the ~? directive, but this
For example: general feature of ~{ is more powerful than ~?.
(format nil "The winners are:~{ ~S~}."

Printer 22{37 22{38 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3.7.5 Tilde Right-Brace: End of Iteration (f 1) ! "One error detected."


(f 23) ! "Twenty-three errors detected."
~} terminates a ~{. The consequences of using it elsewhere are unde ned.
When case conversions appear nested, the outer conversion dominates, as illustrated in the
22.3.7.6 Tilde Question-Mark: Recursive Processing following example:
The next arg must be a format control , and the one after it a list ; both are consumed by the (format nil "~@(how is ~:(BOB SMITH~)?~)")
!
~? directive. The two are processed as a control-string , with the elements of the list as the ar-
"How is bob smith?"
not
guments. Once the recursive processing has been nished, the processing of the control string ! "How is Bob Smith?"

containing the ~? directive is resumed. Example:


(format nil "~? ~D" "<~A ~D>" '("Foo" 5) 7) !
"<Foo 5> 7"
22.3.8.2 Tilde Right-Paren: End of Case Conversion
(format nil "~? ~D" "<~A ~D>" '("Foo" 5 14) 7) !
"<Foo 5> 7" ~) terminates a ~(. The consequences of using it elsewhere are unde ned.
Note that in the second example three arguments are supplied to the format string "<~A ~D>", but
only two are processed and the third is therefore ignored. 22.3.8.3 Tilde P: Plural
With the @ modi er, only one arg is directly consumed. The arg must be a string ; it is processed If arg is not eql to the integer 1, a lowercase s is printed; if arg is eql to 1, nothing is printed. If
as part of the control string as if it had appeared in place of the ~@? construct, and any direc- arg is a oating-point 1.0, the s is printed.
tives in the recursively processed control string may consume arguments of the control string ~:P does the same thing, after doing a ~:* to back up one argument; that is, it prints a lowercase
containing the ~@? directive. Example: s if the previous argument was not 1.
(format nil "~@? ~D" "<~A ~D>" "Foo" 5 7) !
"<Foo 5> 7"
~@P prints y if the argument is 1, or ies if it is not. ~:@P does the same thing, but backs up rst.
(format nil "~@? ~D" "<~A ~D>" "Foo" 5 14 7) !
"<Foo 5> 14"
(format nil "~D tr~:@P/~D win~:P" 7 1) ! "7 tries/1 win"
22.3.8 FORMAT Miscellaneous Operations (format nil "~D tr~:@P/~D win~:P" 1 0)
(format nil "~D tr~:@P/~D win~:P" 1 3)
! "1 try/0 wins"
! "1 try/3 wins"

22.3.8.1 Tilde Left-Paren: Case Conversion 22.3.9 FORMAT Miscellaneous Pseudo-Operations


~( str ~)
The contained control string str is processed, and what it produces is subject to case conversion. 22.3.9.1 Tilde Semicolon: Clause Separator
With no ags, every uppercase character is converted to the corresponding lowercase character . This separates clauses in ~[ and ~< constructs. The consequences of using it elsewhere are unde-
ned.
~:( capitalizes all words, as if by string-capitalize.

~@( capitalizes just the rst word and forces the rest to lower case.

~:@( converts every lowercase character to the corresponding uppercase character.

In this example ~@( is used to cause the rst word produced by ~@R to be capitalized:
(format nil "~@R ~(~@R~)" 14 14)
! "XIV xiv"
(defun f (n) (format nil "~@(~R~) error~:P detected." n)) ! F
(f 0) ! "Zero errors detected."

Printer 22{39 22{40 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3.9.2 Tilde Circum ex: Escape Upward Following are examples of the use of ~^ within a ~< construct.
~^ (format nil "~15<~S~;~^~S~;~^~S~>" 'foo)

This is an escape construct. If there are no more arguments remaining to be processed, then the ! " FOO"
(format nil "~15<~S~;~^~S~;~^~S~>" 'foo 'bar)
immediately enclosing ~{ or ~< construct is terminated. If there is no such enclosing construct, ! "FOO BAR"
then the entire formatting operation is terminated. In the ~< case, the formatting is performed, (format nil "~15<~S~;~^~S~;~^~S~>" 'foo 'bar 'baz)
but no more segments are processed before doing the justi cation. ~^ may appear anywhere in a ! "FOO BAR BAZ"
~{ construct.

(setq donestr "Done.~^ ~D warning~:P.~^ ~D error~:P.") 22.3.9.3 Tilde Newline: Ignored Newline
! "Done.~^ ~D warning~:P.~^ ~D error~:P."
(format nil donestr) ! "Done." Tilde immediately followed by a newline ignores the newline and any following non-newline
(format nil donestr 3) ! "Done. 3 warnings." whitespace 1 characters. With a :, the newline is ignored, but any following whitespace 1 is left
(format nil donestr 1 5) ! "Done. 1 warning. 5 errors." in place. With an @, the newline is left in place, but any following whitespace 1 is ignored. For
example:
If a pre x parameter is given, then termination occurs if the parameter is zero. (Hence ~^ is
equivalent to ~#^.) If two parameters are given, termination occurs if they are equal. If three (defun type-clash-error (fn nargs argnum right-type wrong-type)
parameters are given, termination occurs if the rst is less than or equal to the second and the (format *error-output*
second is less than or equal to the third. Of course, this is useless if all the pre x parameters are "~&~S requires its ~:[~:R~;~*~]~

constants; at least one of them should be a # or a V parameter. argument to be of type ~S,~%but it was called ~
with an argument of type ~S.~%"
If ~^ is used within a ~:{ construct, then it terminates the current iteration step because in the fn (eql nargs 1) argnum right-type wrong-type))
standard case it tests for remaining arguments of the current step only; the next iteration step (type-clash-error 'aref nil 2 'integer 'vector) prints:
commences immediately. ~:^ is used to terminate the iteration process. ~:^ may be used only AREF requires its second argument to be of type INTEGER,
if the command it would terminate is ~:{ or ~:@{. The entire iteration process is terminated if but it was called with an argument of type VECTOR.
and only if the sublist that is supplying the arguments for the current iteration step is the last NIL
sublist in the case of ~:{, or the last format argument in the case of ~:@{. ~:^ is not equivalent to (type-clash-error 'car 1 1 'list 'short-float) prints:
~#:^; the latter terminates the entire iteration if and only if no arguments remain for the current CAR requires its argument to be of type LIST,
iteration step. For example: but it was called with an argument of type SHORT-FLOAT.
NIL
(format nil "~:{~@?~:^...~}" '(("a") ("b"))) ! "a...b"
Note that in this example newlines appear in the output only as speci ed by the ~& and ~%
If appears within a control string being processed under the control of a ~? directive, but
~^ directives; the actual newline characters in the control string are suppressed because each is
not within any ~{ or ~< construct within that string, then the string being processed will be preceded by a tilde.
terminated, thereby ending processing of the ~? directive. Processing then continues within the
string containing the ~? directive at the point following that directive.
If ~^ appears within a ~[ or ~( construct, then all the commands up to the ~^ are properly se-
22.3.10 Additional Information about FORMAT Operations
lected or case-converted, the ~[ or ~( processing is terminated, and the outward search continues
for a ~{ or ~< construct to be terminated. For example:
(setq tellstr "~@(~@[~R~]~^ ~A!~)")
! "~@(~@[~R~]~^ ~A!~)"
(format nil tellstr 23) !"Twenty-three!"
(format nil tellstr nil "losers") !" Losers!"
(format nil tellstr 23 "losers") !
"Twenty-three losers!"

Printer 22{41 22{42 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

22.3.10.1 Nesting of FORMAT Operations (format nil "Look at the ~A!" y) !


"Look at the elephant!"
(setq n 3) ! 3
The case-conversion, conditional, iteration, and justi cation constructs can contain other format- (format nil "~D item~:P found." n) !
"3 items found."
ting constructs by bracketing them. These constructs must nest properly with respect to each (format nil "~R dog~:[s are~; is~] here." n (= n 1))
other. For example, it is not legitimate to put the start of a case-conversion construct in each arm ! "three dogs are here."
of a conditional and the end of the case-conversion construct outside the conditional: (format nil "~R dog~:*~[s are~; is~:;s are~] here." n)
(format nil "~:[abc~:@(def~;ghi~
! "three dogs are here."
(format nil "Here ~[are~;is~:;are~] ~:*~R pupp~:@P." n)
:@(jkl~]mno~)" x) ;Invalid!
! "Here are three puppies."
This notation is invalid because the ~[...~;...~] and ~(...~) constructs are not properly nested. (defun foo (x)
The processing indirection caused by the ~? directive is also a kind of nesting for the purposes of (format nil "~6,2F|~6,2,1,'*F|~6,2,,'?F|~6F|~,2F|~F"
this rule of proper nesting. It is not permitted to start a bracketing construct within a string pro- x x x x x x)) FOO !
cessed under control of a ~? directive and end the construct at some point after the ~? construct (foo 3.14159) !
" 3.14| 31.42| 3.14|3.1416|3.14|3.14159"
in the string containing that construct, or vice versa. For example, this situation is invalid: (foo -3.14159) !
" -3.14|-31.42| -3.14|-3.142|-3.14|-3.14159"
(foo 100.0) !
"100.00|******|100.00| 100.0|100.00|100.0"
(format nil "~@?ghi~)" "abc~@(def") ;Invalid! (foo 1234.0) !
"1234.00|******|??????|1234.0|1234.00|1234.0"

This notation is invalid because the ~? and ~(...~) constructs are not properly nested. (foo 0.006) !
" 0.01| 0.06| 0.01| 0.006|0.01|0.006"

(defun foo (x)


22.3.10.2 Missing and Additional FORMAT Arguments (format nil
"~9,2,1,,'*E|~10,3,2,2,'?,,'$E|~
The consequences are unde ned if no arg remains for a directive requiring an argument. However, ~9,3,2,-2,'%@E|~9,2E"
it is permissible for one or more args to remain unprocessed by a directive; such args are ignored. x x x x))
(foo 3.14159) !
" 3.14E+0| 31.42$-01|+.003E+03| 3.14E+0"
22.3.10.3 Additional FORMAT Parameters (foo -3.14159) !
" -3.14E+0|-31.42$-01|-.003E+03| -3.14E+0"
(foo 1100.0) !
" 1.10E+3| 11.00$+02|+.001E+06| 1.10E+3"
The consequences are unde ned if a format directive is given more parameters than it is described (foo 1100.0L0) !
" 1.10L+3| 11.00$+02|+.001L+06| 1.10L+3"
here as accepting. (foo 1.1E13) !
"*********| 11.00$+12|+.001E+16| 1.10E+13"
(foo 1.1L120) !
"*********|??????????|%%%%%%%%%|1.10L+120"

22.3.10.4 Unde ned FORMAT Modi er Combinations (foo 1.1L1200) !


"*********|??????????|%%%%%%%%%|1.10L+1200"

The consequences are unde ned if colon or at-sign modi ers are given to a directive in a combina- As an example of the e ects of varying the scale factor, the code
tion not speci cally described here as being meaningful. (dotimes (k 13)
(format t "~%Scale factor ~2D: |~13,6,2,VE|"
22.3.11 Examples of FORMAT (- k 5) (- k 5) 3.14159))

produces the following output:


(format nil "foo") !"foo" Scale factor -5: | 0.000003E+06|
(setq x 5) ! 5 Scale factor -4: | 0.000031E+05|
(format nil "The answer is ~D." x) !
"The answer is 5." Scale factor -3: | 0.000314E+04|
(format nil "The answer is ~3D." x) !"The answer is 5." Scale factor -2: | 0.003142E+03|
(format nil "The answer is ~3,'0D." x) !
"The answer is 005." Scale factor -1: | 0.031416E+02|
(format nil "The answer is ~:D." (expt 47 x)) Scale factor 0: | 0.314159E+01|
! "The answer is 229,345,007." Scale factor 1: | 3.141590E+00|
(setq y "elephant") !"elephant"

Printer 22{43 22{44 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Scale
Scale
factor
factor
2:
3:
|
|
31.41590E-01|
314.1590E-02|
copy-pprint-dispatch Function
Scale factor 4: | 3141.590E-03|
Scale factor 5: | 31415.90E-04| Syntax:
Scale factor 6: | 314159.0E-05| copy-pprint-dispatch &optional table ! new-table
Scale factor 7: | 3141590.E-06|

(defun foo (x)


Arguments and Values:
(format nil "~9,2,1,,'*G|~9,3,2,3,'?,,'$G|~9,3,2,0,'%G|~9,2G"
table |a pprint dispatch table , or nil.
x x x x)) new-table |a fresh pprint dispatch table .
(foo 0.0314159) !
" 3.14E-2|314.2$-04|0.314E-01| 3.14E-2"
(foo 0.314159) !
" 0.31
!
|0.314 |0.314 | 0.31 " Description:
(foo 3.14159) "
!
3.1 | 3.14 | 3.14 | 3.1 " Creates and returns a copy of the speci ed table , or of the value of *print-pprint-dispatch* if no
(foo 31.4159) " 31. | 31.4 | 31.4 | 31. " table is speci ed, or of the initial value of *print-pprint-dispatch* if nil is speci ed.
(foo 314.159) !
" 3.14E+2| 314. | 314. | 3.14E+2"
(foo 3141.59) !
" 3.14E+3|314.2$+01|0.314E+04| 3.14E+3"
!
Exceptional Situations:
(foo 3141.59L0)
(foo 3.14E12)
" 3.14L+3|314.2$+01|0.314L+04| 3.14L+3"
!
"*********|314.0$+10|0.314E+13| 3.14E+12"
Should signal an error of type type-error if table is not a pprint dispatch table .
(foo 3.14L120) !
"*********|?????????|%%%%%%%%%|3.14L+120"
(foo 3.14L1200)

(format nil
!
"*********|?????????|%%%%%%%%%|3.14L+1200"

"~10<foo~;bar~>") ! "foo bar"


formatter Macro
(format nil "~10:<foo~;bar~>") ! " foo bar"
(format nil "~10<foobar~>") ! " foobar"
! " foobar"
Syntax:
(format nil "~10:<foobar~>") formatter control-string ! function
(format nil "~10:@<foo~;bar~>") ! " foo bar "
(format nil "~10@<foobar~>") ! "foobar "
! " foobar "
Arguments and Values:
(format nil "~10:@<foobar~>") control-string |a format string ; not evaluated.
function|a function .
(FORMAT NIL "Written to ~A." #P"foo.bin")
! "Written to foo.bin." Description:
Returns a function which has behavior equivalent to:
22.3.12 Notes about FORMAT #'(lambda (*standard-output* &rest arguments)
(apply #'format t control-string
arguments)
Formatted output is performed not only by format, but by certain other functions that accept a arguments-tail )
format control the way format does. For example, error-signaling functions such as cerror accept where arguments-tail is either the tail of arguments which has as its car the argument that would
format controls . be processed next if there were more format directives in the control-string , or else nil if no more
Note that the meaning of nil and t as destinations to format are di erent than those of nil and t arguments follow the most recently processed argument.
as stream designators . Examples:
The ~^ should appear only at the beginning of a ~< clause, because it aborts the entire clause in
which it appears (as well as all following clauses). (funcall (formatter "~&~A~A") *standard-output* 'a 'b 'c)
. AB
! (C)

Printer 22{45 22{46 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Notes:
(format t (formatter "~&~A~A") 'a 'b 'c)
. AB (let ((*print-pretty* t))
! NIL (write object :stream s))
 (funcall (pprint-dispatch object) s object)
Exceptional Situations:
Might signal an error (at macro expansion time or at run time) if the argument is not a valid
format string .
See Also: pprint-exit-if-list-exhausted Local Macro
format
Syntax:
pprint-dispatch Function
pprint-exit-if-list-exhausted hno arguments i ! nil
Description:
Tests whether or not the list passed to the lexically current logical block has been exhausted; see
Syntax: Section 22.2.1.1 (Dynamic Control of the Arrangement of Output). If this list has been reduced
pprint-dispatch object &optional table ! function, found-p to nil, pprint-exit-if-list-exhausted terminates the execution of the lexically current logical block
except for the printing of the sux. Otherwise pprint-exit-if-list-exhausted returns nil.
Arguments and Values: Whether or not pprint-exit-if-list-exhausted is fbound in the global environment is
object |an object . implementation-dependent ; however, the restrictions on rede nition and shadowing of
table |a pprint dispatch table , or nil. The default is the value of *print-pprint-dispatch*. pprint-exit-if-list-exhausted are the same as for symbols in the COMMON-LISP package
which are fbound in the global environment . The consequences of attempting to use
function|a function designator . pprint-exit-if-list-exhausted outside of pprint-logical-block are unde ned.
found-p |a generalized boolean . Exceptional Situations:
Description: An error is signaled (at macro expansion time or at run time) if pprint-exit-if-list-exhausted is
used anywhere other than lexically within a call on pprint-logical-block. Also, the consequences
Retrieves the highest priority function in table that is associated with a type speci er that of executing pprint-if-list-exhausted outside of the dynamic extent of the pprint-logical-block
matches object . The function is chosen by nding all of the type speci ers in table that match which lexically contains it are unde ned.
the object and selecting the highest priority function associated with any of these type speci-
ers . If there is more than one highest priority function, an arbitrary choice is made. If no type
speci ers match the object , a function is returned that prints object using print-object.
See Also:
pprint-logical-block, pprint-pop.
The secondary value , found-p , is true if a matching type speci er was found in table , or false
otherwise.
If table is nil, retrieval is done in the initial pprint dispatch table .
A ected By:
The state of the table .
Exceptional Situations:
Should signal an error of type type-error if table is neither a pprint-dispatch-table nor nil.

Printer 22{47 22{48 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

pprint- ll, pprint-linear, pprint-tabular


pprint- ll, pprint-linear, pprint-tabular Function (pprint-tabular *standard-output* '(elm main maple center) nil nil 8))
Roads ELM MAIN
MAPLE CENTER
Syntax: Side E ects:
pprint- ll stream object &optional colon-p at-sign-p ! nil
Performs output to the indicated stream .
pprint-linear stream object &optional colon-p at-sign-p ! nil
pprint-tabular stream object &optional colon-p at-sign-p tabsize ! nil
A ected By:
The cursor position on the indicated stream , if it can be determined.
Arguments and Values: Notes:
stream|an output stream designator . The function pprint-tabular could be de ned as follows:
object |an object . (defun pprint-tabular (s list &optional (colon-p t) at-sign-p (tabsize nil))
colon-p |a generalized boolean . The default is true . (declare (ignore at-sign-p))
(when (null tabsize) (setq tabsize 16))
at-sign-p |a generalized boolean . The default is implementation-dependent . (pprint-logical-block (s list :prefix (if colon-p "(" "")
:suffix (if colon-p ")" ""))
tabsize |a non-negative integer . The default is 16. (pprint-exit-if-list-exhausted)

Description: (loop (write (pprint-pop) :stream s)


(pprint-exit-if-list-exhausted)
The functions pprint- ll, pprint-linear, and pprint-tabular specify particular ways of pretty (write-char #\Space s)
printing a list to stream. Each function prints parentheses around the output if and only (pprint-tab :section-relative 0 tabsize s)
if colon-p is true . Each function ignores its at-sign-p argument. (Both arguments are in- (pprint-newline :fill s))))
cluded even though only one is needed so that these functions can be used via ~/.../ and as
set-pprint-dispatch functions, as well as directly.) Each function handles abbreviation and the Note that it would have been inconvenient to specify this function using format, because of the
detection of circularity and sharing correctly, and uses write to print object when it is a non-list . need to pass its tabsize argument through to a ~:T format directive nested within an iteration
over a list.
If object is a list and if the value of *print-pretty* is false , each of these functions prints object
using a minimum of whitespace , as described in Section 22.1.3.5 (Printing Lists and Conses).
Otherwise (if object is a list and if the value of *print-pretty* is true ): pprint-indent Function
 The function pprint-linear prints a list either all on one line, or with each element on a
separate line. Syntax:
 The function pprint- ll prints a list with as many elements as possible on each line. pprint-indent relative-to n &optional stream ! nil
 The function pprint-tabular is the same as pprint- ll except that it prints the elements Arguments and Values:
so that they line up in columns. The tabsize speci es the column spacing in ems , which is relative-to |either :block or :current.
the total spacing from the leading edge of one column to the leading edge of the next. n|a real .
stream|an output stream designator . The default is standard output .
Examples:
Evaluating the following with a line length of 25 produces the output shown.
(progn (princ "Roads ")

Printer 22{49 22{50 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

pprint-logical-block
Description: Description:
pprint-indent speci es the indentation to use in a logical block on stream . If stream is a pretty Causes printing to be grouped into a logical block.
printing stream and the value of *print-pretty* is true , pprint-indent sets the indentation in the
innermost dynamically enclosing logical block; otherwise, pprint-indent has no e ect. The logical block is printed to the stream that is the value of the variable denoted by stream-
symbol . During the execution of the forms , that variable is bound to a pretty printing stream
N speci es the indentation in ems . If relative-to is :block, the indentation is set to the horizontal that supports decisions about the arrangement of output and then forwards the output to the
position of the rst character in the dynamically current logical block plus n ems . If relative-to is destination stream. All the standard printing functions (e.g., write, princ, and terpri) can be
:current, the indentation is set to the current output position plus n ems . (For robustness in the used to print output to the pretty printing stream . All and only the output sent to this pretty
face of variable-width fonts, it is advisable to use :current with an n of zero whenever possible.) printing stream is treated as being in the logical block.
N can be negative; however, the total indentation cannot be moved left of the beginning of the The pre x speci es a pre x to be printed before the beginning of the logical block. The per-line-
line or left of the end of the rightmost per-line pre x|an attempt to move beyond one of these pre x speci es a pre x that is printed before the block and at the beginning of each new line
limits is treated the same as an attempt to move to that limit. Changes in indentation caused by in the block. The :prefix and :pre-line-prefix arguments are mutually exclusive. If neither
pprint-indent do not take e ect until after the next line break. In addition, in miser mode all calls :prefix nor :per-line-prefix is speci ed, a pre x of the null string is assumed.
to pprint-indent are ignored, forcing the lines corresponding to the logical block to line up under
the rst character in the block. The sux speci es a sux that is printed just after the logical block.
Exceptional Situations: The object is normally a list that the body forms are responsible for printing. If object is not a
list , it is printed using write. (This makes it easier to write printing functions that are robust
An error is signaled if relative-to is any object other than :block or :current. in the face of malformed arguments.) If *print-circle* is non-nil and object is a circular (or
See Also: shared) reference to a cons , then an appropriate \#n#" marker is printed. (This makes it easy
to write printing functions that provide full support for circularity and sharing abbreviation.)
Section 22.3.5.3 (Tilde I: Indent) If *print-level* is not nil and the logical block is at a dynamic nesting depth of greater than
*print-level* in logical blocks, \#" is printed. (This makes easy to write printing functions that
pprint-logical-block Macro
provide full support for depth abbreviation.)
If either of the three conditions above occurs, the indicated output is printed on stream-symbol
and the body forms are skipped along with the printing of the :prefix and :suffix. (If the body
Syntax: forms are not to be responsible for printing a list, then the rst two tests above can be turned o
by supplying nil for the object argument.)
pprint-logical-block (stream-symbol object &key pre x per-line-pre x sux )
fdeclarationg* fformg* In addition to the object argument of pprint-logical-block, the arguments of the standard
printing functions (such as write, print, prin1, and pprint, as well as the arguments of the
! nil standard format directives such as ~A, ~S, (and ~W) are all checked (when necessary) for circularity
Arguments and Values: and sharing. However, such checking is not applied to the arguments of the functions write-line,
write-string, and write-char or to the literal text output by format. A consequence of this is
stream-symbol |a stream variable designator . that you must use one of the latter functions if you want to print some literal text in the output
object |an object ; evaluated. that is not supposed to be checked for circularity or sharing.
:prefix|a string ; evaluated. Complicated defaulting behavior; see below.
The body forms of a pprint-logical-block form must not perform any side-e ects on the sur-
rounding environment; for example, no variables must be assigned which have not been bound
:per-line-prefix|a string ; evaluated. Complicated defaulting behavior; see below. within its scope.
:suffix|a string ; evaluated. The default is the null string . The pprint-logical-block macro may be used regardless of the value of *print-pretty*.
declaration|a declare expression ; not evaluated. A ected By:
forms |an implicit progn . *print-circle*, *print-level*.

Printer 22{51 22{52 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

pprint-newline
Exceptional Situations: :linear
An error of type type-error is signaled if any of the :suffix, :prefix, or :per-line-prefix is This speci es a \linear-style" conditional newline . A line break is inserted if and only if the
supplied but does not evaluate to a string . immediately containing section cannot be printed on one line. The e ect of this is that line
An error is signaled if :prefix and :pre-line-prefix are both used. breaks are either inserted at every linear-style conditional newline in a logical block or at
none of them.
pprint-logical-block and the pretty printing stream it creates have dynamic extent . The conse-
quences are unde ned if, outside of this extent, output is attempted to the pretty printing stream :miser
it creates.
This speci es a \miser-style" conditional newline . A line break is inserted if and only if the
It is also unspeci ed what happens if, within this extent, any output is sent directly to the immediately containing section cannot be printed on one line and miser style is in e ect in
underlying destination stream. the immediately containing logical block. The e ect of this is that miser-style conditional
newlines act like linear-style conditional newlines, but only when miser style is in e ect. Miser
See Also: style is in e ect for a logical block if and only if the starting position of the logical block is
pprint-pop, pprint-exit-if-list-exhausted, Section 22.3.5.2 (Tilde Less-Than-Sign: Logical Block) less than or equal to *print-miser-width* ems from the right margin.
Notes: :fill
One reason for using the pprint-logical-block macro when the value of *print-pretty* is
nil would be to allow it to perform checking for dotted lists , as well as (in conjunction with This speci es a \ ll-style" conditional newline . A line break is inserted if and only if either
pprint-pop) checking for *print-level* or *print-length* being exceeded. (a) the following section cannot be printed on the end of the current line, (b) the preceding
section was not printed on a single line, or (c) the immediately containing section cannot be
Detection of circularity and sharing is supported by the pretty printer by in essence performing printed on one line and miser style is in e ect in the immediately containing logical block. If
requested output twice. On the rst pass, circularities and sharing are detected and the actual a logical block is broken up into a number of subsections by ll-style conditional newlines,
outputting of characters is suppressed. On the second pass, the appropriate \#n=" and \#n#" the basic e ect is that the logical block is printed with as many subsections as possible on
markers are inserted and characters are output. This is why the restriction on side-e ects is each line. However, if miser style is in e ect, ll-style conditional newlines act like linear-style
necessary. Obeying this restriction is facilitated by using pprint-pop, instead of an ordinary pop conditional newlines.
when traversing a list being printed by the body forms of the pprint-logical-block form .)
:mandatory

pprint-newline Function This speci es a \mandatory-style" conditional newline . A line break is always inserted. This
implies that none of the containing sections can be printed on a single line and will therefore
trigger the insertion of line breaks at linear-style conditional newlines in these sections .
Syntax: When a line break is inserted by any type of conditional newline, any blanks that immediately
pprint-newline kind &optional stream ! nil precede the conditional newline are omitted from the output and indentation is introduced at the
beginning of the next line. By default, the indentation causes the following line to begin in the
Arguments and Values: same horizontal position as the rst character in the immediately containing logical block. (The
kind |one of :linear, :fill, :miser, or :mandatory. indentation can be changed via pprint-indent.)
stream|a stream designator . The default is standard output . There are a variety of ways unconditional newlines can be introduced into the output (i.e., via
terpri or by printing a string containing a newline character). As with mandatory conditional
Description: newlines, this prevents any of the containing sections from being printed on one line. In general,
If stream is a pretty printing stream and the value of *print-pretty* is true , a line break is in- when an unconditional newline is encountered, it is printed out without suppression of the
serted in the output when the appropriate condition below is satis ed; otherwise, pprint-newline preceding blanks and without any indentation following it. However, if a per-line pre x has been
has no e ect. speci ed (see pprint-logical-block), this pre x will always be printed no matter how a newline
originates.
Kind speci es the style of conditional newline. This parameter is treated as follows:

Printer 22{53 22{54 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Examples:  If *print-circle* is non-nil , and the remaining list is a circular (or shared) reference, then
See Section 22.2.2 (Examples of using the Pretty Printer). \. " is printed followed by an appropriate \#n#" marker. (This catches instances of cdr
circularity and sharing in lists.)
Side E ects: If either of the three conditions above occurs, the indicated output is printed on the pretty
Output to stream. printing stream created by the immediately containing pprint-logical-block and the execution
A ected By: of the immediately containing pprint-logical-block is terminated except for the printing of the
sux.
*print-pretty*, *print-miser*. The presence of containing logical blocks. The placement of
newlines and conditional newlines. If pprint-logical-block is given a `list' argument of nil|because it is not processing a list|
Exceptional Situations: pprint-pop can still be used to obtain support for *print-length*. In this situation, the rst and
third tests above are disabled and pprint-pop always returns nil. See Section 22.2.2 (Examples of
An error of type type-error is signaled if kind is not one of :linear, :fill, :miser, or :mandatory. using the Pretty Printer)|speci cally, the pprint-vector example.
See Also: Whether or not pprint-pop is fbound in the global environment is implementation-dependent ;
Section 22.3.5.1 (Tilde Underscore: Conditional Newline), Section 22.2.2 (Examples of using the however, the restrictions on rede nition and shadowing of pprint-pop are the same as for symbols
Pretty Printer) in the COMMON-LISP package which are fbound in the global environment . The consequences of
attempting to use pprint-pop outside of pprint-logical-block are unde ned.
pprint-pop Local Macro Side E ects:
Might cause output to the pretty printing stream associated with the lexically current logical
block.
Syntax: A ected By:
pprint-pop hno arguments i ! object *print-length*, *print-circle*.
Arguments and Values: Exceptional Situations:
object |an element of the list being printed in the lexically current logical block , or nil. An error is signaled (either at macro expansion time or at run time) if a usage of pprint-pop
Description: occurs where there is no lexically containing pprint-logical-block form .
Pops one element from the list being printed in the lexically current logical block , obeying The consequences are unde ned if pprint-pop is executed outside of the dynamic extent of this
*print-length* and *print-circle* as described below. pprint-logical-block.
Each time pprint-pop is called, it pops the next value o the list passed to the lexically current
logical block and returns it. However, before doing this, it performs three tests:
See Also:
pprint-exit-if-list-exhausted, pprint-logical-block.
 If the remaining `list' is not a list , \. " is printed followed by the remaining `list.' (This Notes:
makes it easier to write printing functions that are robust in the face of malformed argu- It is frequently a good idea to call pprint-exit-if-list-exhausted before calling pprint-pop.
ments.)
 If *print-length* is non-nil , and pprint-pop has already been called *print-length* times
within the immediately containing logical block, \..." is printed. (This makes it easy to write
printing functions that properly handle *print-length*.)

Printer 22{55 22{56 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

print-object
pprint-tab Function Arguments and Values:
object |an object .
Syntax: stream|a stream .
pprint-tab kind colnum colinc &optional stream ! nil Description:
Arguments and Values: The generic function print-object writes the printed representation of object to stream. The
function print-object is called by the Lisp printer ; it should not be called by the user.
kind |one of :line, :section, :line-relative, or :section-relative.
colnum|a non-negative integer . Each implementation is required to provide a method on the class standard-object and on the
class structure-object. In addition, each implementation must provide methods on enough other
colinc |a non-negative integer . classes so as to ensure that there is always an applicable method . Implementations are free to add
methods for other classes . Users may write methods for print-object for their own classes if they
stream|an output stream designator . do not wish to inherit an implementation-dependent method .
Description: The method on the class structure-object prints the object in the default #S notation; see
Speci es tabbing to stream as performed by the standard ~T format directive. If stream is a Section 22.1.3.12 (Printing Structures).
pretty printing stream and the value of *print-pretty* is true , tabbing is performed; otherwise, Methods on print-object are responsible for implementing their part of the semantics of the
pprint-tab has no e ect. printer control variables , as follows:
The arguments colnum and colinc correspond to the two parameters to ~T and are in terms
of ems . The kind argument speci es the style of tabbing. It must be one of :line (tab as by *print-readably*
~T), :section (tab as by ~:T, but measuring horizontal positions relative to the start of the
dynamically enclosing section), :line-relative (tab as by ~@T), or :section-relative (tab as All methods for print-object must obey *print-readably*. This includes both user-de ned
by ~:@T, but measuring horizontal positions relative to the start of the dynamically enclosing methods and implementation-de ned methods. Readable printing of structures and standard
section). objects is controlled by their print-object method, not by their make-load-form method .
Similarity for these objects is application dependent and hence is de ned to be whatever these
Exceptional Situations: methods do; see Section 3.2.4.2 (Similarity of Literal Objects).
An error is signaled if kind is not one of :line, :section, :line-relative, or :section-relative.
*print-escape*
See Also: Each method must implement *print-escape*.
pprint-logical-block
*print-pretty*
print-object Standard Generic Function The method may wish to perform specialized line breaking or other output conditional on the
value of *print-pretty*. For further information, see (for example) the macro pprint- ll. See
also Section 22.2.1.4 (Pretty Print Dispatch Tables) and Section 22.2.2 (Examples of using
Syntax: the Pretty Printer).
print-object object stream ! object
*print-length*
Method Signatures: Methods that produce output of inde nite length must obey *print-length*. For further
print-object (object standard-object ) stream
information, see (for example) the macros pprint-logical-block and pprint-pop. See also
print-object (object structure-object ) stream Section 22.2.1.4 (Pretty Print Dispatch Tables) and Section 22.2.2 (Examples of using the
Pretty Printer).

Printer 22{57 22{58 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

*print-level* Arguments and Values:


The printer takes care of *print-level* automatically, provided that each method handles object |an object ; evaluated.
exactly one level of structure and calls write (or an equivalent function ) recursively if there stream|a stream designator ; evaluated.
are more structural levels. The printer's decision of whether an object has components (and
therefore should not be printed when the printing depth is not less than *print-level*) is type |a generalized boolean ; evaluated.
implementation-dependent . In some implementations its print-object method is not called; in identity |a generalized boolean ; evaluated.
others the method is called, and the determination that the object has components is based
on what it tries to write to the stream. forms |an implicit progn .
*print-circle* Description:
When the value of *print-circle* is true , a user-de ned print-object method can print objects Outputs a printed representation of object on stream, beginning with \#<" and ending with
to the supplied stream using write, prin1, princ, or format and expect circularities to be \>". Everything output to stream by the body forms is enclosed in the the angle brackets. If
detected and printed using the #n# syntax. If a user-de ned print-object method prints to a type is true , the output from forms is preceded by a brief description of the object 's type and a
stream other than the one that was supplied, then circularity detection starts over for that space character. If identity is true , the output from forms is followed by a space character and a
stream . See *print-circle*. representation of the object 's identity, typically a storage address.
If either type or identity is not supplied, its value is false . It is valid to omit the body forms . If
*print-base*, *print-radix*, *print-case*, *print-gensym*, and *print-array* type and identity are both true and there are no body forms , only one space character separates
the type and the identity.
These printer control variables apply to speci c types of objects and are handled by the
methods for those objects . Examples:
If these rules are not obeyed, the results are unde ned. ;; Note that in this example, the precise form of the output ;; is implementation-dependent .
In general, the printer and the print-object methods should not rebind the print control variables (defmethod print-object ((obj airplane) stream)
as they operate recursively through the structure, but this is implementation-dependent . (print-unreadable-object (obj stream :type t :identity t)
(princ (tail-number obj) stream)))
In some implementations the stream argument passed to a print-object method is not the original
stream , but is an intermediate stream that implements part of the printer. methods should (prin1-to-string my-airplane)
therefore not depend on the identity of this stream . !
or
"#<Airplane NW0773 36000123135>"
!
See Also: "#<FAA:AIRPLANE NW0773 17>"

pprint- ll, pprint-logical-block, pprint-pop, write, *print-readably*, *print-escape*, Exceptional Situations:


*print-pretty*, *print-length*, Section 22.1.3 (Default Print-Object Methods), Section 22.1.3.12 If *print-readably* is true , print-unreadable-object signals an error of type print-not-readable
(Printing Structures), Section 22.2.1.4 (Pretty Print Dispatch Tables), Section 22.2.2 (Examples without printing anything.
of using the Pretty Printer)

print-unreadable-object Macro
set-pprint-dispatch Function
Syntax:
Syntax: set-pprint-dispatch type-speci er function &optional priority table ! nil
print-unreadable-object (object stream &key type identity ) fformg* ! nil
Arguments and Values:
type-speci er |a type speci er .

Printer 22{59 22{60 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

write, prin1, print, pprint, princ


function|a function , a function name , or nil. ! object
priority |a real . The default is 0. prin1 object &optional output-stream ! object
table |a pprint dispatch table . The default is the value of *print-pprint-dispatch*. princ object &optional output-stream ! object
Description: print object &optional output-stream ! object
Installs an entry into the pprint dispatch table which is table . pprint object &optional output-stream ! hno values i
Type-speci er is the key of the entry. The rst action of set-pprint-dispatch is to remove any Arguments and Values:
pre-existing entry associated with type-speci er . This guarantees that there will never be two
entries associated with the same type speci er in a given pprint dispatch table . Equality of type object |an object .
speci ers is tested by equal. output-stream|an output stream designator . The default is standard output .
Two values are associated with each type speci er in a pprint dispatch table : a function and a pri- array |a generalized boolean .
ority . The function must accept two arguments: the stream to which output is sent and the object
to be printed. The function should pretty print the object to the stream. The function can assume base |a radix .
that object satis es the type given by type-speci er . The function must obey *print-readably*.
Any values returned by the function are ignored. case |a symbol of type (member :upcase :downcase :capitalize).
Priority is a priority to resolve con icts when an object matches more than one entry. circle |a generalized boolean .
It is permissible for function to be nil. In this situation, there will be no type-speci er entry in escape |a generalized boolean .
table after set-pprint-dispatch returns.
gensym|a generalized boolean .
Exceptional Situations: length|a non-negative integer , or nil.
An error is signaled if priority is not a real .
level |a non-negative integer , or nil.
Notes:
Since pprint dispatch tables are often used to control the pretty printing of Lisp code, it is com- lines |a non-negative integer , or nil.
mon for the type-speci er to be an expression of the form miser-width|a non-negative integer , or nil.
(cons car-type cdr-type ) pprint-dispatch|a pprint dispatch table .
This signi es that the corresponding object must be a cons cell whose car matches the type pretty |a generalized boolean .
speci er car-type and whose cdr matches the type speci er cdr-type . The cdr-type can be omitted
in which case it defaults to t. radix |a generalized boolean .
readably |a generalized boolean .
write, prin1, print, pprint, princ Function right-margin|a non-negative integer , or nil.
stream|an output stream designator . The default is standard output .
Syntax: Description:
write object &key array base case circle escape gensym
length level lines miser-width pprint-dispatch write, prin1, princ, print, and pprint write the printed representation of object to output-stream.
pretty radix readably right-margin stream write is the general entry point to the Lisp printer . For each explicitly supplied keyword param-

Printer 22{61 22{62 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

write, prin1, print, pprint, princ


eter named in Figure 22{7, the corresponding printer control variable is dynamically bound to A ected By:
its value while printing goes on; for each keyword parameter in Figure 22{7 that is not explicitly *standard-output*, *terminal-io*, *print-escape*, *print-radix*, *print-base*, *print-circle*,
supplied, the value of the corresponding printer control variable is the same as it was at the time *print-pretty*, *print-level*, *print-length*, *print-case*, *print-gensym*, *print-array*,
write was invoked. Once the appropriate bindings are established , the object is output by the Lisp *read-default- oat-format*.
printer .
See Also:
Parameter Corresponding Dynamic Variable readtable-case, Section 22.3.4 (FORMAT Printer Operations)
array *print-array*
base *print-base* Notes:
case *print-case* The functions prin1 and print do not bind *print-readably*.
circle *print-circle*
escape *print-escape* 
(prin1 object output-stream)
gensym *print-gensym* (write object :stream output-stream :escape t)
length *print-length*
level *print-level* (princ object output-stream)
lines *print-lines*  (write object stream output-stream :escape nil :readably nil)
miser-width *print-miser-width*
pprint-dispatch *print-pprint-dispatch*
pretty *print-pretty* (print object output-stream)
radix *print-radix*  (progn (terpri output-stream)
readably *print-readably* (write object :stream output-stream
right-margin *print-right-margin* :escape t)
(write-char #\space output-stream))
Figure 22{7. Argument correspondences for the WRITE function. (pprint object output-stream)

prin1, princ, print, and pprint implicitly bind certain print parameters to particular values.  (write object :stream output-stream :escape t :pretty t)

The remaining parameter values are taken from *print-array*, *print-base*, *print-case*,
*print-circle*, *print-escape*, *print-gensym*, *print-length*, *print-level*, *print-lines*,
*print-miser-width*, *print-pprint-dispatch*, *print-pretty*, *print-radix*, and
*print-right-margin*. write-to-string,
Function
prin1-to-string, princ-to-string
prin1 produces output suitable for input to read. It binds *print-escape* to true .
princ is just like prin1 except that the output has no escape characters . It binds *print-escape* Syntax:
to false and *print-readably* to false . The general rule is that output from princ is intended to
look good to people, while output from prin1 is intended to be acceptable to read. write-to-string object &key array base case circle escape gensym
length level lines miser-width pprint-dispatch
print is just like prin1 except that the printed representation of object is preceded by a newline pretty radix readably right-margin
and followed by a space.
! string
pprint is just like print except that the trailing space is omitted and object is printed with the
*print-pretty* ag non-nil to produce pretty output. prin1-to-string object ! string
Output-stream speci es the stream to which output is to be sent. princ-to-string object ! string

Printer 22{63 22{64 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

write-to-string, prin1-to-string, princ-to-string


Arguments and Values: The meanings and defaults for the keyword arguments to write-to-string are the same as those
object |an object . for write.
array |a generalized boolean . Examples:
base |a radix . (prin1-to-string "abc") ! "\"abc\""
case |a symbol of type (member :upcase :downcase :capitalize).
(princ-to-string "abc") ! "abc"
circle |a generalized boolean . A ected By:
*print-escape*, *print-radix*, *print-base*, *print-circle*, *print-pretty*, *print-level*,
escape |a generalized boolean . *print-length*, *print-case*, *print-gensym*, *print-array*, *read-default- oat-format*.
gensym|a generalized boolean . See Also:
length|a non-negative integer , or nil. write
level |a non-negative integer , or nil. Notes:
lines |a non-negative integer , or nil. (write-to-string object fkey argument g*
)
 (with-output-to-string (#1=#:string-stream)
miser-width|a non-negative integer , or nil. (write object :stream #1# fkey argument g*
))

pprint-dispatch|a pprint dispatch table . (princ-to-string object


)
pretty |a generalized boolean .  (with-output-to-string (string-stream)
(princ objectstring-stream))
radix |a generalized boolean .
(prin1-to-string object
)
readably |a generalized boolean .  (with-output-to-string (string-stream)

right-margin|a non-negative integer , or nil. (prin1 objectstring-stream))

string |a string .
Description:
write-to-string, prin1-to-string, and princ-to-string are used to create a string consisting of
print-array Variable
the printed representation of object . Object is e ectively printed as if by write, prin1, or princ,
respectively, and the characters that would be output are made into a string . Value Type:
write-to-string is the general output function. It has the ability to specify all the parameters a generalized boolean .
applicable to the printing of object . Initial Value:
prin1-to-string acts like write-to-string with :escape t, that is, escape characters are written implementation-dependent .
where appropriate.
princ-to-string acts like write-to-string with :escape nil :readably nil. Thus no escape charac-
Description:
ters are written. Controls the format in which arrays are printed. If it is false , the contents of arrays other than
strings are never printed. Instead, arrays are printed in a concise form using #< that gives enough
All other keywords that would be speci ed to write-to-string are default values when information for the user to be able to identify the array , but does not include the entire array
prin1-to-string or princ-to-string is invoked. contents. If it is true , non-string arrays are printed using #(...), #*, or #nA syntax.

Printer 22{65 22{66 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

A ected By: . 17 16 15 14
The implementation . ! NIL
(dolist (pb '(2 3 8 10 16))
See Also: (let ((*print-radix* t) ;print the integer 10 and
Section 2.4.8.3 (Sharpsign Left-Parenthesis), Section 2.4.8.20 (Sharpsign Less-Than-Sign) (*print-base* pb)) ;the ratio 1/10 in bases 2,
(format t "~&~S ~S~%" 10 1/10))) ;3, 8, 10, 16
. #b1010 #b1/1010
print-base, print-radix Variable . #3r101 #3r1/101
. #o12 #o1/12
. 10. #10r1/10
Value Type: . #xA #x1/A
! NIL
*print-base*|a radix . *print-radix*|a generalized boolean .
Initial Value: A ected By:
Might be bound by format, and write, write-to-string.
The initial value of *print-base* is 10. The initial value of *print-radix* is false .
Description: See Also:
format, write, write-to-string
*print-base* and *print-radix* control the printing of rationals . The value of *print-base* is
called the current output base .
The value of *print-base* is the radix in which the printer will print rationals . For radices above print-case Variable
10, letters of the alphabet are used to represent digits above 9.

If the value of *print-radix* is true , the printer will print a radix speci er to indicate the radix
in which it is printing a rational number. The radix speci er is always printed using lowercase
Value Type:
One of the symbols :upcase, :downcase, or :capitalize.
letters. If *print-base* is 2, 8, or 16, then the radix speci er used is #b, #o, or #x, respectively.
For integers , base ten is indicated by a trailing decimal point instead of a leading radix speci er;
for ratios , #10r is used.
Initial Value:
The symbol :upcase.
Examples: Description:
(let ((*print-base* 24.) (*print-radix* t)) The value of *print-case* controls the case (upper, lower, or mixed) in which to print any
(print 23.)) uppercase characters in the names of symbols when vertical-bar syntax is not used.
. #24rN *print-case* has an e ect at all times when the value of *print-escape* is false . *print-case*
! 23
also has an e ect when the value of *print-escape* is true unless inside an escape context (i.e.,
(setq *print-base* 10) !
10
unless between vertical-bars or after a slash ).
(setq *print-radix* nil) !NIL
(dotimes (i 35)
(let ((*print-base* (+ i 2))) ;print the decimal number 40
Examples:
(write 40) ;in each base from 2 to 36 (defun test-print-case ()
(if (zerop (mod i 10)) (terpri) (format t " ")))) (dolist (*print-case* '(:upcase :downcase :capitalize))
. 101000 (format t "~&~S ~S~%" 'this-and-that '|And-something-elSE|)))
. 1111 220 130 104 55 50 44 40 37 34 ! TEST-PC
. 31 2C 2A 28 26 24 22 20 1J 1I ;; Although the choice of which characters to escape is specified by
. 1H 1G 1F 1E 1D 1C 1B 1A 19 18 ;; *PRINT-CASE*, the choice of how to escape those characters

Printer 22{67 22{68 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

;; (i.e., whether single escapes or multiple escapes are used) If true , a user-de ned print-object method can print objects to the supplied stream using write,
;; is implementation-dependent. The examples here show two of the prin1, princ, or format and expect circularities and sharing to be detected and printed using the
;; many valid ways in which escaping might appear. #n# syntax. If a user-de ned print-object method prints to a stream other than the one that was
(test-print-case) ;Implementation A supplied, then circularity detection starts over for that stream .
. THIS-AND-THAT |And-something-elSE|
. this-and-that a\n\d-\s\o\m\e\t\h\i\n\g-\e\lse Note that implementations should not use #n# notation when the Lisp reader would automatically
. This-And-That A\n\d-\s\o\m\e\t\h\i\n\g-\e\lse assure sharing without it (e.g., as happens with interned symbols ).
! NIL
Examples:
(test-print-case) ;Implementation B
. THIS-AND-THAT |And-something-elSE| (let ((a (list 1 2 3)))
. this-and-that a|nd-something-el|se (setf (cdddr a) a)
. This-And-That A|nd-something-el|se
! NIL
(let ((*print-circle* t))
(write a)
See Also: :done))
. #1=(1 2 3 . #1#)
write ! :DONE

Notes: See Also:


read normally converts lowercase characters appearing in symbols to corresponding uppercase write
characters, so that internally print names normally contain only uppercase characters.
If *print-escape* is true , lowercase characters in the name of a symbol are always printed in low- Notes:
ercase, and are preceded by a single escape character or enclosed by multiple escape characters; An attempt to print a circular structure with *print-circle* set to nil may lead to looping
uppercase characters in the name of a symbol are printed in upper case, in lower case, or in mixed behavior and failure to terminate.
case so as to capitalize words, according to the value of *print-case*. The convention for what
print-escape
constitutes a \word" is the same as for string-capitalize.
Variable
print-circle Variable Value Type:
a generalized boolean .
Value Type: Initial Value:
a generalized boolean .
true .
Initial Value: Description:
false .
If false , escape characters and package pre xes are not output when an expression is printed.
Description: If true , an attempt is made to print an expression in such a way that it can be read again to
Controls the attempt to detect circularity and sharing in an object being printed. produce an equal expression . (This is only a guideline; not a requirement. See *print-readably*.)
If false , the printing process merely proceeds by recursive descent without attempting to detect For more speci c details of how the value of *print-escape* a ects the printing of certain types ,
circularity and sharing. see Section 22.1.3 (Default Print-Object Methods).
If true , the printer will endeavor to detect cycles and sharing in the structure to be printed, and
to use #n= and #n# syntax to indicate the circularities or shared components.

Printer 22{69 22{70 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

print-level, print-length
Examples: print-level, print-length Variable
(let ((*print-escape* t)) (write #\a))
.
!
#\a Value Type:
#\a
(let ((*print-escape* nil)) (write #\a))
a non-negative integer , or nil.
. a
!
Initial Value:
#\a
nil.
A ected By: Description:
princ, prin1, format *print-level* controls how many levels deep a nested object will print. If it is false , then no
See Also: control is exercised. Otherwise, it is an integer indicating the maximum level to be printed. An
object to be printed is at level 0; its components (as of a list or vector ) are at level 1; and so on.
write, readtable-case If an object to be recursively printed has components and is at a level equal to or greater than the
Notes: value of *print-level*, then the object is printed as \#".
princ e ectively binds *print-escape* to false . prin1 e ectively binds *print-escape* to true . *print-length* controls how many elements at a given level are printed. If it is false , there is no
limit to the number of components printed. Otherwise, it is an integer indicating the maximum
number of elements of an object to be printed. If exceeded, the printer will print \..." in place
print-gensym Variable of the other elements . In the case of a dotted list , if the list contains exactly as many elements as
the value of *print-length*, the terminating atom is printed rather than printing \..."
Value Type: *print-level* and *print-length* a ect the printing of an any object printed with a list-like
syntax. They do not a ect the printing of symbols , strings , and bit vectors .
a generalized boolean .
Initial Value: Examples:
true . (setq a '(1 (2 (3 (4 (5 (6))))))) ! (1 (2 (3 (4 (5 (6))))))
Description: (dotimes (i 8)

Controls whether the pre x \#:" is printed before apparently uninterned symbols . The pre x is (let ((*print-level* i))
printed before such symbols if and only if the value of *print-gensym* is true . (format t "~&~D -- ~S~%" i a)))
. 0 -- #
Examples: . 1 -- (1 #)
. 2 -- (1 (2 #))
(let ((*print-gensym* nil)) . 3 -- (1 (2 (3 #)))
(print (gensym))) . 4 -- (1 (2 (3 (4 #))))
. G6040 . 5 -- (1 (2 (3 (4 (5 #)))))
! #:G6040 . 6 -- (1 (2 (3 (4 (5 (6))))))
. 7 -- (1 (2 (3 (4 (5 (6))))))
See Also: ! NIL
write, *print-escape*
(setq a '(1 2 3 4 5 6)) !(1 2 3 4 5 6)
(dotimes (i 7)
(let ((*print-length* i))

Printer 22{71 22{72 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

(format t "~&~D -- ~S~%" i a))) Description:


. 0 -- (...) When the value of *print-lines* is other than nil, it is a limit on the number of output lines
. 1 -- (1 ...) produced when something is pretty printed. If an attempt is made to go beyond that many lines,
. 2 -- (1 2 ...) \.." is printed at the end of the last line followed by all of the suxes (closing delimiters) that
. 3 -- (1 2 3 ...) are pending to be printed.
. 4 -- (1 2 3 4 ...)
. 5 -- (1 2 3 4 5 6) Examples:
. 6 -- (1 2 3 4 5 6)
! NIL (let ((*print-right-margin* 25) (*print-lines* 3))
(pprint '(progn (setq a 1 b 2 c 3 d 4))))
. (PROGN (SETQ A 1
. B 2
(dolist (level-length '((0 1) (1 1) (1 2) (1 3) (1 4) . C 3 ..))
(2 1) (2 2) (2 3) (3 2) (3 3) (3 4)))
(let ((*print-level* (first level-length))
! hno values i
(*print-length* (second level-length))) Notes:
(format t "~&~D ~D -- ~S~%" The \.." notation is intentionally di erent than the \..." notation used for level abbreviation, so
*print-level* *print-length*
'(if (member x y) (+ (car x) 3) '(foo . #(a b c d "Baz"))))))
that the two di erent situations can be visually distinguished.
. 0 1 -- # This notation is used to increase the likelihood that the Lisp reader will signal an error if an
. 1 1 -- (IF ...) attempt is later made to read the abbreviated output. Note however that if the truncation occurs
. 1 2 -- (IF # ...) in a string , as in "This string has been trunc..", the problem situation cannot be detected later
. 1 3 -- (IF # # ...) and no such error will be signaled.
. 1 4 -- (IF # # #)

print-miser-width
. 2 1 -- (IF ...)
. 2 2 -- (IF (MEMBER X ...) ...)
. 2 3 -- (IF (MEMBER X Y) (+ # 3) ...)
Variable
. 3 2 -- (IF (MEMBER X ...) ...)
. 3 3 -- (IF (MEMBER X Y) (+ (CAR X) 3) ...)
. 3 4 -- (IF (MEMBER X Y) (+ (CAR X) 3) '(FOO . #(A B C D ...)))
Value Type:
! NIL a non-negative integer , or nil.
See Also: Initial Value:
write implementation-dependent
Description:
print-lines Variable If it is not nil, the pretty printer switches to a compact style of output (called miser style)
whenever the width available for printing a substructure is less than or equal to this many ems .

Value Type:
a non-negative integer , or nil.
Initial Value:
nil.

Printer 22{73 22{74 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

print-pprint-dispatch Variable Examples:


(setq *print-pretty* 'nil)! NIL
Value Type: (progn (write '(let ((a 1) (b 2) (c 3)) (+ a b c))) nil)
a pprint dispatch table . . (LET ((A 1) (B 2) (C 3)) (+ A B C))
! NIL
Initial Value: (let ((*print-pretty* t))
implementation-dependent , but the initial entries all use a special class of priorities that have the (progn (write '(let ((a 1) (b 2) (c 3)) (+ a b c))) nil))
. (LET ((A 1)
property that they are less than every priority that can be speci ed using set-pprint-dispatch, so .
that the initial contents of any entry can be overridden. .
(B 2)
(C 3))
Description: . (+ A B C))
!
The pprint dispatch table which currently controls the pretty printer . NIL
;; Note that the first two expressions printed by this next form
See Also: ;; differ from the second two only in whether escape characters are printed.

*print-pretty*, Section 22.2.1.4 (Pretty Print Dispatch Tables) ;; In all four cases, extra whitespace is inserted by the pretty printer.
(flet ((test (x)
Notes: (let ((*print-pretty* t))

The intent is that the initial value of this variable should cause `traditional' pretty printing of (print x)

code . In general, however, you can put a value in *print-pprint-dispatch* that makes pretty- (format t "~%~S " x)

printed output look exactly like non-pretty-printed output. Setting *print-pretty* to true just (terpri) (princ x) (princ " ")

causes the functions contained in the current pprint dispatch table to have priority over normal (format t "~%~A " x))))

print-object methods; it has no magic way of enforcing that those functions actually produce (test '#'(lambda () (list "a" # 'c #'d))))
. #'(LAMBDA ()
pretty output. For details, see Section 22.2.1.4 (Pretty Print Dispatch Tables). . (LIST "a" # 'C #'D))
. #'(LAMBDA ()

print-pretty
. (LIST "a" # 'C #'D))
Variable . #'(LAMBDA ()
. (LIST a b 'C #'D))
. #'(LAMBDA ()
Value Type: . (LIST a b 'C #'D))
a generalized boolean . ! NIL

Initial Value:
implementation-dependent . See Also:
write
Description:
Controls whether the Lisp printer calls the pretty printer .
If it is false , the pretty printer is not used and a minimum of whitespace 1 is output when printing print-readably Variable
an expression.
If it is true , the pretty printer is used, and the Lisp printer will endeavor to insert extra whites- Value Type:
pace 1 where appropriate to make expressions more readable. a generalized boolean .
*print-pretty* has an e ect even when the value of *print-escape* is false .

Printer 22{75 22{76 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

print-readably
Initial Value: (setf (gethash table 1) 'one) ! ONE
false . (setf (gethash table 2) 'two) ! TWO
Description: ;; Implementation A
If *print-readably* is true , some special rules for printing objects go into e ect. Speci cally, (let ((*print-readably* t)) (print table))
printing any object O1 produces a printed representation that, when seen by the Lisp reader while Error: Can't print #<HASH-TABLE EQL 0/120 32005763> readably.
the standard readtable is in e ect, will produce an object O2 that is similar to O1. The printed
representation produced might or might not be the same as the printed representation produced ;; Implementation B
when *print-readably* is false . If printing an object readably is not possible, an error of type ;; No standardized #S notation for hash tables is defined,
print-not-readable is signaled rather than using a syntax (e.g., the \#<" syntax) that would not ;; but there might be an implementation-defined notation.
be readable by the same implementation . If the value of some other printer control variable is (let ((*print-readably* t)) (print table))
such that these requirements would be violated, the value of that other variable is ignored. . #S(HASH-TABLE :TEST EQL :SIZE 120 :CONTENTS (1 ONE 2 TWO))
! #<HASH-TABLE EQL 0/120 32005763>
Speci cally, if *print-readably* is true , printing proceeds as if *print-escape*, *print-array*,
and *print-gensym* were also true , and as if *print-length*, *print-level*, and *print-lines* ;; Implementation C
were false . ;; Note that #. notation can only be used if *READ-EVAL* is true.
;; If *READ-EVAL* were false, this same implementation might have to
If *print-readably* is false , the normal rules for printing and the normal interpretations of other ;; signal an error unless it had yet another printing strategy to fall
printer control variables are in e ect. ;; back on.
Individual methods for print-object, including user-de ned methods , are responsible for imple- (let ((*print-readably* t)) (print table))
menting these requirements. . #.(LET ((HASH-TABLE (MAKE-HASH-TABLE)))
. (SETF (GETHASH 1 HASH-TABLE) ONE)
If *read-eval* is false and *print-readably* is true , any such method that would output a . (SETF (GETHASH 2 HASH-TABLE) TWO)
reference to the \#." reader macro will either output something else or will signal an error (as . HASH-TABLE)
described above). ! #<HASH-TABLE EQL 0/120 32005763>

Examples: See Also:


write, print-unreadable-object
(let ((x (list "a" '\a (gensym) '((a (b (c))) d e f g)))
(*print-escape* nil) Notes:
(*print-gensym* nil) The rules for \similarity " imply that #A or #( syntax cannot be used for arrays of element type
(*print-level* 3) other than t. An implementation will have to use another syntax or signal an error of type
(*print-length* 3)) print-not-readable.
(write x)

print-right-margin
(let ((*print-readably* t))
(terpri)
(write x) Variable
:done))
. (a a G4581 ((A #) D E ...))
. ("a" |a| #:G4581 ((A (B (C))) D E F G)) Value Type:
! :DONE a non-negative integer , or nil.
;; This is setup code is shared between the examples Initial Value:
;; of three hypothetical implementations which follow. nil.
(setq table (make-hash-table)) !
#<HASH-TABLE EQL 0/120 32005763>

Printer 22{77 22{78 Programming Language|Common Lisp


Version 15.17, X3J13/94-101. Version 15.17, X3J13/94-101.
Wed 11-May-1994 6:57pm EDT Wed 11-May-1994 6:57pm EDT

Description: See Also:


If it is non-nil , it speci es the right margin (as integer number of ems ) to use when the pretty print-not-readable, Chapter 9 (Conditions)
printer is making layout decisions.
If it is nil, the right margin is taken to be the maximum line length such that output can be
displayed without wraparound or truncation. If this cannot be determined, an implementation- format Function
dependent value is used.
Notes: Syntax:
This measure is in units of ems in order to be compatible with implementation-de ned variable- format destination control-string &rest args ! result
width fonts while still not requiring the language to provide support for fonts.
Arguments and Values:
destination|nil, t, a stream , or a string with a ll pointer .
print-not-readable Condition Type control-string |a format control .
args |format arguments for control-string .
Class Precedence List: result |if destination is non-nil , then nil; otherwise, a string .
print-not-readable, error, serious-condition, condition, t
Description: Description:
The type print-not-readable consists of error conditions that occur during output while format produces formatted output by outputting the characters of control-string and observing
*print-readably* is true , as a result of attempting to write a printed representation with the that a tilde introduces a directive. The character after the tilde, possibly preceded by pre x
Lisp printer that would not be correctly read back with the Lisp reader . The object which could parameters and modi ers, speci es what kind of formatting is desired. Most directives use one or
not be printed is initialized by the :object initialization argument to make-condition, and is more elements of args to create their output.
accessed by the function print-not-readable-object. If destination is a string , a stream , or t, then the result is nil. Otherwise, the result is a string
containing the `output.'
See Also:
print-not-readable-object format is useful for producing nicely formatted text, producing good-looking messages, and so on.
format can generate and return a string or output to destination.
print-not-readable-object Function For details on how the control-string is interpreted, see Section 22.3 (Formatted Output).
A ected By:
*standard-output*, *print-escape*, *print-radix*, *print-base*, *print-circle*,
Syntax: *print-pretty*, *print-level*, *print-length*, *print-case*, *print-gensym*, *print-array*.
print-not-readable-object condition ! object
Exceptional Situations:
Arguments and Values: If destination is a string with a ll pointer , the consequences are unde ned if destructive modi ca-
condition|a condition of type print-not-readable. tions are performed directly on the string during the dynamic extent of the call.
object |an object . See Also:
Description: write, Section 13.1.10 (Documentation of Implementation-De ned Scripts)
Returns the object that could not be printed readably in the situation represented by condition.

Printer 22{79 22{80 Programming Language|Common Lisp

You might also like