David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package ansiterm |
| 5 | |
| 6 | import ( |
| 7 | "io" |
| 8 | |
| 9 | "github.com/juju/ansiterm/tabwriter" |
| 10 | ) |
| 11 | |
| 12 | // NewTabWriter returns a writer that is able to set colors and styels. |
| 13 | // The ansi escape codes are stripped for width calculations. |
| 14 | func NewTabWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *TabWriter { |
| 15 | return new(TabWriter).Init(output, minwidth, tabwidth, padding, padchar, flags) |
| 16 | } |
| 17 | |
| 18 | // TabWriter is a filter that inserts padding around tab-delimited |
| 19 | // columns in its input to align them in the output. |
| 20 | // |
| 21 | // It also setting of colors and styles over and above the standard |
| 22 | // tabwriter package. |
| 23 | type TabWriter struct { |
| 24 | Writer |
| 25 | tw tabwriter.Writer |
| 26 | } |
| 27 | |
| 28 | // Flush should be called after the last call to Write to ensure |
| 29 | // that any data buffered in the Writer is written to output. Any |
| 30 | // incomplete escape sequence at the end is considered |
| 31 | // complete for formatting purposes. |
| 32 | // |
| 33 | func (t *TabWriter) Flush() error { |
| 34 | return t.tw.Flush() |
| 35 | } |
| 36 | |
| 37 | // SetColumnAlignRight will mark a particular column as align right. |
| 38 | // This is reset on the next flush. |
| 39 | func (t *TabWriter) SetColumnAlignRight(column int) { |
| 40 | t.tw.SetColumnAlignRight(column) |
| 41 | } |
| 42 | |
| 43 | // A Writer must be initialized with a call to Init. The first parameter (output) |
| 44 | // specifies the filter output. The remaining parameters control the formatting: |
| 45 | // |
| 46 | // minwidth minimal cell width including any padding |
| 47 | // tabwidth width of tab characters (equivalent number of spaces) |
| 48 | // padding padding added to a cell before computing its width |
| 49 | // padchar ASCII char used for padding |
| 50 | // if padchar == '\t', the Writer will assume that the |
| 51 | // width of a '\t' in the formatted output is tabwidth, |
| 52 | // and cells are left-aligned independent of align_left |
| 53 | // (for correct-looking results, tabwidth must correspond |
| 54 | // to the tab width in the viewer displaying the result) |
| 55 | // flags formatting control |
| 56 | // |
| 57 | func (t *TabWriter) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *TabWriter { |
| 58 | writer, colorCapable := colorEnabledWriter(output) |
| 59 | t.Writer = Writer{ |
| 60 | Writer: t.tw.Init(writer, minwidth, tabwidth, padding, padchar, flags), |
| 61 | noColor: !colorCapable, |
| 62 | } |
| 63 | return t |
| 64 | } |