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 | "fmt" |
| 8 | "io" |
| 9 | ) |
| 10 | |
| 11 | // Writer allows colors and styles to be specified. If the io.Writer |
| 12 | // is not a terminal capable of color, all attempts to set colors or |
| 13 | // styles are no-ops. |
| 14 | type Writer struct { |
| 15 | io.Writer |
| 16 | |
| 17 | noColor bool |
| 18 | } |
| 19 | |
| 20 | // NewWriter returns a Writer that allows the caller to specify colors and |
| 21 | // styles. If the io.Writer is not a terminal capable of color, all attempts |
| 22 | // to set colors or styles are no-ops. |
| 23 | func NewWriter(w io.Writer) *Writer { |
| 24 | writer, colorCapable := colorEnabledWriter(w) |
| 25 | return &Writer{ |
| 26 | Writer: writer, |
| 27 | noColor: !colorCapable, |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // SetColorCapable forces the writer to either write the ANSI escape color |
| 32 | // if capable is true, or to not write them if capable is false. |
| 33 | func (w *Writer) SetColorCapable(capable bool) { |
| 34 | w.noColor = !capable |
| 35 | } |
| 36 | |
| 37 | // SetForeground sets the foreground color. |
| 38 | func (w *Writer) SetForeground(c Color) { |
| 39 | w.writeSGR(c.foreground()) |
| 40 | } |
| 41 | |
| 42 | // SetBackground sets the background color. |
| 43 | func (w *Writer) SetBackground(c Color) { |
| 44 | w.writeSGR(c.background()) |
| 45 | } |
| 46 | |
| 47 | // SetStyle sets the text style. |
| 48 | func (w *Writer) SetStyle(s Style) { |
| 49 | w.writeSGR(s.enable()) |
| 50 | } |
| 51 | |
| 52 | // ClearStyle clears the text style. |
| 53 | func (w *Writer) ClearStyle(s Style) { |
| 54 | w.writeSGR(s.disable()) |
| 55 | } |
| 56 | |
| 57 | // Reset returns the default foreground and background colors with no styles. |
| 58 | func (w *Writer) Reset() { |
| 59 | w.writeSGR(reset) |
| 60 | } |
| 61 | |
| 62 | type sgr interface { |
| 63 | // sgr returns the combined escape sequence for the Select Graphic Rendition. |
| 64 | sgr() string |
| 65 | } |
| 66 | |
| 67 | // writeSGR takes the appropriate integer SGR parameters |
| 68 | // and writes out the ANIS escape code. |
| 69 | func (w *Writer) writeSGR(value sgr) { |
| 70 | if w.noColor { |
| 71 | return |
| 72 | } |
| 73 | fmt.Fprint(w, value.sgr()) |
| 74 | } |