term

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 13 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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. 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.

Index

Examples

Constants

View Source
const Ellipsis = "…"

Ellipsis marks where Truncate and TruncateMiddle cut text.

Variables

View Source
var ColorModeNames = []string{"auto", "always", "never"}

ColorModeNames are the spellings ParseColorMode accepts, in the order a help text or shell completion lists them.

View Source
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

func CanAnimate(w io.Writer) bool

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

func Colored(w io.Writer) bool

Colored reports whether output written to w is painted under the mode SetColorMode recorded.

func Columns

func Columns(v any, fallback int) int

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

func EscapeLen(s string) int

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(url, text string) string

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

func Interactive(in, out *os.File) bool

Interactive reports whether both in and out are terminals, which is what a prompt needs before it can ask anything.

func IsTerminal

func IsTerminal(v any) bool

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 Linkify

func Linkify(s string) string

Linkify wraps every http and https URL in s in an OSC 8 hyperlink.

func Links(w io.Writer) io.Writer

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

func OpenTTY() (*os.File, error)

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

func PadLeft(s string, width int) string

PadLeft pads s with leading spaces to width visible cells, right-aligning it. Text already that wide or wider is returned unchanged.

func PadRight

func PadRight(s string, width int) string

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

func Plain(s string) string

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

func PlainLine(s string) string

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

func Sanitize(s string) string

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.
  • 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, 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

func SanitizeLines(s string) []string

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

func ScreenRows(lines []string, width int) int

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

func ShouldColor(m ColorMode, w io.Writer) bool

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

func Size(v any) (width, height int)

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

func StripANSI(s string) string

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 Truncate

func Truncate(s string, width int) string

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

func TruncateMiddle(s string, width int) string

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

func VisibleWidth(s string) int

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

func Wrap(s string, width int, indent string) string

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.

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.
	ColorAlways
	// ColorNever never paints output.
	ColorNever
)

func CurrentColorMode

func CurrentColorMode() ColorMode

CurrentColorMode returns the mode SetColorMode last recorded.

func ParseColorMode

func ParseColorMode(value string) (ColorMode, error)

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.

func (ColorMode) String

func (m ColorMode) String() string

String returns the flag spelling of m.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL