Source file src/text/tabwriter/tabwriter.go

     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.
     4  
     5  // Package tabwriter implements a write filter (tabwriter.Writer) that
     6  // translates tabbed columns in input into properly aligned text.
     7  //
     8  // The package is using the Elastic Tabstops algorithm described at
     9  // http://nickgravgaard.com/elastictabstops/index.html.
    10  //
    11  // The text/tabwriter package is frozen and is not accepting new features.
    12  package tabwriter
    13  
    14  import (
    15  	"io"
    16  	"unicode/utf8"
    17  )
    18  
    19  // ----------------------------------------------------------------------------
    20  // Filter implementation
    21  
    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.
    26  type cell struct {
    27  	size  int  // cell size in bytes
    28  	width int  // cell width in runes
    29  	htab  bool // true if the cell is terminated by an htab ('\t')
    30  }
    31  
    32  // A Writer is a filter that inserts padding around tab-delimited
    33  // columns in its input to align them in the output.
    34  //
    35  // The Writer treats incoming bytes as UTF-8-encoded text consisting
    36  // of cells terminated by horizontal ('\t') or vertical ('\v') tabs,
    37  // and newline ('\n') or formfeed ('\f') characters; both newline and
    38  // formfeed act as line breaks.
    39  //
    40  // Tab-terminated cells in contiguous lines constitute a column. The
    41  // Writer inserts padding as needed to make all cells in a column have
    42  // the same width, effectively aligning the columns. It assumes that
    43  // all characters have the same width, except for tabs for which a
    44  // tabwidth must be specified. Column cells must be tab-terminated, not
    45  // tab-separated: non-tab terminated trailing text at the end of a line
    46  // forms a cell but that cell is not part of an aligned column.
    47  // For instance, in this example (where | stands for a horizontal tab):
    48  //
    49  //	aaaa|bbb|d
    50  //	aa  |b  |dd
    51  //	a   |
    52  //	aa  |cccc|eee
    53  //
    54  // the b and c are in distinct columns (the b column is not contiguous
    55  // all the way). The d and e are not in a column at all (there's no
    56  // terminating tab, nor would the column be contiguous).
    57  //
    58  // The Writer assumes that all Unicode code points have the same width;
    59  // this may not be true in some fonts or if the string contains combining
    60  // characters.
    61  //
    62  // If DiscardEmptyColumns is set, empty columns that are terminated
    63  // entirely by vertical (or "soft") tabs are discarded. Columns
    64  // terminated by horizontal (or "hard") tabs are not affected by
    65  // this flag.
    66  //
    67  // If a Writer is configured to filter HTML, HTML tags and entities
    68  // are passed through. The widths of tags and entities are
    69  // assumed to be zero (tags) and one (entities) for formatting purposes.
    70  //
    71  // A segment of text may be escaped by bracketing it with Escape
    72  // characters. The tabwriter passes escaped text segments through
    73  // unchanged. In particular, it does not interpret any tabs or line
    74  // breaks within the segment. If the StripEscape flag is set, the
    75  // Escape characters are stripped from the output; otherwise they
    76  // are passed through as well. For the purpose of formatting, the
    77  // width of the escaped text is always computed excluding the Escape
    78  // characters.
    79  //
    80  // The formfeed character acts like a newline but it also terminates
    81  // all columns in the current line (effectively calling Flush). Tab-
    82  // terminated cells in the next line start new columns. Unless found
    83  // inside an HTML tag or inside an escaped text segment, formfeed
    84  // characters appear as newlines in the output.
    85  //
    86  // The Writer must buffer input internally, because proper spacing
    87  // of one line may depend on the cells in future lines. Clients must
    88  // call Flush when done calling Write.
    89  type Writer struct {
    90  	// configuration
    91  	output   io.Writer
    92  	minwidth int
    93  	tabwidth int
    94  	padding  int
    95  	padbytes [8]byte
    96  	flags    uint
    97  
    98  	// current state
    99  	buf     []byte   // collected text excluding tabs or line breaks
   100  	pos     int      // buffer position up to which cell.width of incomplete cell has been computed
   101  	cell    cell     // current incomplete cell; cell.width is up to buf[pos] excluding ignored sections
   102  	endChar byte     // terminating char of escaped sequence (Escape for escapes, '>', ';' for HTML tags/entities, or 0)
   103  	lines   [][]cell // list of lines; each line is a list of cells
   104  	widths  []int    // list of column widths in runes - re-used during formatting
   105  }
   106  
   107  // addLine adds a new line.
   108  // flushed is a hint indicating whether the underlying writer was just flushed.
   109  // If so, the previous line is not likely to be a good indicator of the new line's cells.
   110  func (b *Writer) addLine(flushed bool) {
   111  	// Grow slice instead of appending,
   112  	// as that gives us an opportunity
   113  	// to re-use an existing []cell.
   114  	if n := len(b.lines) + 1; n <= cap(b.lines) {
   115  		b.lines = b.lines[:n]
   116  		b.lines[n-1] = b.lines[n-1][:0]
   117  	} else {
   118  		b.lines = append(b.lines, nil)
   119  	}
   120  
   121  	if !flushed {
   122  		// The previous line is probably a good indicator
   123  		// of how many cells the current line will have.
   124  		// If the current line's capacity is smaller than that,
   125  		// abandon it and make a new one.
   126  		if n := len(b.lines); n >= 2 {
   127  			if prev := len(b.lines[n-2]); prev > cap(b.lines[n-1]) {
   128  				b.lines[n-1] = make([]cell, 0, prev)
   129  			}
   130  		}
   131  	}
   132  }
   133  
   134  // Reset the current state.
   135  func (b *Writer) reset() {
   136  	b.buf = b.buf[:0]
   137  	b.pos = 0
   138  	b.cell = cell{}
   139  	b.endChar = 0
   140  	b.lines = b.lines[0:0]
   141  	b.widths = b.widths[0:0]
   142  	b.addLine(true)
   143  }
   144  
   145  // Internal representation (current state):
   146  //
   147  // - all text written is appended to buf; tabs and line breaks are stripped away
   148  // - at any given time there is a (possibly empty) incomplete cell at the end
   149  //   (the cell starts after a tab or line break)
   150  // - cell.size is the number of bytes belonging to the cell so far
   151  // - cell.width is text width in runes of that cell from the start of the cell to
   152  //   position pos; html tags and entities are excluded from this width if html
   153  //   filtering is enabled
   154  // - the sizes and widths of processed text are kept in the lines list
   155  //   which contains a list of cells for each line
   156  // - the widths list is a temporary list with current widths used during
   157  //   formatting; it is kept in Writer because it's re-used
   158  //
   159  //                    |<---------- size ---------->|
   160  //                    |                            |
   161  //                    |<- width ->|<- ignored ->|  |
   162  //                    |           |             |  |
   163  // [---processed---tab------------<tag>...</tag>...]
   164  // ^                  ^                         ^
   165  // |                  |                         |
   166  // buf                start of incomplete cell  pos
   167  
   168  // Formatting can be controlled with these flags.
   169  const (
   170  	// Ignore html tags and treat entities (starting with '&'
   171  	// and ending in ';') as single characters (width = 1).
   172  	FilterHTML uint = 1 << iota
   173  
   174  	// Strip Escape characters bracketing escaped text segments
   175  	// instead of passing them through unchanged with the text.
   176  	StripEscape
   177  
   178  	// Force right-alignment of cell content.
   179  	// Default is left-alignment.
   180  	AlignRight
   181  
   182  	// Handle empty columns as if they were not present in
   183  	// the input in the first place.
   184  	DiscardEmptyColumns
   185  
   186  	// Always use tabs for indentation columns (i.e., padding of
   187  	// leading empty cells on the left) independent of padchar.
   188  	TabIndent
   189  
   190  	// Print a vertical bar ('|') between columns (after formatting).
   191  	// Discarded columns appear as zero-width columns ("||").
   192  	Debug
   193  )
   194  
   195  // A Writer must be initialized with a call to Init. The first parameter (output)
   196  // specifies the filter output. The remaining parameters control the formatting:
   197  //
   198  //	minwidth	minimal cell width including any padding
   199  //	tabwidth	width of tab characters (equivalent number of spaces)
   200  //	padding		padding added to a cell before computing its width
   201  //	padchar		ASCII char used for padding
   202  //			if padchar == '\t', the Writer will assume that the
   203  //			width of a '\t' in the formatted output is tabwidth,
   204  //			and cells are left-aligned independent of align_left
   205  //			(for correct-looking results, tabwidth must correspond
   206  //			to the tab width in the viewer displaying the result)
   207  //	flags		formatting control
   208  func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
   209  	if minwidth < 0 || tabwidth < 0 || padding < 0 {
   210  		panic("negative minwidth, tabwidth, or padding")
   211  	}
   212  	b.output = output
   213  	b.minwidth = minwidth
   214  	b.tabwidth = tabwidth
   215  	b.padding = padding
   216  	for i := range b.padbytes {
   217  		b.padbytes[i] = padchar
   218  	}
   219  	if padchar == '\t' {
   220  		// tab padding enforces left-alignment
   221  		flags &^= AlignRight
   222  	}
   223  	b.flags = flags
   224  
   225  	b.reset()
   226  
   227  	return b
   228  }
   229  
   230  // debugging support (keep code around)
   231  func (b *Writer) dump() {
   232  	pos := 0
   233  	for i, line := range b.lines {
   234  		print("(", i, ") ")
   235  		for _, c := range line {
   236  			print("[", string(b.buf[pos:pos+c.size]), "]")
   237  			pos += c.size
   238  		}
   239  		print("\n")
   240  	}
   241  	print("\n")
   242  }
   243  
   244  // local error wrapper so we can distinguish errors we want to return
   245  // as errors from genuine panics (which we don't want to return as errors)
   246  type osError struct {
   247  	err error
   248  }
   249  
   250  func (b *Writer) write0(buf []byte) {
   251  	n, err := b.output.Write(buf)
   252  	if n != len(buf) && err == nil {
   253  		err = io.ErrShortWrite
   254  	}
   255  	if err != nil {
   256  		panic(osError{err})
   257  	}
   258  }
   259  
   260  func (b *Writer) writeN(src []byte, n int) {
   261  	for n > len(src) {
   262  		b.write0(src)
   263  		n -= len(src)
   264  	}
   265  	b.write0(src[0:n])
   266  }
   267  
   268  var (
   269  	newline = []byte{'\n'}
   270  	tabs    = []byte("\t\t\t\t\t\t\t\t")
   271  )
   272  
   273  func (b *Writer) writePadding(textw, cellw int, useTabs bool) {
   274  	if b.padbytes[0] == '\t' || useTabs {
   275  		// padding is done with tabs
   276  		if b.tabwidth == 0 {
   277  			return // tabs have no width - can't do any padding
   278  		}
   279  		// make cellw the smallest multiple of b.tabwidth
   280  		cellw = (cellw + b.tabwidth - 1) / b.tabwidth * b.tabwidth
   281  		n := cellw - textw // amount of padding
   282  		if n < 0 {
   283  			panic("internal error")
   284  		}
   285  		b.writeN(tabs, (n+b.tabwidth-1)/b.tabwidth)
   286  		return
   287  	}
   288  
   289  	// padding is done with non-tab characters
   290  	b.writeN(b.padbytes[0:], cellw-textw)
   291  }
   292  
   293  var vbar = []byte{'|'}
   294  
   295  func (b *Writer) writeLines(pos0 int, line0, line1 int) (pos int) {
   296  	pos = pos0
   297  	for i := line0; i < line1; i++ {
   298  		line := b.lines[i]
   299  
   300  		// if TabIndent is set, use tabs to pad leading empty cells
   301  		useTabs := b.flags&TabIndent != 0
   302  
   303  		for j, c := range line {
   304  			if j > 0 && b.flags&Debug != 0 {
   305  				// indicate column break
   306  				b.write0(vbar)
   307  			}
   308  
   309  			if c.size == 0 {
   310  				// empty cell
   311  				if j < len(b.widths) {
   312  					b.writePadding(c.width, b.widths[j], useTabs)
   313  				}
   314  			} else {
   315  				// non-empty cell
   316  				useTabs = false
   317  				if b.flags&AlignRight == 0 { // align left
   318  					b.write0(b.buf[pos : pos+c.size])
   319  					pos += c.size
   320  					if j < len(b.widths) {
   321  						b.writePadding(c.width, b.widths[j], false)
   322  					}
   323  				} else { // align right
   324  					if j < len(b.widths) {
   325  						b.writePadding(c.width, b.widths[j], false)
   326  					}
   327  					b.write0(b.buf[pos : pos+c.size])
   328  					pos += c.size
   329  				}
   330  			}
   331  		}
   332  
   333  		if i+1 == len(b.lines) {
   334  			// last buffered line - we don't have a newline, so just write
   335  			// any outstanding buffered data
   336  			b.write0(b.buf[pos : pos+b.cell.size])
   337  			pos += b.cell.size
   338  		} else {
   339  			// not the last line - write newline
   340  			b.write0(newline)
   341  		}
   342  	}
   343  	return
   344  }
   345  
   346  // Format the text between line0 and line1 (excluding line1); pos
   347  // is the buffer position corresponding to the beginning of line0.
   348  // Returns the buffer position corresponding to the beginning of
   349  // line1 and an error, if any.
   350  func (b *Writer) format(pos0 int, line0, line1 int) (pos int) {
   351  	pos = pos0
   352  	column := len(b.widths)
   353  	for this := line0; this < line1; this++ {
   354  		line := b.lines[this]
   355  
   356  		if column >= len(line)-1 {
   357  			continue
   358  		}
   359  		// cell exists in this column => this line
   360  		// has more cells than the previous line
   361  		// (the last cell per line is ignored because cells are
   362  		// tab-terminated; the last cell per line describes the
   363  		// text before the newline/formfeed and does not belong
   364  		// to a column)
   365  
   366  		// print unprinted lines until beginning of block
   367  		pos = b.writeLines(pos, line0, this)
   368  		line0 = this
   369  
   370  		// column block begin
   371  		width := b.minwidth // minimal column width
   372  		discardable := true // true if all cells in this column are empty and "soft"
   373  		for ; this < line1; this++ {
   374  			line = b.lines[this]
   375  			if column >= len(line)-1 {
   376  				break
   377  			}
   378  			// cell exists in this column
   379  			c := line[column]
   380  			// update width
   381  			if w := c.width + b.padding; w > width {
   382  				width = w
   383  			}
   384  			// update discardable
   385  			if c.width > 0 || c.htab {
   386  				discardable = false
   387  			}
   388  		}
   389  		// column block end
   390  
   391  		// discard empty columns if necessary
   392  		if discardable && b.flags&DiscardEmptyColumns != 0 {
   393  			width = 0
   394  		}
   395  
   396  		// format and print all columns to the right of this column
   397  		// (we know the widths of this column and all columns to the left)
   398  		b.widths = append(b.widths, width) // push width
   399  		pos = b.format(pos, line0, this)
   400  		b.widths = b.widths[0 : len(b.widths)-1] // pop width
   401  		line0 = this
   402  	}
   403  
   404  	// print unprinted lines until end
   405  	return b.writeLines(pos, line0, line1)
   406  }
   407  
   408  // Append text to current cell.
   409  func (b *Writer) append(text []byte) {
   410  	b.buf = append(b.buf, text...)
   411  	b.cell.size += len(text)
   412  }
   413  
   414  // Update the cell width.
   415  func (b *Writer) updateWidth() {
   416  	b.cell.width += utf8.RuneCount(b.buf[b.pos:])
   417  	b.pos = len(b.buf)
   418  }
   419  
   420  // To escape a text segment, bracket it with Escape characters.
   421  // For instance, the tab in this string "Ignore this tab: \xff\t\xff"
   422  // does not terminate a cell and constitutes a single character of
   423  // width one for formatting purposes.
   424  //
   425  // The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
   426  const Escape = '\xff'
   427  
   428  // Start escaped mode.
   429  func (b *Writer) startEscape(ch byte) {
   430  	switch ch {
   431  	case Escape:
   432  		b.endChar = Escape
   433  	case '<':
   434  		b.endChar = '>'
   435  	case '&':
   436  		b.endChar = ';'
   437  	}
   438  }
   439  
   440  // Terminate escaped mode. If the escaped text was an HTML tag, its width
   441  // is assumed to be zero for formatting purposes; if it was an HTML entity,
   442  // its width is assumed to be one. In all other cases, the width is the
   443  // unicode width of the text.
   444  func (b *Writer) endEscape() {
   445  	switch b.endChar {
   446  	case Escape:
   447  		b.updateWidth()
   448  		if b.flags&StripEscape == 0 {
   449  			b.cell.width -= 2 // don't count the Escape chars
   450  		}
   451  	case '>': // tag of zero width
   452  	case ';':
   453  		b.cell.width++ // entity, count as one rune
   454  	}
   455  	b.pos = len(b.buf)
   456  	b.endChar = 0
   457  }
   458  
   459  // Terminate the current cell by adding it to the list of cells of the
   460  // current line. Returns the number of cells in that line.
   461  func (b *Writer) terminateCell(htab bool) int {
   462  	b.cell.htab = htab
   463  	line := &b.lines[len(b.lines)-1]
   464  	*line = append(*line, b.cell)
   465  	b.cell = cell{}
   466  	return len(*line)
   467  }
   468  
   469  func (b *Writer) handlePanic(err *error, op string) {
   470  	if e := recover(); e != nil {
   471  		if op == "Flush" {
   472  			// If Flush ran into a panic, we still need to reset.
   473  			b.reset()
   474  		}
   475  		if nerr, ok := e.(osError); ok {
   476  			*err = nerr.err
   477  			return
   478  		}
   479  		panic("tabwriter: panic during " + op)
   480  	}
   481  }
   482  
   483  // Flush should be called after the last call to Write to ensure
   484  // that any data buffered in the Writer is written to output. Any
   485  // incomplete escape sequence at the end is considered
   486  // complete for formatting purposes.
   487  func (b *Writer) Flush() error {
   488  	return b.flush()
   489  }
   490  
   491  // flush is the internal version of Flush, with a named return value which we
   492  // don't want to expose.
   493  func (b *Writer) flush() (err error) {
   494  	defer b.handlePanic(&err, "Flush")
   495  	b.flushNoDefers()
   496  	return nil
   497  }
   498  
   499  // flushNoDefers is like flush, but without a deferred handlePanic call. This
   500  // can be called from other methods which already have their own deferred
   501  // handlePanic calls, such as Write, and avoid the extra defer work.
   502  func (b *Writer) flushNoDefers() {
   503  	// add current cell if not empty
   504  	if b.cell.size > 0 {
   505  		if b.endChar != 0 {
   506  			// inside escape - terminate it even if incomplete
   507  			b.endEscape()
   508  		}
   509  		b.terminateCell(false)
   510  	}
   511  
   512  	// format contents of buffer
   513  	b.format(0, 0, len(b.lines))
   514  	b.reset()
   515  }
   516  
   517  var hbar = []byte("---\n")
   518  
   519  // Write writes buf to the writer b.
   520  // The only errors returned are ones encountered
   521  // while writing to the underlying output stream.
   522  func (b *Writer) Write(buf []byte) (n int, err error) {
   523  	defer b.handlePanic(&err, "Write")
   524  
   525  	// split text into cells
   526  	n = 0
   527  	for i, ch := range buf {
   528  		if b.endChar == 0 {
   529  			// outside escape
   530  			switch ch {
   531  			case '\t', '\v', '\n', '\f':
   532  				// end of cell
   533  				b.append(buf[n:i])
   534  				b.updateWidth()
   535  				n = i + 1 // ch consumed
   536  				ncells := b.terminateCell(ch == '\t')
   537  				if ch == '\n' || ch == '\f' {
   538  					// terminate line
   539  					b.addLine(ch == '\f')
   540  					if ch == '\f' || ncells == 1 {
   541  						// A '\f' always forces a flush. Otherwise, if the previous
   542  						// line has only one cell which does not have an impact on
   543  						// the formatting of the following lines (the last cell per
   544  						// line is ignored by format()), thus we can flush the
   545  						// Writer contents.
   546  						b.flushNoDefers()
   547  						if ch == '\f' && b.flags&Debug != 0 {
   548  							// indicate section break
   549  							b.write0(hbar)
   550  						}
   551  					}
   552  				}
   553  
   554  			case Escape:
   555  				// start of escaped sequence
   556  				b.append(buf[n:i])
   557  				b.updateWidth()
   558  				n = i
   559  				if b.flags&StripEscape != 0 {
   560  					n++ // strip Escape
   561  				}
   562  				b.startEscape(Escape)
   563  
   564  			case '<', '&':
   565  				// possibly an html tag/entity
   566  				if b.flags&FilterHTML != 0 {
   567  					// begin of tag/entity
   568  					b.append(buf[n:i])
   569  					b.updateWidth()
   570  					n = i
   571  					b.startEscape(ch)
   572  				}
   573  			}
   574  
   575  		} else {
   576  			// inside escape
   577  			if ch == b.endChar {
   578  				// end of tag/entity
   579  				j := i + 1
   580  				if ch == Escape && b.flags&StripEscape != 0 {
   581  					j = i // strip Escape
   582  				}
   583  				b.append(buf[n:j])
   584  				n = i + 1 // ch consumed
   585  				b.endEscape()
   586  			}
   587  		}
   588  	}
   589  
   590  	// append leftover text
   591  	b.append(buf[n:])
   592  	n = len(buf)
   593  	return
   594  }
   595  
   596  // NewWriter allocates and initializes a new tabwriter.Writer.
   597  // The parameters are the same as for the Init function.
   598  func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer {
   599  	return new(Writer).Init(output, minwidth, tabwidth, padding, padchar, flags)
   600  }
   601  

View as plain text