Documentation
¶
Overview ¶
Package term answers the questions every command-line tool asks about its terminal: whether a stream is a terminal at all, how large it is, whether it may be painted in color, and how wide a piece of text is once it is drawn there.
Color is decided once per process. SetColorMode records what the user asked for (usually through a --color flag), and Colored combines that with the environment (NO_COLOR, TERM=dumb) and the stream itself. Every package in this module asks Colored before it writes an escape sequence, so output headed for a pipe, a file or a test buffer stays plain.
Text from elsewhere — a CI job's log, a remote command's output — goes through Sanitize or SanitizeLines before it is written: they keep its colors and take out every escape sequence and control character that could do more than color it.
Index ¶
- Constants
- Variables
- func CanAnimate(w io.Writer) bool
- func ColorAllowed() bool
- func Colored(w io.Writer) bool
- func Columns(v any, fallback int) int
- func EscapeLen(s string) int
- func Hyperlink(url, text string) string
- func Interactive(in, out *os.File) bool
- func IsTerminal(v any) bool
- func Linkify(s string) string
- func Links(w io.Writer) io.Writer
- func OpenTTY() (*os.File, error)
- func PadLeft(s string, width int) string
- func PadRight(s string, width int) string
- func Sanitize(s string) string
- func SanitizeLines(s string) []string
- func ScreenRows(lines []string, width int) int
- func SetColorMode(m ColorMode)
- func ShouldColor(m ColorMode, w io.Writer) bool
- func Size(v any) (width, height int)
- func StripANSI(s string) string
- func Truncate(s string, width int) string
- func TruncateMiddle(s string, width int) string
- func VisibleWidth(s string) int
- func Wrap(s string, width int, indent string) string
- type ColorMode
Examples ¶
Constants ¶
const Ellipsis = "…"
Ellipsis marks where Truncate and TruncateMiddle cut text.
Variables ¶
var ColorModeNames = []string{"auto", "always", "never"}
ColorModeNames are the spellings ParseColorMode accepts, in the order a help text or shell completion lists them.
var ErrNoTTY = errors.New("term: no controlling terminal")
ErrNoTTY is returned by OpenTTY where no controlling terminal can be opened apart from the standard streams.
Functions ¶
func CanAnimate ¶
CanAnimate reports whether w may be redrawn in place: it is a terminal, the environment permits color, and the user did not ask for --color=never.
func ColorAllowed ¶
func ColorAllowed() bool
ColorAllowed reports whether the environment permits color: NO_COLOR is unset (any value, even empty, turns color off, see https://no-color.org) and TERM is not "dumb".
func Colored ¶
Colored reports whether output written to w is painted under the mode SetColorMode recorded.
func Columns ¶
Columns returns the width of the terminal v is, or wraps, or fallback when it is no terminal or its size cannot be read.
func EscapeLen ¶
EscapeLen returns the length in bytes of the escape sequence s starts with, or 0 when s does not start with one. It recognizes CSI sequences (ESC [ … final byte), OSC, DCS, SOS, PM and APC strings (ended by BEL or ESC \), and the short escapes: ESC, any intermediate bytes (0x20–0x2F), and a final byte (0x30–0x7E), such as ESC 7 or ESC ( B. An ESC followed by anything else, such as a control character or the first byte of a multi-byte rune, is a sequence of one byte, so the rune stays whole. An unterminated sequence runs to the end of s, so a cut-off sequence is never counted as visible text. Code that walks styled text uses it to copy escape sequences through whole.
func Hyperlink ¶
Hyperlink wraps text in an OSC 8 hyperlink to url. Terminals that support OSC 8 make text clickable; all others print text alone.
func Interactive ¶
Interactive reports whether both in and out are terminals, which is what a prompt needs before it can ask anything.
func IsTerminal ¶
IsTerminal reports whether v is, or wraps, a file that is a terminal. v is usually an io.Writer or an io.Reader; a writer wraps another by having an Unwrap() io.Writer method.
func Links ¶
Links returns a writer that hyperlinks the URLs written through it when w is a terminal that may be painted, and w itself otherwise. A URL split across two writes is not recognized, so write whole lines.
func OpenTTY ¶
OpenTTY opens the controlling terminal for reading and writing. It works even when stdin and stdout are redirected, which lets a command that reads its input from a pipe still ask the user a question. The caller closes the file.
func PadLeft ¶
PadLeft pads s with leading spaces to width visible cells, right-aligning it. Text already that wide or wider is returned unchanged.
func PadRight ¶
PadRight pads s with spaces to width visible cells. Text already that wide or wider is returned unchanged.
func Sanitize ¶ added in v0.5.0
Sanitize makes text from elsewhere — a CI job's log, a remote command's output, a message somebody wrote — safe to write to a terminal. Escape sequences in such text can do more than color it: move the cursor over what was written before, retitle the window, set the clipboard, disguise a link, or leave the terminal in a mode it does not get out of. Sanitize keeps what colors text and takes out everything else:
- SGR sequences are kept, with only the attributes that change how text looks and leave it readable: bold, dim, italic, underline, blink, reverse, strikethrough, overline, foreground and background colors (16-color, 256-color and 24-bit) and underline colors (256-color and 24-bit). Concealed text, fonts, frames and the like are dropped, and a sequence left with nothing is removed.
- Every other escape sequence is removed, and so is every control character but the newline: the C0 and C1 controls and DEL.
- A tab becomes the spaces up to the next tab stop, every 8 columns.
- A carriage return ends what came before it on its line, the way a progress meter that redraws its line leaves only its last state on screen: only the text after the line's last one is kept, in the colors the text before it set. Carriage returns ending a line, as in CRLF, are dropped.
- Bytes that are not valid UTF-8 become U+FFFD.
Newlines are kept, so a color carries from one line into the next as the text set it. SanitizeLines makes every line stand on its own instead.
Example ¶
A job log keeps its colors; the title it tried to set, the line it erased and the progress it redrew in place are gone.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
log := "\x1b]0;pwned\x07\x1b[32;1m$ make test\x1b[0;m\n" +
"downloading 10%\rdownloading 100%\x1b[2K\n" +
"\x1b[31mFAIL\x1b[0m\tpkg/foo\n"
fmt.Printf("%q\n", term.Sanitize(log))
}
Output: "\x1b[32;1m$ make test\x1b[0;m\ndownloading 100%\n\x1b[31mFAIL\x1b[0m pkg/foo\n"
func SanitizeLines ¶ added in v0.5.0
SanitizeLines is Sanitize split into lines that each stand on their own: a line starts with the colors and attributes the lines before it left set, and a line that leaves any set ends with a reset. Every line can then be shown apart from the rest, cut short or left out — the last lines of a log under a status board, say — without taking its colors into what follows it. A newline at the end of s ends its last line rather than starting another, and an empty s has no lines.
Example ¶
The last line of a log, shown alone, keeps the color an earlier line set.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
lines := term.SanitizeLines("\x1b[31mERROR: build failed:\nexit code 1\x1b[0m\n")
fmt.Printf("%q\n", lines[len(lines)-1])
}
Output: "\x1b[31mexit code 1\x1b[0m"
func ScreenRows ¶
ScreenRows returns how many terminal rows lines take up on a terminal width cells wide. It follows the cursor the way a terminal does: a line wider than the terminal wraps onto further rows, and a wide character that would straddle the right edge starts the next row, leaving the last cell empty. A line exactly as wide as the terminal takes one row. A width of 0 or less counts one row per line. Redrawing a block in place depends on this count being exact.
func SetColorMode ¶
func SetColorMode(m ColorMode)
SetColorMode records the color choice for the whole process. Call it once, after parsing flags and before writing output. A value other than the three defined modes records ColorAuto.
func ShouldColor ¶
ShouldColor reports whether output written to w is painted under mode m: always under ColorAlways, never under ColorNever, and under ColorAuto only when w is a terminal and ColorAllowed holds.
func Size ¶
Size returns the width and height of the terminal v is, or wraps, in cells. It returns 0, 0 when v is no terminal or its size cannot be read.
func StripANSI ¶
StripANSI removes terminal escape sequences from s: CSI sequences such as colors and cursor movement (ESC [ … final byte), OSC sequences such as hyperlinks (ESC ] … BEL or ESC \), and the short escapes such as ESC 7 and ESC ( B. Everything else, multi-byte runes included, is left untouched. It does not make text from elsewhere safe to show: control characters stay. Sanitize does that.
func Truncate ¶
Truncate cuts s down to width visible cells, ending it with Ellipsis when anything was cut. Escape sequences are kept, and a reset is appended after a cut so a color never bleeds into what follows. A width of 0 or less, what Size reports for anything but a terminal, leaves s whole.
func TruncateMiddle ¶
TruncateMiddle cuts s down to width visible cells by taking text out of its middle, so both ends stay readable: "feature/very-long-branch-name" cut to 21 cells becomes "feature/ve…ranch-name". Escape sequences are dropped. A width of 0 or less leaves s whole.
func VisibleWidth ¶
VisibleWidth returns how many terminal cells s takes up once drawn, escape sequences left out. Wide runes (CJK, most emoji) count two cells, combining marks none. For text spanning several lines it measures the widest line.
func Wrap ¶ added in v0.5.0
Wrap breaks the lines of s at spaces so that each fits into width cells, and starts every line after the first with indent, a hanging indent. Wrap(text, 40, " ") gives
Dry run: would tag 8.4.25 and push it,
then wait for its pipeline.
A line that fits is left as it is, and so are the line breaks s already has; the lines after them are indented too. A line keeps its leading spaces, and a line Wrap starts has indent alone. A word wider than the room left for it gets a line of its own and stays whole. Widths are visible widths, as VisibleWidth measures them, so escape sequences take up none. A width of 0 or less, what Size reports for anything but a terminal, breaks nothing and only indents.
Example ¶
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
fmt.Println(term.Wrap("Dry run: would tag 8.4.25 and push it, then wait for its pipeline.", 40, " "))
}
Output: Dry run: would tag 8.4.25 and push it, then wait for its pipeline.
Types ¶
type ColorMode ¶
type ColorMode int
ColorMode is what the user asked for about color, usually through a --color flag.
func CurrentColorMode ¶
func CurrentColorMode() ColorMode
CurrentColorMode returns the mode SetColorMode last recorded.
func ParseColorMode ¶
ParseColorMode reads a --color value. Besides auto, always and never it takes the spellings other tools use for the same three choices: an empty value or "true" means always (a bare --color), "false" and "none" mean never, and "tty" and "if-tty" mean auto.