1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // The tabwriter package implements a write filter (tabwriter.Writer)
6 // that translates tabbed columns in input into properly aligned text.
8 // The package is using the Elastic Tabstops algorithm described at
9 // http://nickgravgaard.com/elastictabstops/index.html.
21 // ----------------------------------------------------------------------------
22 // Filter implementation
24 // A cell represents a segment of text terminated by tabs or line breaks.
25 // The text itself is stored in a separate buffer; cell only describes the
26 // segment's size in bytes, its width in runes, and whether it's an htab
27 // ('\t') terminated cell.
30 size int // cell size in bytes
31 width int // cell width in runes
32 htab bool // true if the cell is terminated by an htab ('\t')
36 // A Writer is a filter that inserts padding around tab-delimited
37 // columns in its input to align them in the output.
39 // The Writer treats incoming bytes as UTF-8 encoded text consisting
40 // of cells terminated by (horizontal or vertical) tabs or line
41 // breaks (newline or formfeed characters). Cells in adjacent lines
42 // constitute a column. The Writer inserts padding as needed to
43 // make all cells in a column have the same width, effectively
44 // aligning the columns. It assumes that all characters have the
45 // same width except for tabs for which a tabwidth must be specified.
46 // Note that cells are tab-terminated, not tab-separated: trailing
47 // non-tab text at the end of a line does not form a column cell.
49 // The Writer assumes that all Unicode code points have the same width;
50 // this may not be true in some fonts.
52 // If DiscardEmptyColumns is set, empty columns that are terminated
53 // entirely by vertical (or "soft") tabs are discarded. Columns
54 // terminated by horizontal (or "hard") tabs are not affected by
57 // If a Writer is configured to filter HTML, HTML tags and entities
58 // are simply passed through. The widths of tags and entities are
59 // assumed to be zero (tags) and one (entities) for formatting purposes.
61 // A segment of text may be escaped by bracketing it with Escape
62 // characters. The tabwriter passes escaped text segments through
63 // unchanged. In particular, it does not interpret any tabs or line
64 // breaks within the segment. If the StripEscape flag is set, the
65 // Escape characters are stripped from the output; otherwise they
66 // are passed through as well. For the purpose of formatting, the
67 // width of the escaped text is always computed excluding the Escape
70 // The formfeed character ('\f') acts like a newline but it also
71 // terminates all columns in the current line (effectively calling
72 // Flush). Cells in the next line start new columns. Unless found
73 // inside an HTML tag or inside an escaped text segment, formfeed
74 // characters appear as newlines in the output.
76 // The Writer must buffer input internally, because proper spacing
77 // of one line may depend on the cells in future lines. Clients must
78 // call Flush when done calling Write.
90 buf bytes.Buffer // collected text excluding tabs or line breaks
91 pos int // buffer position up to which cell.width of incomplete cell has been computed
92 cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections
93 endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0)
94 lines [][]cell // list of lines; each line is a list of cells
95 widths []int // list of column widths in runes - re-used during formatting
99 func (b *Writer) addLine() { b.lines = append(b.lines, []cell{}) }
102 // Reset the current state.
103 func (b *Writer) reset() {
108 b.lines = b.lines[0:0]
109 b.widths = b.widths[0:0]
114 // Internal representation (current state):
116 // - all text written is appended to buf; tabs and line breaks are stripped away
117 // - at any given time there is a (possibly empty) incomplete cell at the end
118 // (the cell starts after a tab or line break)
119 // - cell.size is the number of bytes belonging to the cell so far
120 // - cell.width is text width in runes of that cell from the start of the cell to
121 // position pos; html tags and entities are excluded from this width if html
122 // filtering is enabled
123 // - the sizes and widths of processed text are kept in the lines list
124 // which contains a list of cells for each line
125 // - the widths list is a temporary list with current widths used during
126 // formatting; it is kept in Writer because it's re-used
128 // |<---------- size ---------->|
130 // |<- width ->|<- ignored ->| |
132 // [---processed---tab------------<tag>...</tag>...]
135 // buf start of incomplete cell pos
138 // Formatting can be controlled with these flags.
140 // Ignore html tags and treat entities (starting with '&'
141 // and ending in ';') as single characters (width = 1).
142 FilterHTML uint = 1 << iota
144 // Strip Escape characters bracketing escaped text segments
145 // instead of passing them through unchanged with the text.
148 // Force right-alignment of cell content.
149 // Default is left-alignment.
152 // Handle empty columns as if they were not present in
153 // the input in the first place.
156 // Always use tabs for indentation columns (i.e., padding of
157 // leading empty cells on the left) independent of padchar.
160 // Print a vertical bar ('|') between columns (after formatting).
161 // Discarded colums appear as zero-width columns ("||").
166 // A Writer must be initialized with a call to Init. The first parameter (output)
167 // specifies the filter output. The remaining parameters control the formatting:
169 // minwidth minimal cell width including any padding
170 // tabwidth width of tab characters (equivalent number of spaces)
171 // padding padding added to a cell before computing its width
172 // padchar ASCII char used for padding
173 // if padchar == '\t', the Writer will assume that the
174 // width of a '\t' in the formatted output is tabwidth,
175 // and cells are left-aligned independent of align_left
176 // (for correct-looking results, tabwidth must correspond
177 // to the tab width in the viewer displaying the result)
178 // flags formatting control
180 // To format in tab-separated columns with a tab stop of 8:
181 // b.Init(w, 8, 1, 8, '\t', 0);
183 // To format in space-separated columns with at least 4 spaces between columns:
184 // b.Init(w, 0, 4, 8, ' ', 0);
186 func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
187 if minwidth < 0 || tabwidth < 0 || padding < 0 {
188 panic("negative minwidth, tabwidth, or padding")
191 b.minwidth = minwidth
192 b.tabwidth = tabwidth
194 for i := range b.padbytes {
195 b.padbytes[i] = padchar
198 // tab padding enforces left-alignment
209 // debugging support (keep code around)
210 func (b *Writer) dump() {
212 for i, line := range b.lines {
214 for _, c := range line {
215 print("[", string(b.buf.Bytes()[pos:pos+c.size]), "]")
224 // local error wrapper so we can distinguish os.Errors we want to return
225 // as errors from genuine panics (which we don't want to return as errors)
226 type osError struct {
231 func (b *Writer) write0(buf []byte) {
232 n, err := b.output.Write(buf)
233 if n != len(buf) && err == nil {
242 func (b *Writer) writeN(src []byte, n int) {
252 newline = []byte{'\n'}
253 tabs = []byte("\t\t\t\t\t\t\t\t")
257 func (b *Writer) writePadding(textw, cellw int, useTabs bool) {
258 if b.padbytes[0] == '\t' || useTabs {
259 // padding is done with tabs
261 return // tabs have no width - can't do any padding
263 // make cellw the smallest multiple of b.tabwidth
264 cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth
265 n := cellw - textw // amount of padding
267 panic("internal error")
269 b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth)
273 // padding is done with non-tab characters
274 b.writeN(b.padbytes[0:], cellw-textw)
278 var vbar = []byte{'|'}
280 func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) {
282 for i := line0; i < line1; i++ {
285 // if TabIndent is set, use tabs to pad leading empty cells
286 useTabs := b.flags&TabIndent != 0
288 for j, c := range line {
289 if j > 0 && b.flags&Debug != 0 {
290 // indicate column break
296 if j < len(b.widths) {
297 b.writePadding(c.width, b.widths[j], useTabs)
302 if b.flags&AlignRight == 0 { // align left
303 b.write0(b.buf.Bytes()[pos : pos+c.size])
305 if j < len(b.widths) {
306 b.writePadding(c.width, b.widths[j], false)
308 } else { // align right
309 if j < len(b.widths) {
310 b.writePadding(c.width, b.widths[j], false)
312 b.write0(b.buf.Bytes()[pos : pos+c.size])
318 if i+1 == len(b.lines) {
319 // last buffered line - we don't have a newline, so just write
320 // any outstanding buffered data
321 b.write0(b.buf.Bytes()[pos : pos+b.cell.size])
324 // not the last line - write newline
332 // Format the text between line0 and line1 (excluding line1); pos
333 // is the buffer position corresponding to the beginning of line0.
334 // Returns the buffer position corresponding to the beginning of
335 // line1 and an error, if any.
337 func (b *Writer) format(pos0 int, line0, line1 int) (pos int) {
339 column := len(b.widths)
340 for this := line0; this < line1; this++ {
341 line := b.lines[this]
343 if column < len(line)-1 {
344 // cell exists in this column => this line
345 // has more cells than the previous line
346 // (the last cell per line is ignored because cells are
347 // tab-terminated; the last cell per line describes the
348 // text before the newline/formfeed and does not belong
351 // print unprinted lines until beginning of block
352 pos = b.writeLines(pos, line0, this)
355 // column block begin
356 width := b.minwidth // minimal column width
357 discardable := true // true if all cells in this column are empty and "soft"
358 for ; this < line1; this++ {
360 if column < len(line)-1 {
361 // cell exists in this column
364 if w := c.width + b.padding; w > width {
367 // update discardable
368 if c.width > 0 || c.htab {
377 // discard empty columns if necessary
378 if discardable && b.flags&DiscardEmptyColumns != 0 {
382 // format and print all columns to the right of this column
383 // (we know the widths of this column and all columns to the left)
384 b.widths = append(b.widths, width) // push width
385 pos = b.format(pos, line0, this)
386 b.widths = b.widths[0 : len(b.widths)-1] // pop width
391 // print unprinted lines until end
392 return b.writeLines(pos, line0, line1)
396 // Append text to current cell.
397 func (b *Writer) append(text []byte) {
399 b.cell.size += len(text)
403 // Update the cell width.
404 func (b *Writer) updateWidth() {
405 b.cell.width += utf8.RuneCount(b.buf.Bytes()[b.pos:b.buf.Len()])
410 // To escape a text segment, bracket it with Escape characters.
411 // For instance, the tab in this string "Ignore this tab: \xff\t\xff"
412 // does not terminate a cell and constitutes a single character of
413 // width one for formatting purposes.
415 // The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
417 const Escape = '\xff'
420 // Start escaped mode.
421 func (b *Writer) startEscape(ch byte) {
433 // Terminate escaped mode. If the escaped text was an HTML tag, its width
434 // is assumed to be zero for formatting purposes; if it was an HTML entity,
435 // its width is assumed to be one. In all other cases, the width is the
436 // unicode width of the text.
438 func (b *Writer) endEscape() {
442 if b.flags&StripEscape == 0 {
443 b.cell.width -= 2 // don't count the Escape chars
445 case '>': // tag of zero width
447 b.cell.width++ // entity, count as one rune
454 // Terminate the current cell by adding it to the list of cells of the
455 // current line. Returns the number of cells in that line.
457 func (b *Writer) terminateCell(htab bool) int {
459 line := &b.lines[len(b.lines)-1]
460 *line = append(*line, b.cell)
466 func handlePanic(err *os.Error) {
467 if e := recover(); e != nil {
468 *err = e.(osError).err // re-panics if it's not a local osError
473 // Flush should be called after the last call to Write to ensure
474 // that any data buffered in the Writer is written to output. Any
475 // incomplete escape sequence at the end is simply considered
476 // complete for formatting purposes.
478 func (b *Writer) Flush() (err os.Error) {
479 defer b.reset() // even in the presence of errors
480 defer handlePanic(&err)
482 // add current cell if not empty
485 // inside escape - terminate it even if incomplete
488 b.terminateCell(false)
491 // format contents of buffer
492 b.format(0, 0, len(b.lines))
498 var hbar = []byte("---\n")
500 // Write writes buf to the writer b.
501 // The only errors returned are ones encountered
502 // while writing to the underlying output stream.
504 func (b *Writer) Write(buf []byte) (n int, err os.Error) {
505 defer handlePanic(&err)
507 // split text into cells
509 for i, ch := range buf {
513 case '\t', '\v', '\n', '\f':
517 n = i + 1 // ch consumed
518 ncells := b.terminateCell(ch == '\t')
519 if ch == '\n' || ch == '\f' {
522 if ch == '\f' || ncells == 1 {
523 // A '\f' always forces a flush. Otherwise, if the previous
524 // line has only one cell which does not have an impact on
525 // the formatting of the following lines (the last cell per
526 // line is ignored by format()), thus we can flush the
528 if err = b.Flush(); err != nil {
531 if ch == '\f' && b.flags&Debug != 0 {
532 // indicate section break
539 // start of escaped sequence
543 if b.flags&StripEscape != 0 {
546 b.startEscape(Escape)
549 // possibly an html tag/entity
550 if b.flags&FilterHTML != 0 {
551 // begin of tag/entity
564 if ch == Escape && b.flags&StripEscape != 0 {
565 j = i // strip Escape
568 n = i + 1 // ch consumed
574 // append leftover text
581 // NewWriter allocates and initializes a new tabwriter.Writer.
582 // The parameters are the same as for the the Init function.
584 func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
585 return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags)