blob: 32437bb27bcf4865d9aa6abeec70c1e5177bb28d [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2016 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4package ansiterm
5
6import (
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.
14type 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.
23func 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.
33func (w *Writer) SetColorCapable(capable bool) {
34 w.noColor = !capable
35}
36
37// SetForeground sets the foreground color.
38func (w *Writer) SetForeground(c Color) {
39 w.writeSGR(c.foreground())
40}
41
42// SetBackground sets the background color.
43func (w *Writer) SetBackground(c Color) {
44 w.writeSGR(c.background())
45}
46
47// SetStyle sets the text style.
48func (w *Writer) SetStyle(s Style) {
49 w.writeSGR(s.enable())
50}
51
52// ClearStyle clears the text style.
53func (w *Writer) ClearStyle(s Style) {
54 w.writeSGR(s.disable())
55}
56
57// Reset returns the default foreground and background colors with no styles.
58func (w *Writer) Reset() {
59 w.writeSGR(reset)
60}
61
62type 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.
69func (w *Writer) writeSGR(value sgr) {
70 if w.noColor {
71 return
72 }
73 fmt.Fprint(w, value.sgr())
74}