2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2006
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
9 @section Pretty Printing
11 @c FIXME::martin: Review me!
13 @cindex pretty printing
14 The module @code{(ice-9 pretty-print)} provides the procedure
15 @code{pretty-print}, which provides nicely formatted output of Scheme
16 objects. This is especially useful for deeply nested or complex data
17 structures, such as lists and vectors.
19 The module is loaded by simply saying.
22 (use-modules (ice-9 pretty-print))
25 This makes the procedure @code{pretty-print} available. As an example
26 how @code{pretty-print} will format the output, see the following:
29 (pretty-print '(define (foo) (lambda (x)
30 (cond ((zero? x) #t) ((negative? x) -x) (else
31 (if (= x 1) 2 (* x x x)))))))
37 (else (if (= x 1) 2 (* x x x))))))
40 @deffn {Scheme Procedure} pretty-print obj [port] [keyword-options]
41 Print the textual representation of the Scheme object @var{obj} to
42 @var{port}. @var{port} defaults to the current output port, if not
45 The further @var{keyword-options} are keywords and parameters as
49 @item @nicode{#:display?} @var{flag}
50 If @var{flag} is true then print using @code{display}. The default is
51 @code{#f} which means use @code{write} style. (@pxref{Writing})
53 @item @nicode{#:per-line-prefix} @var{string}
54 Print the given @var{string} as a prefix on each line. The default is
57 @item @nicode{#:width} @var{columns}
58 Print within the given @var{columns}. The default is 79.
64 @node Formatted Output
65 @section Formatted Output
66 @cindex formatted output
68 @c For reference, in this section escapes like ~a are given in
69 @c @nicode, to give code font in TeX etc, but leave them unadorned in
72 @c The idea is to reduce clutter around what's shown, and avoid any
73 @c possible confusion over whether the ` ' quotes are part of what
74 @c should be entered. (In particular for instance of course ' is
75 @c meaningful in a format string, introducing a char parameter).
77 The @code{format} function is a powerful way to print numbers, strings
78 and other objects together with literal text under the control of a
79 format string. This function is available from
82 (use-modules (ice-9 format))
85 A format string is generally more compact and easier than using just
86 the standard procedures like @code{display}, @code{write} and
87 @code{newline}. Parameters in the output string allow various output
88 styles, and parameters can be taken from the arguments for runtime
91 @code{format} is similar to the Common Lisp procedure of the same
92 name, but it's not identical and doesn't have quite all the features
95 C programmers will note the similarity between @code{format} and
96 @code{printf}, though escape sequences are marked with @nicode{~}
97 instead of @nicode{%}, and are more powerful.
100 @deffn {Scheme Procedure} format dest fmt [args@dots{}]
101 Write output specified by the @var{fmt} string to @var{dest}.
102 @var{dest} can be an output port, @code{#t} for
103 @code{current-output-port} (@pxref{Default Ports}), a number for
104 @code{current-error-port}, or @code{#f} to return the output as a
107 @var{fmt} can contain literal text to be output, and @nicode{~}
108 escapes. Each escape has the form
111 ~ [param [, param@dots{}] [:] [@@] code
114 @nicode{code} is a character determining the escape sequence. The
115 @nicode{:} and @nicode{@@} characters are optional modifiers, one or
116 both of which change the way various codes operate. Optional
117 parameters are accepted by some codes too. Parameters have the
121 @item @nicode{[+/-]number}
122 An integer, with optional @nicode{+} or @nicode{-}.
123 @item @nicode{'} (apostrophe)
124 The following character in the format string, for instance @nicode{'z}
127 The next function argument as the parameter. @nicode{v} stands for
128 ``variable'', a parameter can be calculated at runtime and included in
129 the arguments. Upper case @nicode{V} can be used too.
131 The number of arguments remaining. (See @nicode{~*} below for some
135 Parameters are separated by commas (@nicode{,}). A parameter can be
136 left empty to keep its default value when supplying later parameters.
139 The following escapes are available. The code letters are not
140 case-sensitive, upper and lower case are the same.
145 Object output. Parameters: @var{minwidth}, @var{padinc},
146 @var{minpad}, @var{padchar}.
148 @nicode{~a} outputs an argument like @code{display}, @nicode{~s}
149 outputs an argument like @code{write} (@pxref{Writing}).
152 (format #t "~a" "foo") @print{} foo
153 (format #t "~s" "foo") @print{} "foo"
156 @nicode{~:a} and @nicode{~:s} put objects that don't have an external
157 representation in quotes like a string.
160 (format #t "~:a" car) @print{} "#<primitive-procedure car>"
163 If the output is less than @var{minwidth} characters (default 0), it's
164 padded on the right with @var{padchar} (default space). @nicode{~@@a}
165 and @nicode{~@@s} put the padding on the left instead.
168 (format #f "~5a" 'abc) @result{} "abc "
169 (format #f "~5,,,'-@@a" 'abc) @result{} "--abc"
172 @var{minpad} is a minimum for the padding then plus a multiple of
173 @var{padinc}. Ie.@: the padding is @math{@var{minpad} + @var{N} *
174 @var{padinc}}, where @var{n} is the smallest integer making the total
175 object plus padding greater than or equal to @var{minwidth}. The
176 default @var{minpad} is 0 and the default @var{padinc} is 1 (imposing
177 no minimum or multiple).
180 (format #f "~5,1,4a" 'abc) @result{} "abc "
184 Character. Parameter: @var{charnum}.
186 Output a character. The default is to simply output, as per
187 @code{write-char} (@pxref{Writing}). @nicode{~@@c} prints in
188 @code{write} style. @nicode{~:c} prints control characters (ASCII 0
189 to 31) in @nicode{^X} form.
192 (format #t "~c" #\z) @print{} z
193 (format #t "~@@c" #\z) @print{} #\z
194 (format #t "~:c" #\newline) @print{} ^J
197 If the @var{charnum} parameter is given then an argument is not taken
198 but instead the character is @code{(integer->char @var{charnum})}
199 (@pxref{Characters}). This can be used for instance to output
200 characters given by their ASCII code.
203 (format #t "~65c") @print{} A
210 Integer. Parameters: @var{minwidth}, @var{padchar}, @var{commachar},
213 Output an integer argument as a decimal, hexadecimal, octal or binary
214 integer (respectively).
217 (format #t "~d" 123) @print{} 123
220 @nicode{~@@d} etc shows a @nicode{+} sign is shown on positive
223 @c FIXME: "+" is not shown on zero, unlike in Common Lisp. Should
224 @c that be changed in the code, or is it too late and should just be
225 @c documented that way?
228 (format #t "~@@b" 12) @print{} +1100
231 If the output is less than the @var{minwidth} parameter (default no
232 minimum), it's padded on the left with the @var{padchar} parameter
236 (format #t "~5,'*d" 12) @print{} ***12
237 (format #t "~5,'0d" 12) @print{} 00012
238 (format #t "~3d" 1234) @print{} 1234
241 @nicode{~:d} adds commas (or the @var{commachar} parameter) every
242 three digits (or the @var{commawidth} parameter many).
245 (format #t "~:d" 1234567) @print{} 1,234,567
246 (format #t "~10,'*,'/,2:d" 12345) @print{} ***1/23/45
249 Hexadecimal @nicode{~x} output is in lower case, but the @nicode{~(}
250 and @nicode{~)} case conversion directives described below can be used
254 (format #t "~x" 65261) @print{} feed
255 (format #t "~:@@(~x~)" 65261) @print{} FEED
259 Integer in words, roman numerals, or a specified radix. Parameters:
260 @var{radix}, @var{minwidth}, @var{padchar}, @var{commachar},
263 With no parameters output is in words as a cardinal like ``ten'', or
264 @nicode{~:r} prints an ordinal like ``tenth''.
267 (format #t "~r" 9) @print{} nine ;; cardinal
268 (format #t "~r" -9) @print{} minus nine ;; cardinal
269 (format #t "~:r" 9) @print{} ninth ;; ordinal
272 And also with no parameters, @nicode{~@@r} gives roman numerals and
273 @nicode{~:@@r} gives old roman numerals. In old roman numerals
274 there's no ``subtraction'', so 9 is @nicode{VIIII} instead of
275 @nicode{IX}. In both cases only positive numbers can be output.
278 (format #t "~@@r" 89) @print{} LXXXIX ;; roman
279 (format #t "~:@@r" 89) @print{} LXXXVIIII ;; old roman
282 When a parameter is given it means numeric output in the specified
283 @var{radix}. The modifiers and parameters following the radix are the
284 same as described for @nicode{~d} etc above.
287 (format #f "~3r" 27) @result{} "1000" ;; base 3
288 (format #f "~3,5r" 26) @result{} " 222" ;; base 3 width 5
292 Fixed-point float. Parameters: @var{width}, @var{decimals},
293 @var{scale}, @var{overflowchar}, @var{padchar}.
295 Output a number or number string in fixed-point format, ie.@: with a
299 (format #t "~f" 5) @print{} 5.0
300 (format #t "~f" "123") @print{} 123.0
301 (format #t "~f" "1e-1") @print{} 0.1
304 @nicode{~@@f} prints a @nicode{+} sign on positive numbers (including
308 (format #t "~@@f" 0) @print{} +0.0
311 If the output is less than @var{width} characters it's padded on the
312 left with @var{padchar} (space by default). If the output equals or
313 exceeds @var{width} then there's no padding. The default for
314 @var{width} is no padding.
317 (format #f "~6f" -1.5) @result{} " -1.5"
318 (format #f "~6,,,,'*f" 23) @result{} "**23.0"
319 (format #f "~6f" 1234567.0) @result{} "1234567.0"
322 @var{decimals} is how many digits to print after the decimal point,
323 with the value rounded or padded with zeros as necessary. (The
324 default is to output as many decimals as required.)
327 (format #t "~1,2f" 3.125) @print{} 3.13
328 (format #t "~1,2f" 1.5) @print{} 1.50
331 @var{scale} is a power of 10 applied to the value, moving the decimal
332 point that many places. A positive @var{scale} increases the value
333 shown, a negative decreases it.
336 (format #t "~,,2f" 1234) @print{} 123400.0
337 (format #t "~,,-2f" 1234) @print{} 12.34
340 If @var{overflowchar} and @var{width} are both given and if the output
341 would exceed @var{width}, then that many @var{overflowchar}s are
342 printed instead of the value.
345 (format #t "~5,,,'xf" 12345) @print{} 12345
346 (format #t "~4,,,'xf" 12345) @print{} xxxx
350 Exponential float. Parameters: @var{width}, @var{mantdigits},
351 @var{expdigits}, @var{intdigits}, @var{overflowchar}, @var{padchar},
354 Output a number or number string in exponential notation.
357 (format #t "~e" 5000.25) @print{} 5.00025E+3
358 (format #t "~e" "123.4") @print{} 1.234E+2
359 (format #t "~e" "1e4") @print{} 1.0E+4
362 @nicode{~@@e} prints a @nicode{+} sign on positive numbers (including
363 zero). (This is for the mantissa, a @nicode{+} or @nicode{-} sign is
364 always shown on the exponent.)
367 (format #t "~@@e" 5000.0) @print{} +5.0E+3
370 If the output is less than @var{width} characters it's padded on the
371 left with @var{padchar} (space by default). The default for
372 @var{width} is to output with no padding.
375 (format #f "~10e" 1234.0) @result{} " 1.234E+3"
376 (format #f "~10,,,,,'*e" 0.5) @result{} "****5.0E-1"
379 @c FIXME: Describe what happens when the number is bigger than WIDTH.
380 @c There seems to be a bit of dodginess about this, or some deviation
383 @var{mantdigits} is the number of digits shown in the mantissa after
384 the decimal point. The value is rounded or trailing zeros are added
385 as necessary. The default @var{mantdigits} is to show as much as
389 (format #f "~,3e" 11111.0) @result{} "1.111E+4"
390 (format #f "~,8e" 123.0) @result{} "1.23000000E+2"
393 @var{expdigits} is the minimum number of digits shown for the
394 exponent, with leading zeros added if necessary. The default for
395 @var{expdigits} is to show only as many digits as required. At least
396 1 digit is always shown.
399 (format #f "~,,1e" 1.0e99) @result{} "1.0E+99"
400 (format #f "~,,6e" 1.0e99) @result{} "1.0E+000099"
403 @var{intdigits} (default 1) is the number of digits to show before the
404 decimal point in the mantissa. @var{intdigits} can be zero, in which
405 case the integer part is a single @nicode{0}, or it can be negative,
406 in which case leading zeros are shown after the decimal point.
408 @c FIXME: When INTDIGITS is 0, Common Lisp format apparently only
409 @c shows the single 0 digit if it fits in WIDTH. format.scm seems to
410 @c show it always. Is it meant to?
413 (format #t "~,,,3e" 12345.0) @print{} 123.45E+2
414 (format #t "~,,,0e" 12345.0) @print{} 0.12345E+5
415 (format #t "~,,,-3e" 12345.0) @print{} 0.00012345E+8
418 @c FIXME: MANTDIGITS with negative INTDIGITS doesn't match CL spec,
419 @c believe the spec says it ought to still show mantdigits+1 sig
420 @c figures, ie. leading zeros don't count towards MANTDIGITS, but it
421 @c seems to just treat MANTDIGITS as how many digits after the
424 If @var{overflowchar} is given then @var{width} is a hard limit. If
425 the output would exceed @var{width} then instead that many
426 @var{overflowchar}s are printed.
429 (format #f "~6,,,,'xe" 100.0) @result{} "1.0E+2"
430 (format #f "~3,,,,'xe" 100.0) @result{} "xxx"
433 @var{expchar} is the exponent marker character (default @nicode{E}).
436 (format #t "~,,,,,,'ee" 100.0) @print{} 1.0e+2
440 General float. Parameters: @var{width}, @var{mantdigits},
441 @var{expdigits}, @var{intdigits}, @var{overflowchar}, @var{padchar},
444 Output a number or number string in either exponential format the same
445 as @nicode{~e}, or fixed-point format like @nicode{~f} but aligned
446 where the mantissa would have been and followed by padding where the
447 exponent would have been.
449 @c FIXME: The default MANTDIGITS is apparently max(needed,min(n,7))
450 @c where 10^(n-1)<=abs(x)<=10^n. But the Common Lisp spec seems to
451 @c ask for "needed" to be without leading or trailing zeros, whereas
452 @c format.scm seems to include trailing zeros, ending up with it
453 @c using fixed format for bigger values than it should.
455 Fixed-point is used when the absolute value is 0.1 or more and it
456 takes no more space than the mantissa in exponential format, ie.@:
457 basically up to @var{mantdigits} digits.
460 (format #f "~12,4,2g" 999.0) @result{} " 999.0 "
461 (format #f "~12,4,2g" "100000") @result{} " 1.0000E+05"
464 The parameters are interpreted as per @nicode{~e} above. When
465 fixed-point is used, the @var{decimals} parameter to @nicode{~f} is
466 established from @var{mantdigits}, so as to give a total
467 @math{@var{mantdigits}+1} figures.
470 Monetary style fixed-point float. Parameters: @var{decimals},
471 @var{intdigits}, @var{width}, @var{padchar}.
473 @c For reference, fmtdoc.txi from past versions of slib showed the
474 @c INTDIGITS parameter as SCALE. That looks like a typo, in the code
475 @c and in the Common Lisp spec it's a minimum digits for the integer
476 @c part, it isn't a power of 10 like in ~f.
478 Output a number or number string in fixed-point format, ie.@: with a
479 decimal point. @var{decimals} is the number of decimal places to
483 (format #t "~$" 5) @print{} 5.00
484 (format #t "~4$" "2.25") @print{} 2.2500
485 (format #t "~4$" "1e-2") @print{} 0.0100
488 @nicode{~@@$} prints a @nicode{+} sign on positive numbers (including
492 (format #t "~@@$" 0) @print{} +0.00
495 @var{intdigits} is a minimum number of digits to show in the integer
496 part of the value (default 1).
499 (format #t "~,3$" 9.5) @print{} 009.50
500 (format #t "~,0$" 0.125) @print{} .13
503 If the output is less than @var{width} characters (default 0), it's
504 padded on the left with @var{padchar} (default space). @nicode{~:$}
505 puts the padding after the sign.
508 (format #f "~,,8$" -1.5) @result{} " -1.50"
509 (format #f "~,,8:$" -1.5) @result{} "- 1.50"
510 (format #f "~,,8,'.:@@$" 3) @result{} "+...3.00"
513 Note that floating point for dollar amounts is generally not a good
514 idea, because a cent @math{0.01} cannot be represented exactly in the
515 binary floating point Guile uses, which leads to slowly accumulating
516 rounding errors. Keeping values as cents (or fractions of a cent) in
517 integers then printing with the scale option in @nicode{~f} may be a
520 @c For reference, fractions don't work with ~$ (or any of the float
521 @c conversions) currently. If they did work then we could perhaps
522 @c suggest keeping dollar amounts as rationals, which would of course
523 @c give exact cents. An integer as cents is probably still a better
524 @c recommendation though, since it forces one to think about where
525 @c and when rounding can or should occur.
528 Complex fixed-point float. Parameters: @var{width}, @var{decimals},
529 @var{scale}, @var{overflowchar}, @var{padchar}.
531 @c For reference, in Common Lisp ~i is an indent, but slib fmtdoc.txi
532 @c described it as complex number output, so we keep that.
534 Output the argument as a complex number, with both real and imaginary
535 part shown (even if one or both are zero).
537 The parameters and modifiers are the same as for fixed-point
538 @nicode{~f} described above. The real and imaginary parts are both
539 output with the same given parameters and modifiers, except that for
540 the imaginary part the @nicode{@@} modifier is always enabled, so as
541 to print a @nicode{+} sign between the real and imaginary parts.
544 (format #t "~i" 1) @print{} 1.0+0.0i
548 Plural. No parameters.
550 Output nothing if the argument is 1, or @samp{s} for any other
554 (format #t "enter name~p" 1) @print{} enter name
555 (format #t "enter name~p" 2) @print{} enter names
558 @nicode{~@@p} prints @samp{y} for 1 or @samp{ies} otherwise.
561 (format #t "pupp~@@p" 1) @print{} puppy
562 (format #t "pupp~@@p" 2) @print{} puppies
565 @nicode{~:p} re-uses the preceding argument instead of taking a new
566 one, which can be convenient when printing some sort of count.
569 (format #t "~d cat~:p" 9) @print{} 9 cats
570 (format #t "~d pupp~:@@p" 5) @print{} 5 puppies
573 @nicode{~p} is designed for English plurals and there's no attempt to
574 support other languages. @nicode{~[} conditionals (below) may be able
575 to help. When using @code{gettext} to translate messages
576 @code{ngettext} is probably best though
577 (@pxref{Internationalization}).
580 Pretty print. No parameters.
582 Output an argument with @code{pretty-print} (@pxref{Pretty Printing}).
586 Sub-format. No parameters.
588 Take a format string argument and a second argument which is a list of
589 arguments for that string, and output the result.
592 (format #t "~?" "~d ~d" '(1 2)) @print{} 1 2
595 @nicode{~@@?} takes arguments for the sub-format directly rather than
599 (format #t "~@@? ~s" "~d ~d" 1 2 "foo") @print{} 1 2 "foo"
602 @nicode{~?} and @nicode{~k} are the same, @nicode{~k} is provided for
603 T-Scheme compatibility.
606 Argument jumping. Parameter: @var{N}.
608 Move forward @var{N} arguments (default 1) in the argument list.
609 @nicode{~:*} moves backwards. (@var{N} cannot be negative.)
612 (format #f "~d ~2*~d" 1 2 3 4) @result{} "1 4"
613 (format #f "~d ~:*~d" 6) @result{} "6 6"
616 @nicode{~@@*} moves to argument number @var{N}. The first argument is
617 number 0 (and that's the default for @var{N}).
620 (format #f "~d~d again ~@@*~d~d" 1 2) @result{} "12 again 12"
621 (format #f "~d~d~d ~1@@*~d~d" 1 2 3) @result{} "123 23"
624 A @nicode{#} move to the end followed by a @nicode{:} modifier move
625 back can be used for an absolute position relative to the end of the
626 argument list, a reverse of what the @nicode{@@} modifier does.
629 (format #t "~#*~2:*~a" 'a 'b 'c 'd) @print{} c
632 At the end of the format string the current argument postion doesn't
633 matter, any further arguments are ignored.
636 Advance to a column position. Parameters: @var{colnum}, @var{colinc},
639 Output @var{padchar} (space by default) to move to the given
640 @var{colnum} column. The start of the line is column 0, the default
641 for @var{colnum} is 1.
644 (format #f "~tX") @result{} " X"
645 (format #f "~3tX") @result{} " X"
648 If the current column is already past @var{colnum}, then the move is
649 to there plus a multiple of @var{colinc}, ie.@: column
650 @math{@var{colnum} + @var{N} * @var{colinc}} for the smallest @var{N}
651 which makes that value greater than or equal to the current column.
652 The default @var{colinc} is 1 (which means no further move).
655 (format #f "abcd~2,5,'.tx") @result{} "abcd...x"
658 @nicode{~@@t} takes @var{colnum} as an offset from the current column.
659 @var{colnum} many pad characters are output, then further padding to
660 make the current column a multiple of @var{colinc}, if it isn't
664 (format #f "a~3,5'*@@tx") @result{} "a****x"
667 @nicode{~t} is implemented using @code{port-column} (@pxref{Reading}),
668 so it works even there has been other output before @code{format}.
671 Tilde character. Parameter: @var{n}.
673 Output a tilde character @nicode{~}, or @var{n} many if a parameter is
674 given. Normally @nicode{~} introduces an escape sequence, @nicode{~~}
675 is the way to output a literal tilde.
678 Newline. Parameter: @var{n}.
680 Output a newline character, or @var{n} many if a parameter is given.
681 A newline (or a few newlines) can of course be output just by
682 including them in the format string.
685 Start a new line. Parameter: @var{n}.
687 Output a newline if not already at the start of a line. With a
688 parameter, output that many newlines, but with the first only if not
689 already at the start of a line. So for instance 3 would be a newline
690 if not already at the start of a line, and 2 further newlines.
693 Space character. Parameter: @var{n}.
695 @c For reference, in Common Lisp ~_ is a conditional newline, but
696 @c slib fmtdoc.txi described it as a space, so we keep that.
698 Output a space character, or @var{n} many if a parameter is given.
700 With a variable parameter this is one way to insert runtime calculated
701 padding (@nicode{~t} or the various field widths can do similar
705 (format #f "~v_foo" 4) @result{} " foo"
709 Tab character. Parameter: @var{n}.
711 Output a tab character, or @var{n} many if a parameter is given.
714 Formfeed character. Parameter: @var{n}.
716 Output a formfeed character, or @var{n} many if a parameter is given.
719 Force output. No parameters.
721 At the end of output, call @code{force-output} to flush any buffers on
722 the destination (@pxref{Writing}). @nicode{~!} can occur anywhere in
723 the format string, but the force is done at the end of output.
725 When output is to a string (destination @code{#f}), @nicode{~!} does
728 @item @nicode{~newline} (ie.@: newline character)
729 Continuation line. No parameters.
731 Skip this newline and any following whitespace in the format string,
732 ie.@: don't send it to the output. This can be used to break up a
733 long format string for readability, but not print the extra
739 ~d" 1 2) @result{} "abc1 def2"
742 @nicode{~:newline} skips the newline but leaves any further whitespace
743 to be printed normally.
745 @nicode{~@@newline} prints the newline then skips following
748 @item @nicode{~(} @nicode{~)}
749 Case conversion. No parameters.
751 Between @nicode{~(} and @nicode{~)} the case of all output is changed.
752 The modifiers on @nicode{~(} control the conversion.
756 @nicode{~(} --- lower case.
758 @c FIXME: The : and @ modifiers are not yet documented because the
759 @c code applies string-capitalize and string-capitalize-first to each
760 @c separate format:out-str call, which has various subtly doubtful
761 @c effects. And worse they're applied to individual characters,
762 @c including literal characters in the format string, which has the
763 @c silly effect of being always an upcase.
765 @c The Common Lisp spec is apparently for the capitalization to be
766 @c applied in one hit to the whole of the output between ~( and ~).
767 @c (This can no doubt be implemented without accumulating all that
768 @c text, just by keeping a state or the previous char to tell whether
772 @c @nicode{:} --- first letter of each word upper case, the rest lower
773 @c case, as per the @code{string-capitalize} function (@pxref{Alphabetic
776 @c @nicode{@@} --- first letter of just the first word upper case, the
780 @nicode{~:@@(} --- upper case.
786 (format #t "~(Hello~)") @print{} hello
787 (format #t "~:@@(Hello~)") @print{} HELLO
790 In the future it's intended the modifiers @nicode{:} and @nicode{@@}
791 alone will capitalize the first letters of words, as per Common Lisp
792 @code{format}, but the current implementation of this is flawed and
793 not recommended for use.
795 Case conversions do not nest, currently. This might change in the
796 future, but if it does then it will be to Common Lisp style where the
797 outermost conversion has priority, overriding inner ones (making those
800 @item @nicode{~@{} @nicode{~@}}
801 Iteration. Parameter: @var{maxreps} (for @nicode{~@{}).
803 The format between @nicode{~@{} and @nicode{~@}} is iterated. The
804 modifiers to @nicode{~@{} determine how arguments are taken. The
805 default is a list argument with each iteration successively consuming
806 elements from it. This is a convenient way to output a whole list.
809 (format #t "~@{~d~@}" '(1 2 3)) @print{} 123
810 (format #t "~@{~s=~d ~@}" '("x" 1 "y" 2)) @print{} "x"=1 "y"=2
813 @nicode{~:@{} takes a single argument which is a list of lists, each
814 of those contained lists gives the arguments for the iterated format.
816 @c @print{} on a new line here to avoid overflowing page width in DVI
818 (format #t "~:@{~dx~d ~@}" '((1 2) (3 4) (5 6)))
822 @nicode{~@@@{} takes arguments directly, with each iteration
823 successively consuming arguments.
826 (format #t "~@@@{~d~@}" 1 2 3) @print{} 123
827 (format #t "~@@@{~s=~d ~@}" "x" 1 "y" 2) @print{} "x"=1 "y"=2
830 @nicode{~:@@@{} takes list arguments, one argument for each iteration,
831 using that list for the format.
833 @c @print{} on a new line here to avoid overflowing page width in DVI
835 (format #t "~:@@@{~dx~d ~@}" '(1 2) '(3 4) '(5 6))
839 Iterating stops when there are no more arguments or when the
840 @var{maxreps} parameter to @nicode{~@{} is reached (default no
844 (format #t "~2@{~d~@}" '(1 2 3 4)) @print{} 12
847 If the format between @nicode{~@{} and @nicode{~@}} is empty, then a
848 format string argument is taken (before iteration argument(s)) and
849 used instead. This allows a sub-format (like @nicode{~?} above) to be
853 (format #t "~@{~@}" "~d" '(1 2 3)) @print{} 123
856 @c FIXME: What is the @nicode{:} modifier to ~} meant to do? The
857 @c Common Lisp spec says it's a minimum of 1 iteration, but the
858 @c format.scm code seems to merely make it have MAXREPS default to 1.
860 Iterations can be nested, an inner iteration operates in the same way
861 as described, but of course on the arguments the outer iteration
862 provides it. This can be used to work into nested list structures.
863 For example in the following the inner @nicode{~@{~d~@}x} is applied
864 to @code{(1 2)} then @code{(3 4 5)} etc.
867 (format #t "~@{~@{~d~@}x~@}" '((1 2) (3 4 5))) @print{} 12x345x
870 See also @nicode{~^} below for escaping from iteration.
872 @item @nicode{~[} @nicode{~;} @nicode{~]}
873 Conditional. Parameter: @var{selector}.
875 A conditional block is delimited by @nicode{~[} and @nicode{~]}, and
876 @nicode{~;} separates clauses within the block. @nicode{~[} takes an
877 integer argument and that number clause is used. The first clause is
881 (format #f "~[peach~;banana~;mango~]" 1) @result{} "banana"
884 The @var{selector} parameter can be used for the clause number,
885 instead of taking an argument.
888 (format #f "~2[peach~;banana~;mango~]") @result{} "mango"
891 If the clause number is out of range then nothing is output. Or the
892 last clause can be @nicode{~:;} to use that for a number out of range.
895 (format #f "~[banana~;mango~]" 99) @result{} ""
896 (format #f "~[banana~;mango~:;fruit~]" 99) @result{} "fruit"
899 @nicode{~:[} treats the argument as a flag, and expects two clauses.
900 The first is used if the argument is @code{#f} or the second
904 (format #f "~:[false~;not false~]" #f) @result{} "false"
905 (format #f "~:[false~;not false~]" 'abc) @result{} "not false"
908 (format #t "~d gnu~:[s are~; is~] here" n (= 1 n)))
909 @print{} 3 gnus are here
912 @nicode{~@@[} also treats the argument as a flag, and expects one
913 clause. If the argument is @code{#f} then no output is produced and
914 the argument is consumed, otherwise the clause is used and the
915 argument is not consumed, it's left for the clause. This can be used
916 for instance to suppress output if @code{#f} means something not
920 (format #f "~@@[temperature=~d~]" 27) @result{} "temperature=27"
921 (format #f "~@@[temperature=~d~]" #f) @result{} ""
925 Escape. Parameters: @var{val1}, @var{val2}, @var{val3}.
927 Stop formatting if there are no more arguments. This can be used for
928 instance to have a format string adapt to a variable number of
932 (format #t "~d~^ ~d" 1) @print{} 1
933 (format #t "~d~^ ~d" 1 2) @print{} 1 2
936 Within a @nicode{~@{} @nicode{~@}} iteration, @nicode{~^} stops the
937 current iteration step if there are no more arguments to that step,
938 but continuing with possible further steps and the rest of the format.
939 This can be used for instance to avoid a separator on the last
940 iteration, or to adapt to variable length argument lists.
943 (format #f "~@{~d~^/~@} go" '(1 2 3)) @result{} "1/2/3 go"
944 (format #f "~:@{ ~d~^~d~@} go" '((1) (2 3))) @result{} " 1 23 go"
947 @c For reference, format.scm doesn't implement that Common Lisp ~:^
948 @c modifier which stops the entire iterating of ~:{ or ~@:{.
950 @c FIXME: Believe the Common Lisp spec is for ~^ within ~[ ~]
951 @c conditional to terminate the whole format (or iteration step if in
952 @c an iteration). But format.scm seems to terminate just the
955 @c (format #f "~[abc~^def~;ghi~] blah" 0)
956 @c @result{} "abc blah" ;; looks wrong
958 @c FIXME: Believe the Common Lisp spec is for ~^ within ~( ~) to end
959 @c that case conversion and then also terminate the whole format (or
960 @c iteration step if in an iteration). But format.scm doesn't seem
961 @c to do that quite right.
963 @c (format #f "~d ~^ ~d" 1) @result{} "1 "
964 @c (format #f "~(~d ~^ ~d~)" 1) @result{} ERROR
966 Within a @nicode{~?} sub-format, @nicode{~^} operates just on that
967 sub-format. If it terminates the sub-format then the originating
968 format will still continue.
971 (format #t "~? items" "~d~^ ~d" '(1)) @print{} 1 items
972 (format #t "~? items" "~d~^ ~d" '(1 2)) @print{} 1 2 items
975 The parameters to @nicode{~^} (which are numbers) change the condition
976 used to terminate. For a single parameter, termination is when that
977 value is zero (notice this makes plain @nicode{~^} equivalent to
978 @nicode{~#^}). For two parameters, termination is when those two are
979 equal. For three parameters, termination is when @math{@var{val1}
980 @le{} @var{val2}} and @math{@var{val2} @le{} @var{val3}}.
982 @c FIXME: Good examples of these?
985 Inquiry message. Insert a copyright message into the output.
987 @nicode{~:q} inserts the format implementation version.
991 It's an error if there are not enough arguments for the escapes in the
992 format string, but any excess arguments are ignored.
994 Iterations @nicode{~@{} @nicode{~@}} and conditionals @nicode{~[}
995 @nicode{~;} @nicode{~]} can be nested, but must be properly nested,
996 meaning the inner form must be entirely within the outer form. So
997 it's not possible, for instance, to try to conditionalize the endpoint
1001 (format #t "~@{ ~[ ... ~] ~@}" ...) ;; good
1002 (format #t "~@{ ~[ ... ~@} ... ~]" ...) ;; bad
1005 The same applies to case conversions @nicode{~(} @nicode{~)}, they
1006 must properly nest with respect to iterations and conditionals (though
1007 currently a case conversion cannot nest within another case
1010 When a sub-format (@nicode{~?}) is used, that sub-format string must
1011 be self-contained. It cannot for instance give a @nicode{~@{} to
1012 begin an iteration form and have the @nicode{~@}} up in the
1013 originating format, or similar.
1017 Guile contains a @code{format} procedure even when the module
1018 @code{(ice-9 format)} is not loaded. The default @code{format} is
1019 @code{simple-format} (@pxref{Writing}), it doesn't support all escape
1020 sequences documented in this section, and will signal an error if you
1021 try to use one of them. The reason for two versions is that the full
1022 @code{format} is fairly large and requires some time to load.
1023 @code{simple-format} is often adequate too.
1026 @node File Tree Walk
1027 @section File Tree Walk
1028 @cindex file tree walk
1030 The functions in this section traverse a tree of files and
1031 directories, in a fashion similar to the C @code{ftw} and @code{nftw}
1032 routines (@pxref{Working with Directory Trees,,, libc, GNU C Library
1036 (use-modules (ice-9 ftw))
1040 @defun ftw startname proc ['hash-size n]
1041 Walk the file system tree descending from @var{startname}, calling
1042 @var{proc} for each file and directory.
1044 Hard links and symbolic links are followed. A file or directory is
1045 reported to @var{proc} only once, and skipped if seen again in another
1046 place. One consequence of this is that @code{ftw} is safe against
1047 circularly linked directory structures.
1049 Each @var{proc} call is @code{(@var{proc} filename statinfo flag)} and
1050 it should return @code{#t} to continue, or any other value to stop.
1052 @var{filename} is the item visited, being @var{startname} plus a
1053 further path and the name of the item. @var{statinfo} is the return
1054 from @code{stat} (@pxref{File System}) on @var{filename}. @var{flag}
1055 is one of the following symbols,
1059 @var{filename} is a file, this includes special files like devices,
1063 @var{filename} is a directory.
1066 An error occurred when calling @code{stat}, so nothing is known.
1067 @var{statinfo} is @code{#f} in this case.
1069 @item directory-not-readable
1070 @var{filename} is a directory, but one which cannot be read and hence
1071 won't be recursed into.
1074 @var{filename} is a dangling symbolic link. Symbolic links are
1075 normally followed and their target reported, the link itself is
1076 reported if the target does not exist.
1079 The return value from @code{ftw} is @code{#t} if it ran to completion,
1080 or otherwise the non-@code{#t} value from @var{proc} which caused the
1083 Optional argument symbol @code{hash-size} and an integer can be given
1084 to set the size of the hash table used to track items already visited.
1085 (@pxref{Hash Table Reference})
1087 @c Actually, it's probably safe to escape from ftw, just need to
1090 In the current implementation, returning non-@code{#t} from @var{proc}
1091 is the only valid way to terminate @code{ftw}. @var{proc} must not
1092 use @code{throw} or similar to escape.
1096 @defun nftw startname proc ['chdir] ['depth] ['hash-size n] ['mount] ['physical]
1097 Walk the file system tree starting at @var{startname}, calling
1098 @var{proc} for each file and directory. @code{nftw} has extra
1099 features over the basic @code{ftw} described above.
1101 Like @code{ftw}, hard links and symbolic links are followed. A file
1102 or directory is reported to @var{proc} only once, and skipped if seen
1103 again in another place. One consequence of this is that @code{nftw}
1104 is safe against circular linked directory structures.
1106 Each @var{proc} call is @code{(@var{proc} filename statinfo flag
1107 base level)} and it should return @code{#t} to continue, or any
1108 other value to stop.
1110 @var{filename} is the item visited, being @var{startname} plus a
1111 further path and the name of the item. @var{statinfo} is the return
1112 from @code{stat} on @var{filename} (@pxref{File System}). @var{base}
1113 is an integer offset into @var{filename} which is where the basename
1114 for this item begins. @var{level} is an integer giving the directory
1115 nesting level, starting from 0 for the contents of @var{startname} (or
1116 that item itself if it's a file). @var{flag} is one of the following
1121 @var{filename} is a file, including special files like devices, named
1125 @var{filename} is a directory.
1127 @item directory-processed
1128 @var{filename} is a directory, and its contents have all been visited.
1129 This flag is given instead of @code{directory} when the @code{depth}
1130 option below is used.
1133 An error occurred when applying @code{stat} to @var{filename}, so
1134 nothing is known about it. @var{statinfo} is @code{#f} in this case.
1136 @item directory-not-readable
1137 @var{filename} is a directory, but one which cannot be read and hence
1138 won't be recursed into.
1141 @var{filename} is a dangling symbolic link. Links are normally
1142 followed and their target reported, the link itself is reported if its
1143 target does not exist.
1146 When the @code{physical} option described below is used, this
1147 indicates @var{filename} is a symbolic link whose target exists (and
1148 is not being followed).
1151 The following optional arguments can be given to modify the way
1152 @code{nftw} works. Each is passed as a symbol (and @code{hash-size}
1153 takes a following integer value).
1157 Change to the directory containing the item before calling @var{proc}.
1158 When @code{nftw} returns the original current directory is restored.
1160 Under this option, generally the @var{base} parameter to each
1161 @var{proc} call should be used to pick out the base part of the
1162 @var{filename}. The @var{filename} is still a path but with a changed
1163 directory it won't be valid (unless the @var{startname} directory was
1167 Visit files ``depth first'', meaning @var{proc} is called for the
1168 contents of each directory before it's called for the directory
1169 itself. Normally a directory is reported first, then its contents.
1171 Under this option, the @var{flag} to @var{proc} for a directory is
1172 @code{directory-processed} instead of @code{directory}.
1174 @item @code{hash-size @var{n}}
1175 Set the size of the hash table used to track items already visited.
1176 (@pxref{Hash Table Reference})
1179 Don't cross a mount point, meaning only visit items on the same
1180 file system as @var{startname} (ie.@: the same @code{stat:dev}).
1182 @item @code{physical}
1183 Don't follow symbolic links, instead report them to @var{proc} as
1184 @code{symlink}. Dangling links (those whose target doesn't exist) are
1185 still reported as @code{stale-symlink}.
1188 The return value from @code{nftw} is @code{#t} if it ran to
1189 completion, or otherwise the non-@code{#t} value from @var{proc} which
1192 @c For reference, one reason not to esacpe is that the current
1193 @c directory is not saved and restored with dynamic-wind. Maybe
1194 @c changing that would be enough to allow escaping.
1196 In the current implementation, returning non-@code{#t} from @var{proc}
1197 is the only valid way to terminate @code{ftw}. @var{proc} must not
1198 use @code{throw} or similar to escape.
1208 The functions in this section are provided by
1211 (use-modules (ice-9 q))
1214 This module implements queues holding arbitrary scheme objects and
1215 designed for efficient first-in / first-out operations.
1217 @code{make-q} creates a queue, and objects are entered and removed
1218 with @code{enq!} and @code{deq!}. @code{q-push!} and @code{q-pop!}
1219 can be used too, treating the front of the queue like a stack.
1223 @deffn {Scheme Procedure} make-q
1227 @deffn {Scheme Procedure} q? obj
1228 Return @code{#t} if @var{obj} is a queue, or @code{#f} if not.
1230 Note that queues are not a distinct class of objects but are
1231 implemented with cons cells. For that reason certain list structures
1232 can get @code{#t} from @code{q?}.
1235 @deffn {Scheme Procedure} enq! q obj
1236 Add @var{obj} to the rear of @var{q}, and return @var{q}.
1239 @deffn {Scheme Procedure} deq! q
1240 @deffnx {Scheme Procedure} q-pop! q
1241 Remove and return the front element from @var{q}. If @var{q} is
1242 empty, a @code{q-empty} exception is thrown.
1244 @code{deq!} and @code{q-pop!} are the same operation, the two names
1245 just let an application match @code{enq!} with @code{deq!}, or
1246 @code{q-push!} with @code{q-pop!}.
1249 @deffn {Scheme Procedure} q-push! q obj
1250 Add @var{obj} to the front of @var{q}, and return @var{q}.
1253 @deffn {Scheme Procedure} q-length q
1254 Return the number of elements in @var{q}.
1257 @deffn {Scheme Procedure} q-empty? q
1258 Return true if @var{q} is empty.
1261 @deffn {Scheme Procedure} q-empty-check q
1262 Throw a @code{q-empty} exception if @var{q} is empty.
1265 @deffn {Scheme Procedure} q-front q
1266 Return the first element of @var{q} (without removing it). If @var{q}
1267 is empty, a @code{q-empty} exception is thrown.
1270 @deffn {Scheme Procedure} q-rear q
1271 Return the last element of @var{q} (without removing it). If @var{q}
1272 is empty, a @code{q-empty} exception is thrown.
1275 @deffn {Scheme Procedure} q-remove! q obj
1276 Remove all occurences of @var{obj} from @var{q}, and return @var{q}.
1277 @var{obj} is compared to queue elements using @code{eq?}.
1281 @cindex @code{q-empty}
1282 The @code{q-empty} exceptions described above are thrown just as
1283 @code{(throw 'q-empty)}, there's no message etc like an error throw.
1285 A queue is implemented as a cons cell, the @code{car} containing a
1286 list of queued elements, and the @code{cdr} being the last cell in
1287 that list (for ease of enqueuing).
1290 (@var{list} . @var{last-cell})
1294 If the queue is empty, @var{list} is the empty list and
1295 @var{last-cell} is @code{#f}.
1297 An application can directly access the queue list if desired, for
1298 instance to search the elements or to insert at a specific point.
1300 @deffn {Scheme Procedure} sync-q! q
1301 Recompute the @var{last-cell} field in @var{q}.
1303 All the operations above maintain @var{last-cell} as described, so
1304 normally there's no need for @code{sync-q!}. But if an application
1305 modifies the queue @var{list} then it must either maintain
1306 @var{last-cell} similarly, or call @code{sync-q!} to recompute it.
1314 A stream represents a sequence of values, each of which is calculated
1315 only when required. This allows large or even infinite sequences to
1316 be represented and manipulated with familiar operations like ``car'',
1317 ``cdr'', ``map'' or ``fold''. In such manipulations only as much as
1318 needed is actually held in memory at any one time. The functions in
1319 this section are available from
1322 (use-modules (ice-9 streams))
1325 Streams are implemented using promises (@pxref{Delayed Evaluation}),
1326 which is how the underlying calculation of values is made only when
1327 needed, and the values then retained so the calculation is not
1331 Here is a simple example producing a stream of all odd numbers,
1334 (define odds (make-stream (lambda (state)
1335 (cons state (+ state 2)))
1337 (stream-car odds) @result{} 1
1338 (stream-car (stream-cdr odds)) @result{} 3
1342 @code{stream-map} could be used to derive a stream of odd squares,
1345 (define (square n) (* n n))
1346 (define oddsquares (stream-map square odds))
1349 These are infinite sequences, so it's not possible to convert them to
1350 a list, but they could be printed (infinitely) with for example
1353 (stream-for-each (lambda (n sq)
1354 (format #t "~a squared is ~a\n" n sq))
1365 @defun make-stream proc initial-state
1366 Return a new stream, formed by calling @var{proc} successively.
1368 Each call is @code{(@var{proc} @var{state})}, it should return a pair,
1369 the @code{car} being the value for the stream, and the @code{cdr}
1370 being the new @var{state} for the next call. For the first call
1371 @var{state} is the given @var{initial-state}. At the end of the
1372 stream, @var{proc} should return some non-pair object.
1375 @defun stream-car stream
1376 Return the first element from @var{stream}. @var{stream} must not be
1380 @defun stream-cdr stream
1381 Return a stream which is the second and subsequent elements of
1382 @var{stream}. @var{stream} must not be empty.
1385 @defun stream-null? stream
1386 Return true if @var{stream} is empty.
1389 @defun list->stream list
1390 @defunx vector->stream vector
1391 Return a stream with the contents of @var{list} or @var{vector}.
1393 @var{list} or @var{vector} should not be modified subsequently, since
1394 it's unspecified whether changes there will be reflected in the stream
1398 @defun port->stream port readproc
1399 Return a stream which is the values obtained by reading from
1400 @var{port} using @var{readproc}. Each read call is
1401 @code{(@var{readproc} @var{port})}, and it should return an EOF object
1402 (@pxref{Reading}) at the end of input.
1404 For example a stream of characters from a file,
1407 (port->stream (open-input-file "/foo/bar.txt") read-char)
1411 @defun stream->list stream
1412 Return a list which is the entire contents of @var{stream}.
1415 @defun stream->reversed-list stream
1416 Return a list which is the entire contents of @var{stream}, but in
1420 @defun stream->list&length stream
1421 Return two values (@pxref{Multiple Values}), being firstly a list
1422 which is the entire contents of @var{stream}, and secondly the number
1423 of elements in that list.
1426 @defun stream->reversed-list&length stream
1427 Return two values (@pxref{Multiple Values}) being firstly a list which
1428 is the entire contents of @var{stream}, but in reverse order, and
1429 secondly the number of elements in that list.
1432 @defun stream->vector stream
1433 Return a vector which is the entire contents of @var{stream}.
1436 @defun stream-fold proc init stream0 @dots{} streamN
1437 Apply @var{proc} successively over the elements of the given streams,
1438 from first to last until the end of the shortest stream is reached.
1439 Return the result from the last @var{proc} call.
1441 Each call is @code{(@var{proc} elem0 @dots{} elemN prev)}, where each
1442 @var{elem} is from the corresponding @var{stream}. @var{prev} is the
1443 return from the previous @var{proc} call, or the given @var{init} for
1447 @defun stream-for-each proc stream0 @dots{} streamN
1448 Call @var{proc} on the elements from the given @var{stream}s. The
1449 return value is unspecified.
1451 Each call is @code{(@var{proc} elem0 @dots{} elemN)}, where each
1452 @var{elem} is from the corresponding @var{stream}.
1453 @code{stream-for-each} stops when it reaches the end of the shortest
1457 @defun stream-map proc stream0 @dots{} streamN
1458 Return a new stream which is the results of applying @var{proc} to the
1459 elements of the given @var{stream}s.
1461 Each call is @code{(@var{proc} elem0 @dots{} elemN)}, where each
1462 @var{elem} is from the corresponding @var{stream}. The new stream
1463 ends when the end of the shortest given @var{stream} is reached.
1467 @node Buffered Input
1468 @section Buffered Input
1469 @cindex Buffered input
1470 @cindex Line continuation
1472 The following functions are provided by
1475 (use-modules (ice-9 buffered-input))
1478 A buffered input port allows a reader function to return chunks of
1479 characters which are to be handed out on reading the port. A notion
1480 of further input for an application level logical expression is
1481 maintained too, and passed through to the reader.
1483 @defun make-buffered-input-port reader
1484 Create an input port which returns characters obtained from the given
1485 @var{reader} function. @var{reader} is called (@var{reader} cont),
1486 and should return a string or an EOF object.
1488 The new port gives precisely the characters returned by @var{reader},
1489 nothing is added, so if any newline characters or other separators are
1490 desired they must come from the reader function.
1492 The @var{cont} parameter to @var{reader} is @code{#f} for initial
1493 input, or @code{#t} when continuing an expression. This is an
1494 application level notion, set with
1495 @code{set-buffered-input-continuation?!} below. If the user has
1496 entered a partial expression then it allows @var{reader} for instance
1497 to give a different prompt to show more is required.
1500 @defun make-line-buffered-input-port reader
1501 @cindex Line buffered input
1502 Create an input port which returns characters obtained from the
1503 specified @var{reader} function, similar to
1504 @code{make-buffered-input-port} above, but where @var{reader} is
1505 expected to be a line-oriented.
1507 @var{reader} is called (@var{reader} cont), and should return a string
1508 or an EOF object as above. Each string is a line of input without a
1509 newline character, the port code inserts a newline after each string.
1512 @defun set-buffered-input-continuation?! port cont
1513 Set the input continuation flag for a given buffered input
1516 An application uses this by calling with a @var{cont} flag of
1517 @code{#f} when beginning to read a new logical expression. For
1518 example with the Scheme @code{read} function (@pxref{Scheme Read}),
1521 (define my-port (make-buffered-input-port my-reader))
1523 (set-buffered-input-continuation?! my-port #f)
1524 (let ((obj (read my-port)))
1531 @c TeX-master: "guile.texi"