Programming Language - Common Lisp 22. Printer
Programming Language - Common Lisp 22. Printer
Programming Language - Common Lisp 22. Printer
22. Printer
22.1 The Lisp Printer In addition to the printer control variables , the following additional dened names relate to or
aect 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 prexes.
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 eects 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".
nil might be printed as () when *print-pretty* is true and printer escaping is enabled. 22.1.3.3.2 Eect of Readtable Case on the Lisp Printer
22.1.3.3.1 Package Prexes for Symbols When printer escaping is disabled, or the characters under consideration are not already quoted
specically by single escape or multiple escape syntax, the readtable case of the current readtable
Package prexes are printed if necessary. The rules for package prexes are as follows. When aects 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 prex ; :upcase
otherwise, it is printed with a package prex . When the readtable case is :upcase, uppercase characters are printed in the case specied
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 prex, 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 specied 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 prex 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 aected 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
22.1.3.3.2.1 Examples of Eect 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 aected 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
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 aected 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 aected by *print-level*, *print-length*, and *print-circle*. If *print-readably* is true , the vector prints in an implementation-dened 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 eectively 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-dened manner; see the vari-
able *print-readably*. In particular, this may be important for arrays having some dimension
. #\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 redene 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 eect 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 .
(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 specier .
333 3333 The values associated with a key are a \function" (specically, a function designator or nil) and a
44444444444444 44444 \numerical priority" (specically, 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-dened
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 specier 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 dened 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. Dened names related to pretty printing.
Figure 22{5 identies 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 ~/.../ ~
The following two forms illustrate the denition 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 species 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
eect. #<Lucy and
Mark Bob . Dan>)
(set-pprint-dispatch '(cons (member quote)) ()
#'(lambda (s list) Note that a pretty printing function for a structure is dierent 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 dierent
(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 species 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 dened 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)
This nal example shows how to dene a pretty printing function for a user dened 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 species 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 dierent 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.
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 specied 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-specic printer control variables for each format directive,
but they may neither bind any standard printer control variables not specied 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 specied 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 species 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 modier
ags.
A directive consists of a tilde , optional prex 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 modiers, 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 modier. The case of the directive character implementation-dened , abbreviated format. For example,
is ignored. Prex 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 prex 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 eect 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 prex parameter; it represents the number of args remaining simple and not printing , what is spelled out is implementation-dened . For example,
to be processed. When used within a recursive format, in the context of ~? or ~{, the # prex !
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 modiers. !
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 prex 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
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 @ modier causes the number's sign to be printed always; the default is to print it only if
the number is negative. The : modier 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 : modier is given to any of these directives, the commachar
is printed between groups of comma-interval digits.
n prints arg in radix n . The modier
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 prex parameters are given to ~R, then a dierent 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 .
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 eect 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.
modier 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 @ modier 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 eect, a value is chosen for k signicant 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.
are printed rst k zeros and then d +k signicant 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 eect a value is chosen for w In either case, an @ modier 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 eect 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 dierence is that the ~E directive arg is not negative, then a plus sign is printed if and only if the @ modier was supplied. If the
always prints a plus or minus sign in front of the exponent, while prin1 omits the plus sign if the : modier 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.
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 modier, ~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 modier, ~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 modier (~: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 modiers, ~ 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).
@ modier 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 @ modier 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 ~<...~:> species 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 modiers ~<prex ~;body ~;sux ~:> by ~; directives. If the rst section is terminated by ~@;, it species
that ~A does. a per-line prex rather than a simple prex. The prex and sux cannot contain format di-
rectives. An error is signaled if either the prex 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 prex and the sux default to the
null string. If the colon modier is used (i.e., ~:<...~:>), the prex 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
detection of circularity, sharing, and length abbreviation. Within the body segment, ~^ acts like boolean that is true if the at-sign modier was used. The remaining arguments consist of any
pprint-exit-if-list-exhausted. parameters specied 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 specically 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 modier 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 dier-
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: Justication). (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 dened functions can be called from within a format string by using the directive ~/name /. If the colon modier is used with the ~T directive, the tabbing computation is done relative to
The colon modier, the at-sign modier, and arbitrarily many parameters can be specied 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 modier was used, and a generalized
22.3.6.2 Tilde Less-Than-Sign: Justication 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 Justication
This justies the text produced by processing str within a eld at least mincol columns wide. str terminates a ~<. The consequences of using it elsewhere are undened.
may be divided up into segments with ~;, in which case the spacing is evenly divided between the ~>
text segments.
With no modiers, the leftmost text segment is left justied in the eld, and the rightmost text 22.3.7 FORMAT Control-Flow Operations
segment is right justied. If there is only one text element, as a special case, it is right justied.
The : modier causes spacing to be introduced before the rst text segment; the @ modier
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 justied. 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 justied. 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 prex 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 prex 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 prex 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 justied 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 prex 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.
~@[ 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 undened. ! "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 prex
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 prex 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~}."
~@( capitalizes just the rst word and forces the rest to lower case.
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."
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 justication. ~^ 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 prex 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 prex 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 specied 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!"
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"
The consequences are undened if colon or at-sign modiers are given to a directive in a combina- As an example of the eects of varying the scale factor, the code
tion not specically 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))
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|
(format nil
!
"*********|?????????|%%%%%%%%%|3.14L+1200"
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 redenition 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 undened.
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 specier 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 speciers in table that match which lexically contains it are undened.
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
speciers 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 specier was found in table , or false
otherwise.
If table is nil, retrieval is done in the initial pprint dispatch table .
Aected 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.
pprint-logical-block
Description: Description:
pprint-indent species 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 eect. 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 species 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 prex species a prex to be printed before the beginning of the logical block. The per-line-
line or left of the end of the rightmost per-line prex|an attempt to move beyond one of these prex species a prex 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 eect until after the next line break. In addition, in miser mode all calls :prefix nor :per-line-prefix is specied, a prex 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 species 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 prex per-line-prex 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-eects 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. Aected By:
forms |an implicit progn . *print-circle*, *print-level*.
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 species 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 eect 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 undened if, outside of this extent, output is attempted to the pretty printing stream :miser
it creates.
This species a \miser-style" conditional newline . A line break is inserted if and only if the
It is also unspecied 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 eect in
underlying destination stream. the immediately containing logical block. The eect of this is that miser-style conditional
newlines act like linear-style conditional newlines, but only when miser style is in eect. Miser
See Also: style is in eect 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 species 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 eect 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 eect 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-eects is each line. However, if miser style is in eect, 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 species 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 satised; otherwise, pprint-newline preceding blanks and without any indentation following it. However, if a per-line prex has been
has no eect. specied (see pprint-logical-block), this prex will always be printed no matter how a newline
originates.
Kind species the style of conditional newline. This parameter is treated as follows:
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 Eects: 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
Aected 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)|specically, 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 redenition 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 undened.
pprint-pop Local Macro Side Eects:
Might cause output to the pretty printing stream associated with the lexically current logical
block.
Syntax: Aected 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 undened 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*.)
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
Species 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 eect. 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 species 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-dened
by ~:@T, but measuring horizontal positions relative to the start of the dynamically enclosing methods and implementation-dened 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 dened 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 indenite 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).
print-unreadable-object Macro
set-pprint-dispatch Function
Syntax:
Syntax: set-pprint-dispatch type-specier function &optional priority table ! nil
print-unreadable-object (object stream &key type identity ) fformg* ! nil
Arguments and Values:
type-specier |a type specier .
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 species the stream to which output is to be sent. princ-to-string object ! string
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 eectively 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 specied 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.
Aected 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: Aected 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 specier to indicate the radix
in which it is printing a rational number. The radix specier 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 specier used is #b, #o, or #x, respectively.
For integers , base ten is indicated by a trailing decimal point instead of a leading radix specier;
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 eect at all times when the value of *print-escape* is false . *print-case*
! 23
also has an eect 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
;; (i.e., whether single escapes or multiple escapes are used) If true , a user-dened 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-dened 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
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.
Aected 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 eectively binds *print-escape* to false . prin1 eectively 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* aect the printing of an any object printed with a list-like
syntax. They do not aect 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 prex \#:" is printed before apparently uninterned symbols . The prex 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))
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.
*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 eect even when the value of *print-escape* is false .
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 eect. Specically, (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 eect, 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>
Specically, 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 eect. ;; back on.
Individual methods for print-object, including user-dened 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>
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>