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