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. On Windows, Colored and CanAnimate switch on the console's virtual terminal processing before they report true, and report false for a console that would show escape sequences as text.
Widths are counted in terminal cells and are the same on every machine: VisibleWidth, WidthAt, Truncate, Wrap and ScreenRows count a wide rune as two cells, a tab as the cells up to the next of the tab stops every 8 columns, and a character of ambiguous width, such as a box-drawing line, as one cell whatever the locale.
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, 24-bit ones as the nearest of the 256 colors, and take out every escape sequence and control character that could do more than color it. Text that is shown plain, without the sender's colors, goes through Plain instead, and a value shown within one line, such as a name or a header, through PlainLine. A URL that becomes a link with Hyperlink must hold no control character, or it is no link; ShouldLink decides whether a stream gets links at all, under a --links mode as ShouldColor does under --color.
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 Nearest256(r, g, b uint8) int
- func OpenTTY() (*os.File, error)
- func PadLeft(s string, width int) string
- func PadRight(s string, width int) string
- func Plain(s string) string
- func PlainLine(s string) 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 ShouldLink(m ColorMode, w io.Writer) bool
- func Size(v any) (width, height int)
- func StripANSI(s string) string
- func TrueColor() bool
- func Truncate(s string, width int) string
- func TruncateMiddle(s string, width int) string
- func VisibleWidth(s string) int
- func WidthAt(s string, column int) 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. On Windows it switches on the console's virtual terminal processing as ShouldColor does, and reports false for a console that does not take it.
func ColorAllowed ¶
func ColorAllowed() bool
ColorAllowed reports whether the environment permits color: NO_COLOR is unset and TERM is not "dumb". Any value of NO_COLOR, even an empty one, disables color. That is stricter than https://no-color.org, which lets an empty NO_COLOR stand for no setting at all, and it is deliberate: whoever sets the variable wants no color, however it came to be empty.
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.
The url is written into an escape sequence, where a control character would end the sequence early and let the rest of the url act as one of its own: a clipboard write, say. A url that holds a control character (C0, DEL or C1) or is not valid UTF-8 is therefore no link, and Hyperlink returns text alone, as it does for an empty url. The text is written as it is: text from elsewhere goes through Plain or PlainLine first.
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. Asking leaves the file as it is: its deadlines keep working afterwards.
func Linkify ¶
Linkify wraps every http and https URL in s in an OSC 8 hyperlink. Only text is searched: a URL inside an escape sequence, such as the target of a hyperlink s already has or a window title, is left alone, and so is the text of a hyperlink that is open, so text that was linkified before comes back unchanged.
Punctuation that ends a URL is taken for the sentence's and stays outside the link: a period, comma, semicolon, colon, exclamation or question mark, and a closing bracket that nothing in the URL opens. A bracket the URL opens itself belongs to it, as in https://en.wikipedia.org/wiki/Go_(game) or http://[::1].
Example ¶
A sentence's punctuation stays outside the link, and a hyperlink that is already there is left as it is.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
fmt.Printf("%q\n", term.Linkify("See https://example.com/a_(b)."))
fmt.Printf("%q\n", term.Linkify(term.Hyperlink("https://example.com", "the docs")))
}
Output: "See \x1b]8;;https://example.com/a_(b)\x1b\\https://example.com/a_(b)\x1b]8;;\x1b\\." "\x1b]8;;https://example.com\x1b\\the docs\x1b]8;;\x1b\\"
func Links ¶
Links returns a writer that hyperlinks the URLs written through it, as Linkify does, when w is a terminal that may be painted, and w itself otherwise. A URL split across two writes is not recognized, and neither is a hyperlink that one write opens and another closes, so write whole lines.
func Nearest256 ¶ added in v0.7.0
Nearest256 returns the index among the 256 colors that is nearest to the 24-bit color r, g, b, for a terminal that does not take 24-bit colors: "38;5;n" paints text in it and "48;5;n" the background. It is the mapping Sanitize applies to the 24-bit colors of the text it is given.
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. The spaces move s along its line and its tab stops with it, so the tabs of text that is padded become the spaces they stood for.
func PadRight ¶
PadRight pads s with spaces to width visible cells. Text already that wide or wider is returned unchanged.
func Plain ¶ added in v0.6.0
Plain is Sanitize for text shown as plain text: the colors Sanitize keeps go too, so the result holds no escape sequence at all, and no control character but the newline. Use it for text from elsewhere that the program paints itself or not at all — a server's message, a name, a comment somebody typed — where the sender's colors could only mislead: text in the background color is hidden, and red or bold can pass the sender's words off as the program's own warning. Lines, tab stops, carriage returns and invalid UTF-8 are handled as Sanitize handles them.
Example ¶
A comment somebody typed is shown in the program's own colors only: the sender's red and the clipboard write it carried, in either form, are gone.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
comment := "\x1b[31mURGENT:\x1b[0m call me\x1b]52;c;Y3VybCBldmlsLmV4YW1wbGUgfCBzaA==\x07\u009d52;c;Zm9v\u009c"
fmt.Printf("%q\n", term.Plain(comment))
}
Output: "URGENT: call me"
func PlainLine ¶ added in v0.6.0
PlainLine is Plain for text shown within one line: a header value, a name, a file name, a label. Before anything else, every line break (LF, CR, VT, FF, NEL, U+2028 and U+2029) and every tab becomes a space, so the text can neither spill onto lines of its own nor, with a carriage return, draw one part of itself over another. The bidirectional embeddings, overrides and isolates (U+202A–U+202E and U+2066–U+2069) are dropped, since they reorder text on screen: an override turns the name "invoice\u202efdp.exe" into "invoiceexe.pdf". Last, every run of white space, a no-break space as much as a space, becomes one space, and white space at either end goes, so a value made of nothing but escape sequences, control characters and spaces comes back empty.
Multi-line text keeps its bidirectional controls in Sanitize and Plain, since right-to-left text depends on them; a value shown on one line has no use for them.
Example ¶
A file name stays on its line and in the order it was written.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
fmt.Printf("%q\n", term.PlainLine("invoice\u202efdp.exe\r\n\x1b[2J (2 MB)"))
}
Output: "invoicefdp.exe (2 MB)"
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, and foreground and background colors from the 16 and the 256 colors. Concealed text, fonts, frames and the like are dropped, and a sequence left with nothing is removed.
- A 24-bit color (38;2;r;g;b or 48;2;r;g;b) becomes the nearest of the 256 colors (38;5;n or 48;5;n), and an underline color (58 with its components, and 59, which ends it) is dropped. A terminal that does not know these forms, GNU screen 4 for one, reads each of their numbers as an attribute of its own: 38;2;8;7;0 conceals the text, reverses it and resets everything, and 58;5;8 blinks and conceals. A color could so carry any attribute that is dropped here. The 256-color forms stay as they are: nearly every terminal reads them whole.
- Every other escape sequence is removed, and so is every control character but the newline: the C0 and C1 controls and DEL.
- An escape string (OSC, DCS, SOS, PM or APC, such as a window title or a clipboard write) goes with its payload up to its terminator, BEL or ESC \, also when that is lines further on, as a terminal reads it. One that no terminator ends anywhere in the text goes up to the end of its line only: text that was cut off inside a sequence, or that starts one to make the rest disappear, does not take the lines after it along.
- The 8-bit forms of escape sequences, which start with a C1 control instead of ESC, are removed with what belongs to them, so a clipboard write such as U+009D 52;c;… BEL does not leave its payload behind as text. A CSI (U+009B) goes with its parameters and final byte, an SGR one too: most terminals that read UTF-8 do not take it for a sequence, so its colors would not show there anyway. An OSC, DCS, SOS, PM or APC string (U+009D, U+0090, U+0098, U+009E, U+009F) goes up to its terminator, BEL, ESC \ or ST (U+009C), when that ends it on the same line. Without a terminator on its line, or for a CSI that is not well formed, only the C1 control itself goes: text decoded as Latin-1 although it was Windows-1252 has C1 controls where it meant letters (U+009E for ž), and the rest of such a text must not be taken for the payload of a sequence.
- 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 once text follows it, the way a progress meter that redraws its line leaves only its last state on screen: only the text after the line's last such return is kept, in the colors the text before it set. A carriage return that nothing but escape sequences follows on its line draws over nothing and is dropped: the one of a CRLF line ending, also when a color is reset between the two, as git diff --color writes the added lines of a file with CRLF line endings.
- 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 tab moves to the next tab stop of its row, every 8 columns, and stops at the row's last column instead of wrapping. A width of 0 or less counts one row per line. Redrawing a block in place depends on this count being exact, so lines hold no control character but the tab: no newline, no carriage return.
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.
On Windows a console reads escape sequences only once its virtual terminal processing is switched on. ShouldColor switches it on for the console w is, once, before it reports true for it, and reports false under every mode for a console that does not take the setting, as the console host of Windows versions before 10 does not.
func ShouldLink ¶ added in v0.9.0
ShouldLink reports whether text written to w carries OSC 8 hyperlinks under mode m, usually the value of a --links flag (see cobrax.AddModeFlag): always under ColorAlways, never under ColorNever, and under ColorAuto only when w is a terminal, where a link can be clicked, and ColorAllowed holds. A hyperlink is an escape sequence like a color, so NO_COLOR and TERM=dumb, which ask for output free of them, switch links off as well.
On Windows it switches on the console's virtual terminal processing as ShouldColor does, and reports false under every mode for a console that would show the sequence as text.
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 and Plain do that.
func TrueColor ¶ added in v0.8.0
func TrueColor() bool
TrueColor reports whether the terminal announces 24-bit colors: the COLORTERM environment variable is "truecolor" or "24bit", in any case. Terminals that do not take 24-bit colors read the parameters of one as attributes of their own, so paint them only where TrueColor holds, and the nearest of the 256 colors (Nearest256) everywhere else.
TrueColor says what the terminal can show, not whether output is painted at all; that is still for Colored to decide.
func Truncate ¶
Truncate cuts s down to width visible cells, ending it with Ellipsis when anything was cut. Text of several lines is cut line by line: every line wider than width ends with an Ellipsis of its own, and the lines that fit stay as they are. Escape sequences up to a cut are kept, and a color or hyperlink still open there, even one an earlier line opened, is closed after the cut so that it 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". Text of several lines is cut line by line: every line wider than width loses its own middle, and the lines that fit keep their text. Where anything is cut, the escape sequences of s are dropped, and the tabs of a line that is cut become the spaces up to their tab stops. 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, and a tab counts the cells up to the next tab stop, every 8 columns from the start of its line. For text spanning several lines it measures the widest line.
A character whose width Unicode leaves ambiguous, such as a box-drawing line, the ellipsis or a bullet, counts one cell, as terminals draw it by default. The width of text does not depend on the locale: LANG, LC_ALL and RUNEWIDTH_EASTASIAN change nothing about it.
func WidthAt ¶ added in v0.7.0
WidthAt returns how many terminal cells s, text within one line, takes up when it starts at column, the number of cells before it on its line. It measures the way VisibleWidth does; the two differ only for text with a tab in it, whose width depends on where the tab stands: "\tx" is 9 cells wide at column 0 and 5 at column 4. Code that lays text out cell by cell measures each piece at the column it is drawn at. A column below 0 is 0.
Example ¶
A tab is as wide as the column it stands at makes it: it ends at the next tab stop, every 8 columns.
package main
import (
"fmt"
"github.com/mittwald/cli-kit/term"
)
func main() {
fmt.Println(term.WidthAt("\tx", 0), term.WidthAt("\tx", 4))
}
Output: 9 5
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, and a tab takes up the cells to the next tab stop from where its word stands on the line; a tab is part of a word and no place to break. 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.
const ( // ColorAuto paints output written to a terminal and leaves everything // else plain. It honors NO_COLOR and TERM=dumb. It is the default. ColorAuto ColorMode = iota // ColorAlways paints output wherever it goes, even into a pipe. The one // exception is a Windows console that cannot be made to read escape // sequences, where they would show as text. ColorAlways // ColorNever never paints output. ColorNever )
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.