...

Source file src/github.com/liggitt/tabwriter/tabwriter.go

Documentation: github.com/liggitt/tabwriter

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

View as plain text