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 // Package tabwriter implements a write filter (tabwriter.Writer) that
6 // 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.
19 // ----------------------------------------------------------------------------
20 // Filter implementation
22 // A cell represents a segment of text terminated by tabs or line breaks.
23 // The text itself is stored in a separate buffer; cell only describes the
24 // segment's size in bytes, its width in runes, and whether it's an htab
25 // ('\t') terminated cell.
28 size int // cell size in bytes
29 width int // cell width in runes
30 htab bool // true if the cell is terminated by an htab ('\t')
33 // A Writer is a filter that inserts padding around tab-delimited
34 // columns in its input to align them in the output.
36 // The Writer treats incoming bytes as UTF-8 encoded text consisting
37 // of cells terminated by (horizontal or vertical) tabs or line
38 // breaks (newline or formfeed characters). Cells in adjacent lines
39 // constitute a column. The Writer inserts padding as needed to
40 // make all cells in a column have the same width, effectively
41 // aligning the columns. It assumes that all characters have the
42 // same width except for tabs for which a tabwidth must be specified.
43 // Note that cells are tab-terminated, not tab-separated: trailing
44 // non-tab text at the end of a line does not form a column cell.
46 // The Writer assumes that all Unicode code points have the same width;
47 // this may not be true in some fonts.
49 // If DiscardEmptyColumns is set, empty columns that are terminated
50 // entirely by vertical (or "soft") tabs are discarded. Columns
51 // terminated by horizontal (or "hard") tabs are not affected by
54 // If a Writer is configured to filter HTML, HTML tags and entities
55 // are passed through. The widths of tags and entities are
56 // assumed to be zero (tags) and one (entities) for formatting purposes.
58 // A segment of text may be escaped by bracketing it with Escape
59 // characters. The tabwriter passes escaped text segments through
60 // unchanged. In particular, it does not interpret any tabs or line
61 // breaks within the segment. If the StripEscape flag is set, the
62 // Escape characters are stripped from the output; otherwise they
63 // are passed through as well. For the purpose of formatting, the
64 // width of the escaped text is always computed excluding the Escape
67 // The formfeed character ('\f') acts like a newline but it also
68 // terminates all columns in the current line (effectively calling
69 // Flush). Cells in the next line start new columns. Unless found
70 // inside an HTML tag or inside an escaped text segment, formfeed
71 // characters appear as newlines in the output.
73 // The Writer must buffer input internally, because proper spacing
74 // of one line may depend on the cells in future lines. Clients must
75 // call Flush when done calling Write.
87 buf bytes.Buffer // collected text excluding tabs or line breaks
88 pos int // buffer position up to which cell.width of incomplete cell has been computed
89 cell cell // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections
90 endChar byte // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0)
91 lines [][]cell // list of lines; each line is a list of cells
92 widths []int // list of column widths in runes - re-used during formatting
95 func (b *Writer) addLine() { b.lines = append(b.lines, []cell{}) }
97 // Reset the current state.
98 func (b *Writer) reset() {
103 b.lines = b.lines[0:0]
104 b.widths = b.widths[0:0]
108 // Internal representation (current state):
110 // - all text written is appended to buf; tabs and line breaks are stripped away
111 // - at any given time there is a (possibly empty) incomplete cell at the end
112 // (the cell starts after a tab or line break)
113 // - cell.size is the number of bytes belonging to the cell so far
114 // - cell.width is text width in runes of that cell from the start of the cell to
115 // position pos; html tags and entities are excluded from this width if html
116 // filtering is enabled
117 // - the sizes and widths of processed text are kept in the lines list
118 // which contains a list of cells for each line
119 // - the widths list is a temporary list with current widths used during
120 // formatting; it is kept in Writer because it's re-used
122 // |<---------- size ---------->|
124 // |<- width ->|<- ignored ->| |
126 // [---processed---tab------------<tag>...</tag>...]
129 // buf start of incomplete cell pos
131 // Formatting can be controlled with these flags.
133 // Ignore html tags and treat entities (starting with '&'
134 // and ending in ';') as single characters (width = 1).
135 FilterHTML uint = 1 << iota
137 // Strip Escape characters bracketing escaped text segments
138 // instead of passing them through unchanged with the text.
141 // Force right-alignment of cell content.
142 // Default is left-alignment.
145 // Handle empty columns as if they were not present in
146 // the input in the first place.
149 // Always use tabs for indentation columns (i.e., padding of
150 // leading empty cells on the left) independent of padchar.
153 // Print a vertical bar ('|') between columns (after formatting).
154 // Discarded columns appear as zero-width columns ("||").
158 // A Writer must be initialized with a call to Init. The first parameter (output)
159 // specifies the filter output. The remaining parameters control the formatting:
161 // minwidth minimal cell width including any padding
162 // tabwidth width of tab characters (equivalent number of spaces)
163 // padding padding added to a cell before computing its width
164 // padchar ASCII char used for padding
165 // if padchar == '\t', the Writer will assume that the
166 // width of a '\t' in the formatted output is tabwidth,
167 // and cells are left-aligned independent of align_left
168 // (for correct-looking results, tabwidth must correspond
169 // to the tab width in the viewer displaying the result)
170 // flags formatting control
172 func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
173 if minwidth < 0 || tabwidth < 0 || padding < 0 {
174 panic("negative minwidth, tabwidth, or padding")
177 b.minwidth = minwidth
178 b.tabwidth = tabwidth
180 for i := range b.padbytes {
181 b.padbytes[i] = padchar
184 // tab padding enforces left-alignment
194 // debugging support (keep code around)
195 func (b *Writer) dump() {
197 for i, line := range b.lines {
199 for _, c := range line {
200 print("[", string(b.buf.Bytes()[pos:pos+c.size]), "]")
208 // local error wrapper so we can distinguish errors we want to return
209 // as errors from genuine panics (which we don't want to return as errors)
210 type osError struct {
214 func (b *Writer) write0(buf []byte) {
215 n, err := b.output.Write(buf)
216 if n != len(buf) && err == nil {
217 err = io.ErrShortWrite
224 func (b *Writer) writeN(src []byte, n int) {
233 newline = []byte{'\n'}
234 tabs = []byte("\t\t\t\t\t\t\t\t")
237 func (b *Writer) writePadding(textw, cellw int, useTabs bool) {
238 if b.padbytes[0] == '\t' || useTabs {
239 // padding is done with tabs
241 return // tabs have no width - can't do any padding
243 // make cellw the smallest multiple of b.tabwidth
244 cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth
245 n := cellw - textw // amount of padding
247 panic("internal error")
249 b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth)
253 // padding is done with non-tab characters
254 b.writeN(b.padbytes[0:], cellw-textw)
257 var vbar = []byte{'|'}
259 func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) {
261 for i := line0; i < line1; i++ {
264 // if TabIndent is set, use tabs to pad leading empty cells
265 useTabs := b.flags&TabIndent != 0
267 for j, c := range line {
268 if j > 0 && b.flags&Debug != 0 {
269 // indicate column break
275 if j < len(b.widths) {
276 b.writePadding(c.width, b.widths[j], useTabs)
281 if b.flags&AlignRight == 0 { // align left
282 b.write0(b.buf.Bytes()[pos : pos+c.size])
284 if j < len(b.widths) {
285 b.writePadding(c.width, b.widths[j], false)
287 } else { // align right
288 if j < len(b.widths) {
289 b.writePadding(c.width, b.widths[j], false)
291 b.write0(b.buf.Bytes()[pos : pos+c.size])
297 if i+1 == len(b.lines) {
298 // last buffered line - we don't have a newline, so just write
299 // any outstanding buffered data
300 b.write0(b.buf.Bytes()[pos : pos+b.cell.size])
303 // not the last line - write newline
310 // Format the text between line0 and line1 (excluding line1); pos
311 // is the buffer position corresponding to the beginning of line0.
312 // Returns the buffer position corresponding to the beginning of
313 // line1 and an error, if any.
315 func (b *Writer) format(pos0 int, line0, line1 int) (pos int) {
317 column := len(b.widths)
318 for this := line0; this < line1; this++ {
319 line := b.lines[this]
321 if column < len(line)-1 {
322 // cell exists in this column => this line
323 // has more cells than the previous line
324 // (the last cell per line is ignored because cells are
325 // tab-terminated; the last cell per line describes the
326 // text before the newline/formfeed and does not belong
329 // print unprinted lines until beginning of block
330 pos = b.writeLines(pos, line0, this)
333 // column block begin
334 width := b.minwidth // minimal column width
335 discardable := true // true if all cells in this column are empty and "soft"
336 for ; this < line1; this++ {
338 if column < len(line)-1 {
339 // cell exists in this column
342 if w := c.width + b.padding; w > width {
345 // update discardable
346 if c.width > 0 || c.htab {
355 // discard empty columns if necessary
356 if discardable && b.flags&DiscardEmptyColumns != 0 {
360 // format and print all columns to the right of this column
361 // (we know the widths of this column and all columns to the left)
362 b.widths = append(b.widths, width) // push width
363 pos = b.format(pos, line0, this)
364 b.widths = b.widths[0 : len(b.widths)-1] // pop width
369 // print unprinted lines until end
370 return b.writeLines(pos, line0, line1)
373 // Append text to current cell.
374 func (b *Writer) append(text []byte) {
376 b.cell.size += len(text)
379 // Update the cell width.
380 func (b *Writer) updateWidth() {
381 b.cell.width += utf8.RuneCount(b.buf.Bytes()[b.pos:b.buf.Len()])
385 // To escape a text segment, bracket it with Escape characters.
386 // For instance, the tab in this string "Ignore this tab: \xff\t\xff"
387 // does not terminate a cell and constitutes a single character of
388 // width one for formatting purposes.
390 // The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
392 const Escape = '\xff'
394 // Start escaped mode.
395 func (b *Writer) startEscape(ch byte) {
406 // Terminate escaped mode. If the escaped text was an HTML tag, its width
407 // is assumed to be zero for formatting purposes; if it was an HTML entity,
408 // its width is assumed to be one. In all other cases, the width is the
409 // unicode width of the text.
411 func (b *Writer) endEscape() {
415 if b.flags&StripEscape == 0 {
416 b.cell.width -= 2 // don't count the Escape chars
418 case '>': // tag of zero width
420 b.cell.width++ // entity, count as one rune
426 // Terminate the current cell by adding it to the list of cells of the
427 // current line. Returns the number of cells in that line.
429 func (b *Writer) terminateCell(htab bool) int {
431 line := &b.lines[len(b.lines)-1]
432 *line = append(*line, b.cell)
437 func handlePanic(err *error) {
438 if e := recover(); e != nil {
439 *err = e.(osError).err // re-panics if it's not a local osError
443 // Flush should be called after the last call to Write to ensure
444 // that any data buffered in the Writer is written to output. Any
445 // incomplete escape sequence at the end is considered
446 // complete for formatting purposes.
448 func (b *Writer) Flush() (err error) {
449 defer b.reset() // even in the presence of errors
450 defer handlePanic(&err)
452 // add current cell if not empty
455 // inside escape - terminate it even if incomplete
458 b.terminateCell(false)
461 // format contents of buffer
462 b.format(0, 0, len(b.lines))
467 var hbar = []byte("---\n")
469 // Write writes buf to the writer b.
470 // The only errors returned are ones encountered
471 // while writing to the underlying output stream.
473 func (b *Writer) Write(buf []byte) (n int, err error) {
474 defer handlePanic(&err)
476 // split text into cells
478 for i, ch := range buf {
482 case '\t', '\v', '\n', '\f':
486 n = i + 1 // ch consumed
487 ncells := b.terminateCell(ch == '\t')
488 if ch == '\n' || ch == '\f' {
491 if ch == '\f' || ncells == 1 {
492 // A '\f' always forces a flush. Otherwise, if the previous
493 // line has only one cell which does not have an impact on
494 // the formatting of the following lines (the last cell per
495 // line is ignored by format()), thus we can flush the
497 if err = b.Flush(); err != nil {
500 if ch == '\f' && b.flags&Debug != 0 {
501 // indicate section break
508 // start of escaped sequence
512 if b.flags&StripEscape != 0 {
515 b.startEscape(Escape)
518 // possibly an html tag/entity
519 if b.flags&FilterHTML != 0 {
520 // begin of tag/entity
533 if ch == Escape && b.flags&StripEscape != 0 {
534 j = i // strip Escape
537 n = i + 1 // ch consumed
543 // append leftover text
549 // NewWriter allocates and initializes a new tabwriter.Writer.
550 // The parameters are the same as for the Init function.
552 func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
553 return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags)