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