The format function produces nicely formatted text and messages. It can generate and return a string or output to a specified destination.
The control-string argument to format is a format control, which can be either:
formatter macro)When the control-string is a function, it is called with the output stream as its first argument and the data arguments as remaining arguments. The function performs necessary output and returns any unused arguments.
Control-strings consist of simple text (characters) and embedded directives.
A directive structure includes:
~):) and at-sign (@) modifiersPrefix parameters use signed decimal notation or single-quote followed by a character. For example: ~5,'0d prints an integer with leading zeros in five columns, or ~5,'*d for leading asterisks.
"~S" ;S directive with no parameters or modifiers
"~3,-4:@s" ;S directive with parameters 3 and -4,
;with colon and at-sign flags
"~,+4S" ;First parameter omitted (default), second is 4
format sends output to the specified destination:
The term "arg" refers to the next item from the arguments to be processed. format directives do not bind printer control variables (*print-...*) except as specified in individual directive descriptions.
The ~C format directive handles character output with various modifier flags controlling the display style.
~C (Basic)
Prints a character using write-char if it is simple. Non-simple characters use implementation-defined abbreviated formatting.
Examples:
(format nil "~C" #\A) => "A"(format nil "~C" #\Space) => " "~:C (Pretty)
Displays printing characters normally, while "spelling out" non-printing characters. For simple non-printing characters, the output shows the character's name via char-name. Non-simple non-printing characters use implementation-defined output.
Examples:
(format nil "~:C" #\A) => "A"(format nil "~:C" #\Space) => "Space"~:@C (Key Description)
Extends ~:C output by noting "unusual shift keys on the keyboard." Designed for user prompts about expected keypresses, with output potentially varying by implementation and I/O devices.
~@C (Lisp Reader Syntax)
Outputs characters in #\ syntax readable by the Lisp reader, binding *print-escape* to t.
~% outputs a #\Newline character, thereby terminating the current output line and beginning a new one. ~n% outputs n newlines. No argument is consumed.
Unless it can be determined that the output stream is already at the beginning of a line, ~& outputs a newline. ~n& calls fresh-line and then outputs n-1 additional newlines. ~0& produces no output.
~| outputs a page separator character, if possible. ~n| repeats this n times.
~~ outputs a tilde. ~n~ outputs n tildes.
The ~R directive prints arguments in various radix formats.
With Prefix Parameters:
~radix,mincol,padchar,commachar,comma-intervalR
When ~nR is used with a radix parameter n, the argument displays in that base. The ~D directive is equivalent to ~10R.
When the first parameter n is supplied, ~R binds: *print-escape* to false, *print-radix* to false, *print-base* to n, and *print-readably* to false.
Without Prefix Parameters: The argument must be an integer and supports four distinct formats:
~R - Cardinal English number (example: 4 becomes "four")~:R - Ordinal English number (example: 4 becomes "fourth")~@R - Roman numeral (example: 4 becomes "IV")~:@R - Old Roman numeral (example: 4 becomes "IIII")When no parameters are supplied, *print-base* binds to 10.
Examples:
(format nil "~,,' ,4:B" 13) => "1101"
(format nil "~,,' ,4:B" 17) => "1 0001"
(format nil "~19,0,' ,4:B" 3333) => "0000 1101 0000 0101"
(format nil "~3,,,' ,2:R" 17) => "1 22"
(format nil "~,,'|,2:D" #xFFFF) => "6|55|35"
The ~D directive prints an integer argument in decimal radix without a decimal point.
Full form: ~mincol,padchar,commachar,comma-intervalD
~mincolD specifies minimum column width, padding left with spaces if needed.~mincol,padcharD allows substitution of a custom pad character.If arg is not an integer, it is printed in ~A format and decimal base.
Binds *print-escape* to false, *print-radix* to false, *print-base* to 10, *print-readably* to false.
~B is like ~D but prints in binary radix (base 2).
Full form: ~mincol,padchar,commachar,comma-intervalB
Binds *print-escape* to false, *print-radix* to false, *print-base* to 2, *print-readably* to false.
~O is like ~D but prints in octal radix (base 8).
Full form: ~mincol,padchar,commachar,comma-intervalO
Binds *print-escape* to false, *print-radix* to false, *print-base* to 8, *print-readably* to false.
~X is like ~D but prints in hexadecimal radix (base 16).
Full form: ~mincol,padchar,commachar,comma-intervalX
Binds *print-escape* to false, *print-radix* to false, *print-base* to 16, *print-readably* to false.
Full syntax: ~w,d,k,overflowchar,padcharF
Parameters:
Output Formatting:
The directive outputs exactly w characters. Leading padding characters fill the field left side. A minus sign appears for negative values; a plus sign for non-negative values only with the @ modifier. The output includes one decimal point with d fractional digits, rounded appropriately. A single leading zero appears before the decimal point only if the magnitude is less than one and w != d+1.
Overflow Handling:
When the scaled value cannot fit in w characters: if overflowchar is provided, w copies of that character print instead; otherwise, the value prints using additional characters as needed.
Omitted Parameters:
d digits follow the decimal.w, with no trailing zeros.prin1 behavior for numbers with magnitude zero or between 10^-3 and 10^7.If w is omitted and printing would require over 100 digits, implementations may use exponential notation (as ~E).
Non-Float Arguments:
~wD.Binds *print-escape* and *print-readably* to false.
Full syntax: ~w,d,e,k,overflowchar,padchar,exponentcharE
Parameters:
Formatting Rules: The output always contains exactly w characters, padded on the left as needed. For negative arguments, a minus sign prints; for non-negative, a plus sign prints only with the @ modifier.
Scale Factor Behavior:
Exponent Representation:
The exponent character prints first (or the default marker from prin1), followed by a sign and e digits for the power of ten.
Overflow Handling: If it is impossible to print the value in the required format in a field of width w, either overflow repetition occurs or the value expands beyond w characters as needed.
Optional Parameters: When w is omitted, field width adjusts to eliminate leading padding. Omitting d removes digit constraints. Omitting e uses minimum necessary digits. Omitting all three produces free-format exponential-notation output.
Rational numbers coerce to single float. Complex numbers or non-numeric objects print using ~wD.
Binds *print-escape* and *print-readably* to false.
Full syntax: ~w,d,e,k,overflowchar,padchar,exponentcharG
Parameters:
Format Selection Logic: The directive calculates an integer n where 10^(n-1) <= |arg| < 10^n.
Let ee = e + 2 (or 4 if e is omitted), and ww = w - ee (or nil if w is omitted).
When d is omitted, calculate q (digits needed without information loss or leading/trailing zeros), then d = (max q (min n 7)).
Let dd = d - n.
Conditional Output:
~ww,dd,,overflowchar,padcharF~ee@T (note: scale factor k is not passed to ~F)~w,d,e,k,overflowchar,padchar,exponentcharEThe @ modifier applies to both cases only if provided to ~G.
Binds *print-escape* and *print-readably* to false.
Full syntax: ~d,n,w,padchar$
Parameters:
Output Processing:
@ modifier.: modifier places the sign before padding; otherwise it appears after.w is specified and total output characters are fewer than w, padchar copies fill the gap.n digits for the integer portion (with leading zeros if needed), a decimal point, then d rounded fraction digits.If the magnitude of arg is so large that more than m digits would have to be printed, where m is the larger of w and 100, then an implementation is free to print the number using exponential notation instead.
Rational numbers coerce to single float. Complex numbers or non-numeric objects print using ~wD.
Binds *print-escape* and *print-readably* to false.
The ~A directive prints an argument without escape characters, functioning similarly to princ.
Basic Behavior:
The colon modifier (~:A) changes nil display to "()" for top-level arguments, though nested nil values within composite structures remain as "nil".
Padding Control:
~mincol,colinc,minpad,padcharA
Padding is applied on the right, or left with the @ modifier.
Binds *print-escape* to false, *print-readably* to false.
~S is like ~A but prints arg with escape characters (as by prin1 rather than princ). The output is therefore suitable for input to read.
Accepts all arguments and modifiers that ~A supports.
Binds *print-escape* to t.
The ~W directive prints any object while respecting all printer control variables, similar to the write function. It properly integrates with depth abbreviation by maintaining the depth counter rather than resetting it.
~W does not accept parameters.
Modifiers:
:): Binds *print-pretty* to true.@): Binds *print-length* and *print-level* to nil.~W provides automatic support for the detection of circularity and sharing. When *print-circle* is not nil and the directive encounters a circular or shared reference, it substitutes an appropriate #n# marker.
~_ (no modifiers): Equivalent to (pprint-newline :linear)~@_ (@ modifier): Equivalent to (pprint-newline :miser)~:_ (: modifier): Equivalent to (pprint-newline :fill)~:@_ (both modifiers): Equivalent to (pprint-newline :mandatory)Syntax: ~<...~:>
This directive functions as a call to pprint-logical-block. The argument is processed similarly to the list parameter of pprint-logical-block, automatically handling non-list arguments and detecting circularity, sharing, and depth abbreviation.
Control String Segmentation:
The nested control string can be divided into up to three segments using ~; directives:
~<prefix~;body~;suffix~:>
~@; specifies a per-line prefix instead of a simple prefix~:<...~:>): prefix and suffix default to "(" and ")" respectivelyBody Segment:
The body accepts any format string applied to list elements. Elements are extracted using pprint-pop, supporting malformed lists and detecting circularity, sharing, and length abbreviation. Within the body, ~^ behaves like pprint-exit-if-list-exhausted.
Fill-style formatting: Using ~:@> terminator automatically inserts fill-style conditional newlines after blank groups in the body.
At-sign modifier: ~@<...~:> passes the entire remaining argument list to the directive, consuming all arguments regardless of actual use.
An error occurs if ~<...~> nests directives like ~W, ~_, ~<...~:>, ~I, or ~:T. The ~<...~:;...~> form cannot coexist with these directives in the same format string.
~nI: Equivalent to (pprint-indent :block n) (n defaults to zero)~n:I: Equivalent to (pprint-indent :current n) (n defaults to zero)Syntax: ~/name/
User-defined functions can be invoked within format strings. The name follows these rules:
: or ::, the portion before identifies the package, the portion after identifies the symbol: or ::, the entire name is looked up in the COMMON-LISP-USER package/) cannot appear in nameThe directive calls the resolved function with these arguments:
The function should print the argument appropriately. Any values returned by the function are ignored.
Three standard functions are designed for use with this directive: pprint-linear, pprint-fill, and pprint-tabular.
Basic Tabulation (~T):
~colnum,colincT spaces the cursor to a specified column.
colnumcolnum, advances to colnum + k*colinc (smallest positive integer k)colinc is zero and cursor is already at/beyond colnum, outputs no spacesColumn Position Detection:
When the current column position cannot be directly determined, format attempts deduction by noting directives that reset position (like ~%, ~&), counting characters emitted since the reset, assuming the destination started at column zero, or as a fallback, outputting two spaces.
Relative Tabulation (~@T):
~colrel,colinc@T performs relative tabulation:
colrel spaces initiallycolinc~3,8@T outputs three spaces then moves to a standard multiple-of-eight tab stopcolinc is ignored and exactly colrel spaces outputColon Modifier (~:T): Tabbing computes relative to where the containing section begins rather than column zero. Parameters represent units of ems (both defaulting to 1):
~n,m:T equals (pprint-tab :section n m)~n,m:@T equals (pprint-tab :section-relative n m)Syntax: ~mincol,colinc,minpad,padchar<str~>
This directive justifies text produced by processing str within a field at least mincol columns wide. The str parameter may be divided into segments using ~; separators, with spacing distributed evenly between text segments.
: modifier: Introduces spacing before the first text segment.@ modifier: Adds spacing after the last segment.Parameters:
mincol: Minimum field width (default: 0)colinc: Column increment (default: 1)minpad: Minimum padding characters between segments (default: 0)padchar: Padding character used (default: space)When total required width exceeds mincol, the actual width becomes mincol + k*colinc for the smallest non-negative integer k.
~:; Clause Termination:
When the first clause ends with ~:; instead of ~;, it receives special handling: it is processed but excluded from spacing/padding calculations. The padded result outputs if it fits the current line; otherwise, the first clause text outputs first. A prefix parameter n with ~:; requires n spare character positions. A second prefix parameter specifies line width, overriding the stream's natural width.
The ~^ directive can prematurely terminate clause processing; only completely processed clauses participate in justification.
If line width cannot be determined, format uses 72 as the default line length.
~> terminates a ~<. The consequences of using it elsewhere are undefined.
Basic Ignore: ~* skips the next argument. ~n* ignores the following n arguments.
Backup Navigation: ~:* backs up one position in the argument list. ~n:* backs up by n arguments.
Absolute Positioning: ~n@* jumps to the nth argument (0-indexed). ~@* returns to the first argument.
Within ~{ iteration constructs, all navigation operations are relative to the arguments being processed within that iteration context.
Syntax: ~[str0~;str1~;...~;strn~]
Selects and processes one control string from a set of clauses separated by ~; and terminated by ~].
The _arg_th clause is selected (first clause is numbered 0). If a prefix parameter is provided as ~n[, that parameter determines clause selection instead of consuming an argument. When the argument is out of range, no clause executes and no error occurs.
Default Case: Using ~:; before the final clause creates a default case.
~:[alternative~;consequent~] selects based on argument truthiness: alternative if false, consequent otherwise.
~@[consequent~] tests the argument. If true, the argument remains unconsumed and consequent processes. If false, the argument is consumed and nothing executes.
Examples:
(setq *print-level* nil *print-length* 5)
(format nil
"~@[ print level = ~D~]~@[ print length = ~D~]"
*print-level* *print-length*)
=> " print length = 5"
(setq foo "Items:~#[ none~; ~S~; ~S and ~S~
~:;~@{~#[~; and~] ~S~^ ,~}~].")
(format nil foo) => "Items: none."
(format nil foo 'foo) => "Items: FOO."
(format nil foo 'foo 'bar) => "Items: FOO and BAR."
~] terminates a ~[. The consequences of using it elsewhere are undefined.
Basic Form: ~{str~}
The argument should be a list, which is used as a set of arguments as if for a recursive call to format. The control string str repeats over list elements.
(format nil "The winners are:~{ ~S~}."
'(fred harry jill))
=> "The winners are: FRED HARRY JILL."
Sublist Form: ~:{str~}
The argument should be a list of sublists. At each repetition step, one sublist is used as the set of arguments for processing str.
(format nil "Pairs:~:{ <~S,~S>~} ."
'((a 1) (b 2) (c 3)))
=> "Pairs: <A,1> <B,2> <C,3>."
Arguments Form: ~@{str~}
All the remaining arguments are used as the list of arguments for the iteration.
(format nil "Pairs:~@{ <~S,~S>~} ." 'a 1 'b 2 'c 3)
=> "Pairs: <A,1> <B,2> <C,3>."
Combined Form: ~:@{str~}
All the remaining arguments are used, and each one must be a list.
(format nil "Pairs:~:@{ <~S,~S>~} ."
'(a 1) '(b 2) '(c 3))
=> "Pairs: <A,1> <B,2> <C,3>."
Termination:
n limits repetitions to at most n times~^ directive terminates iteration prematurely~:} instead of ~} forces at least one processing iterationstr means an argument provides the control string~} terminates a ~{. The consequences of using it elsewhere are undefined.
Basic Syntax (~?): Consumes two arguments: a format control string and a list of arguments for that control string.
(format nil "~? ~D" "<~A ~D>" '("Foo" 5) 7)
=> "<Foo 5> 7"
When excess arguments exist in the list, they are ignored.
With @ Modifier (~@?): Consumes only one direct argument -- the control string. Arguments for the nested control come from the outer format call's remaining arguments.
(format nil "~@? ~D" "<~A ~D>" "Foo" 5 7)
=> "<Foo 5> 7"
(format nil "~@? ~D" "<~A ~D>" "Foo" 5 14 7)
=> "<Foo 5> 14"
Syntax: ~(str~)
The contained control string is processed and its output undergoes case conversion.
| Directive | Behavior |
|---|---|
~( | Converts all uppercase characters to lowercase |
~:( | Capitalizes all words, as if by string-capitalize |
~@( | Capitalizes the first word and converts remaining text to lowercase |
~:@( | Converts all lowercase characters to uppercase |
Examples:
(format nil "~@R ~(~@R~)" 14 14)
=> "XIV xiv"
(defun f (n) (format nil "~@(~R~) error~:P detected." n))
(f 0) => "Zero errors detected."
(f 1) => "One error detected."
(f 23) => "Twenty-three errors detected."
When case conversions appear nested, the outer conversion dominates.
~) terminates a ~(. The consequences of using it elsewhere are undefined.
~P: If the argument is not eql to the integer 1, a lowercase "s" is printed. If 1, nothing is printed. Floating-point 1.0 prints the "s".~:P: Backs up one argument using ~:*, then applies the same logic.~@P: Prints "y" if the argument equals 1, or "ies" if it does not.~:@P: Combines both modifiers -- backs up first, then prints "y" or "ies".Examples:
(format nil "~D tr~:@P/~D win~:P" 7 1) => "7 tries/1 win"
(format nil "~D tr~:@P/~D win~:P" 1 0) => "1 try/0 wins"
(format nil "~D tr~:@P/~D win~:P" 1 3) => "1 try/3 wins"
~; separates clauses in ~[ and ~< constructs. The consequences of using it elsewhere are undefined.
The ~^ directive terminates enclosing constructs based on argument availability or parameter conditions.
Basic Behavior: If there are no more arguments remaining to be processed, then the immediately enclosing ~{ or ~< construct is terminated. If no such construct exists, the entire formatting operation ends.
Parameter-Based Termination:
~#^ (tests for remaining arguments)Usage in Iteration Constructs:
Within ~:{ constructs, ~^ terminates only the current iteration step. To end the entire iteration, use ~:^, which works exclusively with ~:{ or ~:@{ directives.
Examples:
(format nil "Done.~^ ~D warning~:P.~^ ~D error~:P.")
=> "Done."
(format nil "Done.~^ ~D warning~:P.~^ ~D error~:P." 3)
=> "Done. 3 warnings."
(format nil "~15<~S~;~^~S~;~^~S~>" 'foo 'bar 'baz)
=> "FOO BAR BAZ"
The directive can appear within ~?, ~[, and ~( constructs, where it terminates processing and searches outward for associated ~{ or ~< constructs.
The tilde character followed immediately by a newline handles whitespace in format control strings:
~<newline>): Ignores the newline and any following non-newline whitespace characters.~:<newline>): The newline is ignored, but trailing whitespace remains in the output.~@<newline>): The newline appears in the output, but any following whitespace is removed.Example:
(defun type-clash-error (fn nargs argnum right-type wrong-type)
(format *error-output*
"~&~S requires its ~:[~:R~;~*~]~
argument to be of type ~S,~%but it was called ~
with an argument of type ~S.~%"
fn (eql nargs 1) argnum right-type wrong-type))
(type-clash-error 'aref nil 2 'integer 'vector)
;; prints:
;; AREF requires its second argument to be of type INTEGER,
;; but it was called with an argument of type VECTOR.
Newlines appear in the output only as specified by the ~& and ~% directives; the actual newline characters in the control string are suppressed because each is preceded by a tilde.
Can you improve this documentation?Edit on GitHub
cljdoc builds & hosts documentation for Clojure/Script libraries
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |