CodeWriterApril 5: The CodeWriter class has been updated with a new version that generates the optimum format.
The CodeWriter class provides
essential support for pretty-printing: automatically
formatting structured text. When a CodeWriter
object is created, two parameters have to be specified:
an OutputStream object o and an
integer width. The CodeWriter
will format text onto o while keeping the width of the
output within width characters if possible.
It can be a little tricky to get the expected output when you first
use
CodeWriter. But after some experiments, you will find it
is a nice tool. Here are some tips that might shorten your learning
time.
CodeWriter.begin and blocksbegin
method call and ends with the nearest end method
call. CodeWriter will try to squeeze the whole block
into one line. If this cannot be done, CodeWriter
will output the block in several lines according to the
allowBreak and newline method calls
you make in the block. Suppose the current cursor position
is "pos". The first line of the block will start
at "pos". All the following lines will start at
"pos+n" in which "n" is a parameter of
begin method. newline and allowBreaknewline forces the insertion of a line break.
allowBreak merely allows the formatter to insert a
line break. If CodeWriter can output a block in one
line, all the allowBreak calls in the block
will be ignored. However, if there is any newline
method call in a block, every allowBreak in the block
will incur a line change no matter what. So newline
is not recommended unless you don't really don't want the block
to sit in one line. When you observe the output of the sample,
you will find Block1 and Block3 are similar except one
allowBreak in
Block1 is replaced by a newline in Block3. You should
be able to figure out how the small change affects the output.