tabwriter.go 19 KB

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