github.com/euank/go@v0.0.0-20160829210321-495514729181/src/text/tabwriter/tabwriter.go (about)

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