\title{Combinator Formatting}
\eval
(begin
(display "\n"))
\flushright{\urlh{http://synthcode.com/}{Alex Shinn}}
\flushright{\urlh{http://synthcode.com/scheme/fmt/fmt-0.8.4.tar.gz}{Download Version 0.8.4}}
\eval(display "
\n\n")
A library of procedures for formatting Scheme objects to text in
various ways, and for easily concatenating, composing and extending
these formatters efficiently without resorting to capturing and
manipulating intermediate strings.
\eval(display "
\n\n")
\section{Table of Contents}
\eval(display "\n\n\n\n")
\eval(display "
\n\n")
\section{Installation}
Available for Chicken as the \p{fmt} egg, providing the \q{fmt},
\q{fmt-c}, \q{fmt-color} and \q{fmt-unicode} extensions. To install
manually for Chicken just run \p{"chicken-setup"} in the fmt
directory.
For Gauche run \p{"make gauche && make install-gauche"}. The modules
are installed as \q{text.fmt}, \q{text.fmt.c}, \q{text.fmt.color} and
\q{text.fmt.unicode}.
For MzScheme you can download and install the latest \p{fmt.plt} yourself
from:
\urlh{http://synthcode.com/scheme/fmt/fmt.plt}{http://synthcode.com/scheme/fmt/fmt.plt}
To build the \p{fmt.plt} for yourself you can run \p{"make mzscheme"}.
For Scheme48 the package descriptions are in \p{fmt-scheme48.scm}:
\q{
> ,config ,load fmt-scheme48.scm
> ,open fmt
}
For other implementations you'll need to load SRFI's 1, 6, 13, 33
(sample provided) and 69 (also provided), and then load the following
files:
\q{
(load "let-optionals.scm") ; if you don't have LET-OPTIONALS*
(load "read-line.scm") ; if you don't have READ-LINE
(load "string-ports.scm") ; if you don't have CALL-WITH-OUTPUT-STRING
(load "make-eq-table.scm")
(load "mantissa.scm")
(load "fmt.scm")
(load "fmt-pretty.scm") ; optional pretty printing
(load "fmt-column.scm") ; optional columnar output
(load "fmt-c.scm") ; optional C formatting utilities
(load "fmt-color.scm") ; optional color utilities
(load "fmt-unicode.scm") ; optional Unicode-aware formatting,
; also requires SRFI-4 or SRFI-66
}
\section{Background}
There are several approaches to text formatting. Building strings to
\q{display} is not acceptable, since it doesn't scale to very large
output. The simplest realistic idea, and what people resort to in
typical portable Scheme, is to interleave \q{display} and \q{write}
and manual loops, but this is both extremely verbose and doesn't
compose well. A simple concept such as padding space can't be
achieved directly without somehow capturing intermediate output.
The traditional approach is to use templates - typically strings,
though in theory any object could be used and indeed Emacs' mode-line
format templates allow arbitrary sexps. Templates can use either
escape sequences (as in C's \q{printf} and \urlh{#BIBITEM_2}{CL's}
\q{format}) or pattern matching (as in Visual Basic's \q{Format},
\urlh{#BIBITEM_6}{Perl6's} \q{form}, and SQL date formats). The
primary disadvantage of templates is the relative difficulty (usually
impossibility) of extending them, their opaqueness, and the
unreadability that arises with complex formats. Templates are not
without their advantages, but they are already addressed by other
libraries such as \urlh{#BIBITEM_3}{SRFI-28} and
\urlh{#BIBITEM_4}{SRFI-48}.
This library takes a combinator approach. Formats are nested chains
of closures, which are called to produce their output as needed.
The primary goal of this library is to have, first and foremost, a
maximally expressive and extensible formatting library. The next
most important goal is scalability - to be able to handle
arbitrarily large output and not build intermediate results except
where necessary. The third goal is brevity and ease of use.
\section{Usage}
The primary interface is the \q{fmt} procedure:
\q{(fmt ...)}
where \q{} has the same semantics as with \q{format} -
specifically it can be an output-port, \q{#t} to indicate the current
output port, or \q{#f} to accumulate output into a string.
Each \q{} should be a format closure as discussed below. As a
convenience, non-procedure arguments are also allowed and are
formatted similar to \q{display}, so that
\q{(fmt #f "Result: " res nl)}
would return the string \q{"Result: 42\n"}, assuming \q{RES} is bound
to \q{42}.
\q{nl} is the newline format combinator.
\section{Specification}
The procedure names have gone through several variations, and I'm
still open to new suggestions. The current approach is to use
abbreviated forms of standard output procedures when defining an
equivalent format combinator (thus \q{display} becomes \q{dsp} and
\q{write} becomes \q{wrt}), and to use an \q{fmt-} prefix for
utilities and less common combinators. Variants of the same formatter
get a \q{/} suffix.
\subsection{Formatting Objects}
\subsubsection*{(dsp )}
Outputs \q{} using \q{display} semantics. Specifically, strings
are output without surrounding quotes or escaping and characters are
written as if by \q{write-char}. Other objects are written as with
\q{write} (including nested strings and chars inside \q{}). This
is the default behavior for top-level formats in \q{fmt}, \q{cat} and
most other higher-order combinators.
\subsubsection*{(wrt )}
Outputs \q{} using \q{write} semantics. Handles shared
structures as in \urlh{#BIBITEM_5}{SRFI-38}.
\subsubsection*{(wrt/unshared )}
As above, but doesn't handle shared structures. Infinite loops can
still be avoided if used inside a combinator that truncates data (see
\q{trim} and \q{fit} below).
\subsubsection*{(pretty )}
Pretty-prints \q{}. Also handles shared structures. Unlike many
other pretty printers, vectors and data lists (lists that don't begin
with a (nested) symbol), are printed in tabular format when there's
room, greatly saving vertical space.
\subsubsection*{(pretty/unshared )}
As above but without sharing.
\subsubsection*{(slashified [ ])}
Outputs the string \q{}, escaping any quote or escape characters.
If \q{} is \q{#f} escapes only the \q{} by
doubling it, as in SQL strings and CSV values. If \q{} is
provided, it should be a procedure of one character which maps that
character to its escape value, e.g. \q{#\newline => #\n}, or \q{#f} if
there is no escape value.
\q{(fmt #f (slashified "hi, \"bob!\""))}
\q{=> "hi, \"bob!\""}
\subsubsection*{(maybe-slashified [ ])}
Like \q{slashified}, but first checks if any quoting is required (by
the existence of either any quote or escape characters, or any
character matching \q{}), and if so outputs the string in quotes
and with escapes. Otherwise outputs the string as is.
\q{(fmt #f (maybe-slashified "foo" char-whitespace? #\"))}
\q{=> "foo"}
\q{(fmt #f (maybe-slashified "foo bar" char-whitespace? #\"))}
\q{=> "\"foo bar\""}
\q{(fmt #f (maybe-slashified "foo\"bar\"baz" char-whitespace? #\"))}
\q{=> "\"foo\"bar\"baz\""}
\subsection{Formatting Numbers}
\subsubsection*{(num [ ])}
Formats a single number \q{}. You can optionally specify any
\q{} from 2 to 36 (even if \q{} isn't an integer).
\q{} forces a fixed-point format.
A \q{} of \q{#t} indicates to output a plus sign (+) for positive
integers. However, if \q{} is a character, it means to wrap the
number with that character and its mirror opposite if the number is
negative. For example, \q{#\(} prints negative numbers in parenthesis,
financial style: \q{-3.14 => (3.14)}
\q{} is an integer specifying the number of digits between
commas. Variable length, as in subcontinental-style, is not yet
supported.
\q{} is the character to use for commas, defaulting to \q{#\,}.
\q{} is the character to use for decimals, defaulting to
\q{#\.}, or to \q{#\,} (European style) if \q{} is already
\q{#\.}.
These parameters may seem unwieldy, but they can also take their
defaults from state variables, described below.
\subsubsection*{(num/comma [ ])}
Shortcut for \q{num} to print with commas.
\q{(fmt #f (num/comma 1234567))}
\q{=> "1,234,567"}
\subsubsection*{(num/si [ ])}
Abbreviates \q{} with an SI suffix as in the -h or --si option to
many GNU commands. The base defaults to 1024, using suffix names
like Ki, Mi, Gi, etc. Other bases (e.g. the standard 1000) have the
suffixes k, M, G, etc.
The \q{} argument is appended only if an abbreviation is used.
\q{(fmt #f (num/si 608))}
\q{=> "608"}
\q{(fmt #f (num/si 3986))}
\q{=> "3.9Ki"}
\q{(fmt #f (num/si 3986 1000 "B"))}
\q{=> "4kB"}
See \urlh{http://www.bipm.org/en/si/si_brochure/chapter3/prefixes.html}{http://www.bipm.org/en/si/si_brochure/chapter3/prefixes.html}.
\subsubsection*{(num/fit . )}
Like \q{num}, but if the result doesn't fit in \q{}, output
instead a string of hashes (with the current \q{}) rather
than showing an incorrectly truncated number. For example
\q{(fmt #f (fix 2 (num/fit 4 12.345)))}
\q{=> "#.##"}
\subsubsection*{(num/roman )}
Formats the number as a Roman numeral:
\q{(fmt #f (num/roman 1989))}
\q{=> "MCMLXXXIX"}
\subsubsection*{(num/old-roman )}
Formats the number as an old-style Roman numeral, without the
subtraction abbreviation rule:
\q{(fmt #f (num/old-roman 1989))}
\q{=> "MDCCCCLXXXVIIII"}
\subsection{Formatting Space}
\subsubsection*{nl}
Outputs a newline.
\subsubsection*{fl}
Short for "fresh line," outputs a newline only if we're not already
at the start of a line.
\subsubsection*{(space-to )}
Outputs spaces up to the given \q{}. If the current column is
already >= \q{}, does nothing.
\subsubsection*{(tab-to [])}
Outputs spaces up to the next tab stop, using tab stops of width
\q{}, which defaults to 8. If already on a tab stop, does
nothing. If you want to ensure you always tab at least one space, you
can use \q{(cat " " (tab-to width))}.
\subsubsection*{fmt-null}
Outputs nothing (useful in combinators and as a default noop in
conditionals).
\subsection{Concatenation}
\subsubsection*{(cat ...)}
Concatenates the output of each \q{}.
\subsubsection*{(apply-cat )}
Equivalent to \q{(apply cat )} but may be more efficient.
\subsubsection*{(fmt-join [])}
Formats each element \q{} of \q{} with \q{(
)}, inserting \q{} in between. \q{} defaults to the
empty string, but can be any format.
\q{(fmt #f (fmt-join dsp '(a b c) ", "))}
\q{=> "a, b, c"}
\subsubsection*{(fmt-join/prefix [])}
\subsubsection*{(fmt-join/suffix [])}
\q{(fmt #f (fmt-join/prefix dsp '(usr local bin) "/"))}
\q{=> "/usr/local/bin"}
As \q{fmt-join}, but inserts \q{} before/after every element.
\subsubsection*{(fmt-join/last [])}
As \q{fmt-join}, but the last element of the list is formatted with
\q{} instead.
\subsubsection*{(fmt-join/dot [])}
As \q{fmt-join}, but if the list is a dotted list, then formats the dotted
value with \q{} instead.
\subsection{Padding and Trimming}
\subsubsection*{(pad ...)}
\subsubsection*{(pad/left ...)}
\subsubsection*{(pad/both ...)}
Analogs of SRFI-13 \q{string-pad}, these add extra space to the left,
right or both sides of the output generated by the \q{}s to
pad it to \q{}. If \q{} is exceeded has no effect.
\q{pad/both} will include an extra space on the right side of the
output if the difference is odd.
\q{pad} does not accumulate any intermediate data.
Note these are column-oriented padders, so won't necessarily work
with multi-line output (padding doesn't seem a likely operation for
multi-line output).
\subsubsection*{(trim ...)}
\subsubsection*{(trim/left ...)}
\subsubsection*{(trim/both ...)}
Analogs of SRFI-13 \q{string-trim}, truncates the output of the
\q{}s to force it in under \q{} columns. As soon as
any of the \q{}s exceed \q{}, stop formatting and
truncate the result, returning control to whoever called \q{trim}. If
\q{} is not exceeded has no effect.
If a truncation ellipse is set (e.g. with the \q{ellipses} procedure
below), then when any truncation occurs \q{trim} and \q{trim/left}
will append and prepend the ellipse, respectively. \q{trim/both} will
both prepend and append. The length of the ellipse will be considered
when truncating the original string, so that the total width will
never be longer than \q{}.
\q{(fmt #f (ellipses "..." (trim 5 "abcde")))}
\q{=> "abcde"}
\q{(fmt #f (ellipses "..." (trim 5 "abcdef")))}
\q{=> "ab..."}
\subsubsection*{(trim/length ...)}
A variant of \q{trim} which acts on the actual character count rather
than columns, useful for truncating potentially cyclic data.
\subsubsection*{(fit ...)}
\subsubsection*{(fit/left ...)}
\subsubsection*{(fit/both ...)}
A combination of \q{pad} and \q{trunc}, ensures the output width is
exactly \q{}, truncating if it goes over and padding if it goes
under.
\subsection{Format Variables}
You may have noticed many of the formatters are aware of the current
column. This is because each combinator is actually a procedure of
one argument, the current format state, which holds basic
information such as the row, column, and any other information that
a format combinator may want to keep track of. The basic interface
is:
\subsubsection*{(fmt-let ...)}
\subsubsection*{(fmt-bind ...)}
\q{fmt-let} sets the name for the duration of the \q{}s, and
restores it on return. \q{fmt-bind} sets it without restoring it.
A convenience control structure can be useful in combination with
these states:
\subsubsection*{(fmt-if [])}
\q{} takes one argument (the format state) and returns a boolean
result. If true, the \q{} format is applied to the state,
otherwise \q{} (defaulting to the identity) is applied.
Many of the previously mentioned combinators have behavior which can
be altered with state variables. Although \q{fmt-let} and \q{fmt-bind}
could be used, these common variables have shortcuts:
\subsubsection*{(radix ...)}
\subsubsection*{(fix ...)}
These alter the radix and fixed point precision of numbers output with
\q{dsp}, \q{wrt}, \q{pretty} or \q{num}. These settings apply
recursively to all output data structures, so that
\q{(fmt #f (radix 16 '(70 80 90)))}
will return the string \q{"(#x46 #x50 #x5a)"}. Note that read/write
invariance is essential, so for \q{dsp}, \q{wrt} and \q{pretty} the
radix prefix is always included when not decimal. Use \q{num} if you
want to format numbers in alternate bases without this prefix. For
example,
\q{(fmt #f (radix 16 "(" (fmt-join num '(70 80 90) " ") ")"))}
would return \q{"(46 50 5a)"}, the same output as above without the
"#x" radix prefix.
Note that fixed point formatting supports arbitrary precision in
implementations with exact non-integral rationals. When trying to
print inexact numbers more than the machine precision you will
typically get results like
\q{(fmt #f (fix 30 #i2/3))}
\q{=> "0.666666666666666600000000000000"}
but with an exact rational it will give you as many digits as you
request:
\q{(fmt #f (fix 30 2/3))}
\q{=> "0.666666666666666666666666666667"}
\subsubsection*{(decimal-align ...)}
Specifies an alignment for the decimal place when formatting numbers,
useful for outputting tables of numbers.
\q{
(define (print-angles x)
(fmt-join num (list x (sin x) (cos x) (tan x)) " "))
(fmt #t (decimal-align 5 (fix 3 (fmt-join/suffix print-angles (iota 5) nl))))
}
would output
\p{
0.000 0.000 1.000 0.000
1.000 0.842 0.540 1.557
2.000 0.909 -0.416 -2.185
3.000 0.141 -0.990 -0.142
4.000 -0.757 -0.654 1.158
}
\subsubsection*{(comma-char ...)}
\subsubsection*{(decimal-char ...)}
\q{comma-char} and \q{decimal-char} set the defaults for number
formatting.
\subsubsection*{(pad-char ...)}
The \q{pad-char} sets the character used by \q{space-to}, \q{tab-to},
\q{pad/*}, and \q{fit/*}, and defaults to \q{#\space}.
\q{
(define (print-table-of-contents alist)
(define (print-line x)
(cat (car x) (space-to 72) (pad/left 3 (cdr x))))
(fmt #t (pad-char #\. (fmt-join/suffix print-line alist nl))))
(print-table-of-contents
'(("An Unexpected Party" . 29)
("Roast Mutton" . 60)
("A Short Rest" . 87)
("Over Hill and Under Hill" . 100)
("Riddles in the Dark" . 115)))
}
would output
\p{
An Unexpected Party.....................................................29
Roast Mutton............................................................60
A Short Rest............................................................87
Over Hill and Under Hill...............................................100
Riddles in the Dark....................................................115
}
\subsubsection*{(ellipse ...)}
Sets the truncation ellipse to \q{}, would should be a string or
character.
\subsubsection*{(with-width ...)}
Sets the maximum column width used by some formatters. The default
is 78.
\subsection{Columnar Formatting}
Although \q{tab-to}, \q{space-to} and padding can be used to manually
align columns to produce table-like output, these can be awkward to
use. The optional extensions in this section make this easier.
\subsubsection*{(columnar ...)}
Formats each \q{} side-by-side, i.e. as though each were
formatted separately and then the individual lines concatenated
together. The current column width is divided evenly among the
columns, and all but the last column are right-padded. For example
\q{(fmt #t (columnar (dsp "abc\\ndef\\n") (dsp "123\\n456\\n")))}
outputs
\p{
abc 123
def 456
}
assuming a 16-char width (the left side gets half the width, or 8
spaces, and is left aligned). Note that we explicitly use DSP instead
of the strings directly. This is because \q{columnar} treats raw
strings as literals inserted into the given location on every line, to
be used as borders, for example:
\q{
(fmt #t (columnar "/* " (dsp "abc\\ndef\\n")
" | " (dsp "123\\n456\\n")
" */"))
}
would output
\p{
/* abc | 123 */
/* def | 456 */
}
You may also prefix any column with any of the symbols \q{'left},
\q{'right} or \q{'center} to control the justification. The symbol
\q{'infinite} can be used to indicate the column generates an infinite
stream of output.
You can further prefix any column with a width modifier. Any
positive integer is treated as a fixed width, ignoring the available
width. Any real number between 0 and 1 indicates a fraction of the
available width (after subtracting out any fixed widths). Columns
with unspecified width divide up the remaining width evenly.
Note that \q{columnar} builds its output incrementally, interleaving
calls to the generators until each has produced a line, then
concatenating that line together and outputting it. This is important
because as noted above, some columns may produce an infinite stream of
output, and in general you may want to format data larger than can fit
into memory. Thus columnar would be suitable for line numbering a
file of arbitrary size, or implementing the Unix \q{yes(1)} command,
etc.
As an implementation detail, \q{columnar} uses first-class
continuations to interleave the column output. The core \q{fmt}
itself has no knowledge of or special support for \q{columnar}, which
could complicate and potentially slow down simpler \q{fmt} operations.
This is a testament to the power of \q{call/cc} - it can be used to
implement coroutines or arbitrary control structures even where they
were not planned for.
\subsubsection*{(tabular ...)}
Equivalent to \q{columnar} except that each column is padded at least
to the minimum width required on any of its lines. Thus
\q{(fmt #t (tabular "|" (dsp "a\\nbc\\ndef\\n") "|" (dsp "123\\n45\\n6\\n") "|"))}
outputs
\p{
|a |123|
|bc |45 |
|def|6 |
}
This makes it easier to generate tables without knowing widths in
advance. However, because it requires generating the entire output in
advance to determine the correct column widths, \q{tabular} cannot
format a table larger than would fit in memory.
\subsubsection*{(fmt-columns ...)}
The low-level formatter on which \q{columnar} is based. Each \q{}
must be a list of 2-3 elements:
\q{( [])}
where \q{} is the column generator as above, and the
\q{} is how each line is formatted. Raw concatenation
of each line is performed, without any spacing or width adjustment.
\q{}, if true, indicates this generator produces an
infinite number of lines and termination should be determined without
it.
\subsubsection*{(wrap-lines ...)}
Behaves like \q{cat}, except text is accumulated and lines are optimally
wrapped to fit in the current width as in the Unix \p{fmt(1)} command.
\subsubsection*{(justify ...)}
Like \q{wrap-lines} except the lines are full-justified.
\q{
(define func
'(define (fold kons knil ls)
(let lp ((ls ls) (acc knil))
(if (null? ls) acc (lp (cdr ls) (kons (car ls) acc))))))
(define doc
(string-append
"The fundamental list iterator. Applies KONS to each element "
"of LS and the result of the previous application, beginning "
"with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))
(fmt #t (columnar (pretty func) " ; " (justify doc)))
}
outputs
\p{
(define (fold kons knil ls) ; The fundamental list iterator.
(let lp ((ls ls) (acc knil)) ; Applies KONS to each element of
(if (null? ls) ; LS and the result of the previous
acc ; application, beginning with KNIL.
(lp (cdr ls) ; With KONS as CONS and KNIL as '(),
(kons (car ls) acc))))) ; equivalent to REVERSE.
}
\subsubsection*{(fmt-file )}
Simply displayes the contents of the file \q{} a line at a
time, so that in typical formatters such as \q{columnar} only constant
memory is consumed, making this suitable for formatting files of
arbitrary size.
\subsubsection*{(line-numbers [])}
A convenience utility, just formats an infinite stream of numbers (in
the current radix) beginning with \q{}, which defaults to \q{1}.
The Unix \q{nl(1)} utility could be implemented as:
\q{
(fmt #t (columnar 6 'right 'infinite (line-numbers)
" " (fmt-file "read-line.scm")))
}
\p{
1
2 (define (read-line . o)
3 (let ((port (if (pair? o) (car o) (current-input-port))))
4 (let lp ((res '()))
5 (let ((c (read-char port)))
6 (if (or (eof-object? c) (eqv? c #\newline))
7 (list->string (reverse res))
8 (lp (cons c res)))))))
}
\section{C Formatting}
\subsection{C Formatting Basics}
For purposes such as writing wrappers, code-generators, compilers or
other language tools, people often need to generate or emit C code.
Without a decent library framework it's difficult to maintain proper
indentation. In addition, for the Scheme programmer it's tedious to
work with all the context sensitivities of C, such as the expression
vs. statement distinction, special rules for writing preprocessor
macros, and when precedence rules require parenthesis. Fortunately,
context is one thing this formatting library is good at keeping
track of. The C formatting interface tries to make it as easy as
possible to generate C code without getting in your way.
There are two approaches to using the C formatting extensions -
procedural and sexp-oriented (described in \ref{csexprs}). In the
procedural interface, C operators are made available as formatters
with a "c-" prefix, literals are converted to their C equivalents and
symbols are output as-is (you're responsible for making sure they are
valid C identifiers). Indentation is handled automatically.
\q{(fmt #t (c-if 1 2 3))}
outputs
\p{
if (1) {
2;
} else {
3;
}
}
In addition, the formatter knows when you're in an expression and
when you're in a statement, and behaves accordingly, so that
\q{(fmt #t (c-if (c-if 1 2 3) 4 5))}
outputs
\p{
if (1 ? 2 : 3) {
4;
} else {
5;
}
}
Similary, \q{c-begin}, used for sequencing, will separate with
semi-colons in a statement and commas in an expression.
Moreover, we also keep track of the final expression in a function
and insert returns for you:
\q{(fmt #t (c-fun 'int 'foo '() (c-if (c-if 1 2 3) 4 5)))}
outputs
\p{
int foo () {
if (1 ? 2 : 3) {
return 4;
} else {
return 5;
}
}
}
although it knows that void functions don't return.
Switch statements insert breaks by default if they don't return:
\q{
(fmt #t (c-switch 'y
(c-case 1 (c+= 'x 1))
(c-default (c+= 'x 2))))
}
\p{
switch (y) {
case 1:
x += 1;
break;
default:
x += 2;
break;
}
}
though you can explicitly fallthrough if you want:
\q{
(fmt #t (c-switch 'y
(c-case/fallthrough 1 (c+= 'x 1))
(c-default (c+= 'x 2))))
}
\p{
switch (y) {
case 1:
x += 1;
default:
x += 2;
break;
}
}
Operators are available with just a "c" prefix, e.g. c+, c-, c*, c/,
etc. \q{c++} is a prefix operator, \q{c++/post} is postfix. ||, | and
|= are written as \q{c-or}, \q{c-bit-or} and \q{c-bit-or=} respectively.
Function applications are written with \q{c-apply}. Other control
structures such as \q{c-for} and \q{c-while} work as expected. The full
list is in the procedure index below.
When a C formatter encounters an object it doesn't know how to write
(including lists and records), it outputs them according to the
format state's current \q{'gen} variable. This allows you to specify
generators for your own types, e.g. if you are using your own AST
records in a compiler.
If the \q{'gen} variable isn't set it defaults to the \q{c-expr/sexp}
procedure, which formats an s-expression as if it were C code. Thus
instead of \q{c-apply} you can just use a list. The full API is
available via normal s-expressions - formatters that aren't keywords
in C are prefixed with a % or otherwise made invalid C identifiers so
that they can't be confused with function application.
\subsection{C Preprocessor Formatting}
C preprocessor formatters also properly handle their surrounding
context, so you can safely intermix them in the normal flow of C
code.
\q{
(fmt #t (c-switch 'y
(c-case 1 (c= 'x 1))
(cpp-ifdef 'H_TWO (c-case 2 (c= 'x 4)))
(c-default (c= 'x 5))))
}
\p{
switch (y) {
case 1:
x = 1;
break;
#ifdef H_TWO
case 2:
x = 4;
break;
#endif /* H_TWO */
default:
x = 5;
break;
}
}
Macros can be handled with \q{cpp-define}, which knows to wrap
individual variable references in parenthesis:
\q{(fmt #t (cpp-define '(min x y) (c-if (c< 'x 'y) 'x 'y)))}
\p{
#define min(x, y) (((x) < (y)) ? (x) : (y))
}
As with all C formatters, the CPP output is pretty printed as
needed, and if it wraps over several lines the lines are terminated
with a backslash.
To write a C header file that is included at most once, you can wrap
the entire body in \q{cpp-wrap-header}:
\q{
(fmt #t (cpp-wrap-header "FOO_H"
(c-extern (c-prototype 'int 'foo '()))))
}
\p{
#ifndef FOO_H
#define FOO_H
extern int foo ();
#endif /* ! FOO_H */
}
\subsection{Customizing C Style}
The output uses a simplified K&R style with 4 spaces for indentation
by default. The following state variables let you override the
style:
\subsubsection*{'indent-space}
how many spaces to indent bodies, default \q{4}
\subsubsection*{'switch-indent-space}
how many spaces to indent switch clauses, also defaults to \q{4}
\subsubsection*{'newline-before-brace?}
insert a newline before an open brace (non-K&R), defaults to \q{#f}
\subsubsection*{'braceless-bodies?}
omit braces when we can prove they aren't needed
\subsubsection*{'non-spaced-ops?}
omit spaces between operators and operands for groups of variables and
literals (e.g. "a+b+3" instead of "a + b + 3"}
\subsubsection*{'no-wrap?}
Don't wrap function calls and long operator groups over mulitple
lines. Functions and control structures will still use multiple
lines.
The C formatters also respect the \q{'radix} and \q{'precision} settings.
\subsection{C Formatter Index}
\subsubsection*{(c-if [ [ ...]])}
Print a chain of if/else conditions. Use a final condition of \q{'else}
for a final else clause.
\subsubsection*{(c-for ...)}
\subsubsection*{(c-while ...)}
Basic loop constructs.
\subsubsection*{(c-fun ...)}
\subsubsection*{(c-prototype )}
Output a function or function prototype. The parameters should be a
list 2-element lists of the form \q{( )},
which are output with DSP. A parameter can be abbreviated as just the
symbol name, or \q{#f} can be passed as the type, in which case the
\q{'default-type} state variable is used. The parameters may be a
dotted list, in which case ellipses for a C variadic are inserted -
the actual name of the dotted value is ignored.
Types are just typically just symbols, or lists of symbols such as
\q{'(const char)}. A complete description is given below in section
\ref{ctypes}.
These can also accessed as %fun and %prototype at the head of a list.
\subsubsection*{(c-var [])}
Declares and optionally initializes a variable. Also accessed as %var
at the head of a list.
\subsubsection*{(c-begin ...)}
Outputs each of the s, separated by semi-colons if in a
statement or commas if in an expression.
\subsubsection*{(c-switch ...)}
\subsubsection*{(c-case ...)}
\subsubsection*{(c-case/fallthrough ...)}
\subsubsection*{(c-default ...)}
Switch statements. In addition to using the clause formatters,
clauses inside a switch may be handled with a Scheme CASE-like list,
with the car a list of case values and the cdr the body.
\subsubsection*{(c-label )}
\subsubsection*{(c-goto )}
\subsubsection*{(c-return [])}
\subsubsection*{c-break}
\subsubsection*{c-continue}
Manual labels and jumps. Labels can also be accessed as a list
beginning with a colon, e.g. \q{'(: label1)}.
\subsubsection*{(c-const )}
\subsubsection*{(c-static )}
\subsubsection*{(c-volatile )}
\subsubsection*{(c-restrict )}
\subsubsection*{(c-register )}
\subsubsection*{(c-auto )}
\subsubsection*{(c-inline )}
\subsubsection*{(c-extern )}
Declaration modifiers. May be nested.
\subsubsection*{(c-extern/C ...)}
Wraps body in an extern "C" { ... } for use with C++.
\subsubsection*{(c-cast )}
Casts an expression to a type. Also %cast at the head of a list.
\subsubsection*{(c-typedef ...)}
Creates a new type definition with one or more names.
\subsubsection*{(c-struct [] [])}
\subsubsection*{(c-union [] [])}
\subsubsection*{(c-class [] [])}
\subsubsection*{(c-attribute ...)}
Composite type constructors. Attributes may be accessed as
%attribute at the head of a list.
\q{
(fmt #f (c-struct 'employee
'((short age)
((char *) name)
((struct (year month day)) dob))
(c-attribute 'packed)))
}
\p{
struct employee {
short age;
char* name;
struct {
int year;
int month;
int day;
} dob;
} __attribute__ ((packed));
}
\subsubsection*{(c-enum [] )}
Enumerated types. \q{} may be strings, symbols, or lists of
string or symbol followed by the enum's value.
\subsubsection*{(c-comment ...)}
Outputs the \q{}s wrapped in C's /* ... */ comment. Properly
escapes nested comments inside in an Emacs-friendly style.
\subsection{C Preprocessor Formatter Index}
\subsubsection*{(cpp-include )}
If file is a string, outputs in it "quotes", otherwise (as a symbol
or arbitrary formatter) it outputs it in brackets.
\q{(fmt #f (cpp-include 'stdio.h))}
\q{=> "#include \n"}
\q{(fmt #f (cpp-include "config.h"))}
\q{=> "#include \"config.h\"\n"}
\subsubsection*{(cpp-define [])}
Defines a preprocessor macro, which may be just a name or a list of
name and parameters. Properly wraps the value in parenthesis and
escapes newlines. A dotted parameter list will use the C99 variadic
macro syntax, and will also substitute any references to the dotted
name with \p{__VA_ARGS__}:
\q{(fmt #t (cpp-define '(eprintf . args) '(fprintf stderr args)))}
\p{
#define eprintf(...) (fprintf(stderr, __VA_ARGS__))
}
\subsubsection*{(cpp-if [ ...])}
\subsubsection*{(cpp-ifdef [ ...])}
\subsubsection*{(cpp-ifndef [ ...])}
\subsubsection*{(cpp-elif [ ...])}
\subsubsection*{(cpp-else ...)}
Conditional compilation.
\subsubsection*{(cpp-line [])}
Line number information.
\subsubsection*{(cpp-pragma ...)}
\subsubsection*{(cpp-error ...)}
\subsubsection*{(cpp-warning ...)}
Additional preprocessor directives.
\subsubsection*{(cpp-stringify )}
Stringifies \q{} by prefixing the # operator.
\subsubsection*{(cpp-sym-cat ...)}
Joins the \q{} into a single preprocessor token with the ##
operator.
\subsubsection*{(cpp-wrap-header ...)}
Wrap an entire header to only be included once.
\subsubsection*{Operators:}
\q{
c++ c-- c+ c- c* c/ c% c& c^ c~ c! c&& c<< c>> c== c!=
c< c> c<= c>= c= c+= c-= c*= c/= c%= c&= c^= c<<= c>>=
c++/post c--/post c-or c-bit-or c-bit-or=
}
\subsection{C Types}
\label{ctypes}
Typically a type is just a symbol such as \q{'char} or \q{'int}. You
can wrap types with modifiers such as \q{c-const}, but as a
convenience you can just use a list such as in \q{'(const unsignedchar *)}.
You can also nest these lists, so the previous example is
equivalent to \q{'(* (const (unsigned char)))}.
Pointers may be written as \q{'(%pointer )} for readability -
\q{%pointer} is exactly equivalent to \q{*} in types.
Unamed structs, classes, unions and enums may be used directly as
types, using their respective keywords at the head of a list.
Two special types are the %array type and function pointer type. An
array is written:
\q{(%array [