Categorygithub.com/muesli/termenv
modulepackage
0.16.0
Repository: https://github.com/muesli/termenv.git
Documentation: pkg.go.dev

# README

termenv Logo
Latest Release GoDoc Build Status Coverage Status Go ReportCard
Example terminal output

termenv lets you safely use advanced styling options on the terminal. It gathers information about the terminal environment in terms of its ANSI & color support and offers you convenient methods to colorize and style your output, without you having to deal with all kinds of weird ANSI escape sequences and color conversions.

Features

  • RGB/TrueColor support
  • Detects the supported color range of your terminal
  • Automatically converts colors to the best matching, available colors
  • Terminal theme (light/dark) detection
  • Chainable syntax
  • Nested styles

Installation

go get github.com/muesli/termenv

Usage

output := termenv.NewOutput(os.Stdout)

termenv queries the terminal's capabilities it is running in, so you can safely use advanced features, like RGB colors or ANSI styles. output.Profile returns the supported profile:

  • termenv.Ascii - no ANSI support detected, ASCII only
  • termenv.ANSI - 16 color ANSI support
  • termenv.ANSI256 - Extended 256 color ANSI support
  • termenv.TrueColor - RGB/TrueColor support

Alternatively, you can use termenv.EnvColorProfile which evaluates the terminal like ColorProfile, but also respects the NO_COLOR and CLICOLOR_FORCE environment variables.

You can also query the terminal for its color scheme, so you know whether your app is running in a light- or dark-themed environment:

// Returns terminal's foreground color
color := output.ForegroundColor()

// Returns terminal's background color
color := output.BackgroundColor()

// Returns whether terminal uses a dark-ish background
darkTheme := output.HasDarkBackground()

Manual Profile Selection

If you don't want to rely on the automatic detection, you can manually select the profile you want to use:

output := termenv.NewOutput(os.Stdout, termenv.WithProfile(termenv.TrueColor))

Colors

termenv supports multiple color profiles: Ascii (black & white only), ANSI (16 colors), ANSI Extended (256 colors), and TrueColor (24-bit RGB). Colors will automatically be degraded to the best matching available color in the desired profile:

TrueColor => ANSI 256 Colors => ANSI 16 Colors => Ascii

s := output.String("Hello World")

// Supports hex values
// Will automatically degrade colors on terminals not supporting RGB
s.Foreground(output.Color("#abcdef"))
// but also supports ANSI colors (0-255)
s.Background(output.Color("69"))
// ...or the color.Color interface
s.Foreground(output.FromColor(color.RGBA{255, 128, 0, 255}))

// Combine fore- & background colors
s.Foreground(output.Color("#ffffff")).Background(output.Color("#0000ff"))

// Supports the fmt.Stringer interface
fmt.Println(s)

Styles

You can use a chainable syntax to compose your own styles:

s := output.String("foobar")

// Text styles
s.Bold()
s.Faint()
s.Italic()
s.CrossOut()
s.Underline()
s.Overline()

// Reverse swaps current fore- & background colors
s.Reverse()

// Blinking text
s.Blink()

// Combine multiple options
s.Bold().Underline()

Template Helpers

termenv provides a set of helper functions to style your Go templates:

// load template helpers
f := output.TemplateFuncs()
tpl := template.New("tpl").Funcs(f)

// apply bold style in a template
bold := `{{ Bold "Hello World" }}`

// examples for colorized templates
col := `{{ Color "#ff0000" "#0000ff" "Red on Blue" }}`
fg := `{{ Foreground "#ff0000" "Red Foreground" }}`
bg := `{{ Background "#0000ff" "Blue Background" }}`

// wrap styles
wrap := `{{ Bold (Underline "Hello World") }}`

// parse and render
tpl, err = tpl.Parse(bold)

var buf bytes.Buffer
tpl.Execute(&buf, nil)
fmt.Println(&buf)

Other available helper functions are: Faint, Italic, CrossOut, Underline, Overline, Reverse, and Blink.

Positioning

// Move the cursor to a given position
output.MoveCursor(row, column)

// Save the cursor position
output.SaveCursorPosition()

// Restore a saved cursor position
output.RestoreCursorPosition()

// Move the cursor up a given number of lines
output.CursorUp(n)

// Move the cursor down a given number of lines
output.CursorDown(n)

// Move the cursor up a given number of lines
output.CursorForward(n)

// Move the cursor backwards a given number of cells
output.CursorBack(n)

// Move the cursor down a given number of lines and place it at the beginning
// of the line
output.CursorNextLine(n)

// Move the cursor up a given number of lines and place it at the beginning of
// the line
output.CursorPrevLine(n)

Screen

// Reset the terminal to its default style, removing any active styles
output.Reset()

// RestoreScreen restores a previously saved screen state
output.RestoreScreen()

// SaveScreen saves the screen state
output.SaveScreen()

// Switch to the altscreen. The former view can be restored with ExitAltScreen()
output.AltScreen()

// Exit the altscreen and return to the former terminal view
output.ExitAltScreen()

// Clear the visible portion of the terminal
output.ClearScreen()

// Clear the current line
output.ClearLine()

// Clear a given number of lines
output.ClearLines(n)

// Set the scrolling region of the terminal
output.ChangeScrollingRegion(top, bottom)

// Insert the given number of lines at the top of the scrollable region, pushing
// lines below down
output.InsertLines(n)

// Delete the given number of lines, pulling any lines in the scrollable region
// below up
output.DeleteLines(n)

Session

// SetWindowTitle sets the terminal window title
output.SetWindowTitle(title)

// SetForegroundColor sets the default foreground color
output.SetForegroundColor(color)

// SetBackgroundColor sets the default background color
output.SetBackgroundColor(color)

// SetCursorColor sets the cursor color
output.SetCursorColor(color)

// Hide the cursor
output.HideCursor()

// Show the cursor
output.ShowCursor()

// Copy to clipboard
output.Copy(message)

// Copy to primary clipboard (X11)
output.CopyPrimary(message)

// Trigger notification
output.Notify(title, body)

Mouse

// Enable X10 mouse mode, only button press events are sent
output.EnableMousePress()

// Disable X10 mouse mode
output.DisableMousePress()

// Enable Mouse Tracking mode
output.EnableMouse()

// Disable Mouse Tracking mode
output.DisableMouse()

// Enable Hilite Mouse Tracking mode
output.EnableMouseHilite()

// Disable Hilite Mouse Tracking mode
output.DisableMouseHilite()

// Enable Cell Motion Mouse Tracking mode
output.EnableMouseCellMotion()

// Disable Cell Motion Mouse Tracking mode
output.DisableMouseCellMotion()

// Enable All Motion Mouse mode
output.EnableMouseAllMotion()

// Disable All Motion Mouse mode
output.DisableMouseAllMotion()

Bracketed Paste

// Enables bracketed paste mode
termenv.EnableBracketedPaste()

// Disables bracketed paste mode
termenv.DisableBracketedPaste()

Terminal Feature Support

Color Support

  • 24-bit (RGB): alacritty, foot, iTerm, kitty, Konsole, st, tmux, vte-based, wezterm, Ghostty, Windows Terminal
  • 8-bit (256): rxvt, screen, xterm, Apple Terminal
  • 4-bit (16): Linux Console

Control Sequences

Click to show feature matrix
TerminalQuery Color SchemeQuery Cursor PositionSet Window TitleChange Cursor ColorChange Default Foreground SettingChange Default Background SettingBracketed PasteExtended Mouse (SGR)Pixels Mouse (SGR-Pixels)
alacritty
foot
kitty
Konsole
rxvt
urxvt
screen1
st
tmux1
vte-based2
wezterm
xterm
Linux Console
Apple Terminal
iTerm
Windows cmd
Windows Terminal

You can help improve this list! Check out how to and open an issue or pull request.

System Commands

Click to show feature matrix
TerminalCopy to Clipboard (OSC52)Hyperlinks (OSC8)Notifications (OSC777)
alacritty3
foot
kitty
Konsole4
rxvt
urxvt5
screen6
st
tmux7
vte-based22
wezterm
xterm
Linux Console
Apple Terminal8
iTerm
Windows cmd
Windows Terminal

Platform Support

termenv works on Unix systems (like Linux, macOS, or BSD) and Windows. While terminal applications on Unix support ANSI styling out-of-the-box, on Windows you need to enable ANSI processing in your application first:

    restoreConsole, err := termenv.EnableVirtualTerminalProcessing(termenv.DefaultOutput())
    if err != nil {
        panic(err)
    }
    defer restoreConsole()

The above code is safe to include on non-Windows systems or when os.Stdout does not refer to a terminal (e.g. in tests).

Color Chart

ANSI color chart

You can find the source code used to create this chart in termenv's examples.

Related Projects

  • reflow - ANSI-aware text operations
  • Lip Gloss - style definitions for nice terminal layouts 👄
  • ansi - ANSI sequence helpers

termenv in the Wild

Need some inspiration or just want to see how others are using termenv? Check out these projects:

  • Bubble Tea - a powerful little TUI framework 🏗
  • Glamour - stylesheet-based markdown rendering for your CLI apps 💇🏻‍♀️
  • Glow - a markdown renderer for the command-line 💅🏻
  • duf - Disk Usage/Free Utility - a better 'df' alternative
  • gitty - contextual information about your git projects
  • slides - terminal-based presentation tool

Feedback

Got some feedback or suggestions? Please open an issue or drop me a note!

License

MIT

Footnotes

  1. Unavailable as multiplexers (like tmux or screen) can be connected to multiple terminals (with different color settings) at the same time. 2

  2. This covers all vte-based terminals, including Gnome Terminal, guake, Pantheon Terminal, Terminator, Tilix, XFCE Terminal. 2 3

  3. OSC8 is supported since v0.11.0

  4. OSC52 is not supported, for more info see bug#372116.

  5. Workaround for urxvt not supporting OSC52. See this for more information.

  6. OSC8 is not supported, for more info see bug#50952.

  7. OSC8 is not supported, for more info see issue#911.

  8. OSC52 works with a workaround.

# Packages

No description provided by the author

# Functions

AltScreen switches to the alternate screen buffer.
BackgroundColor returns the terminal's default background color.
ChangeScrollingRegion sets the scrolling region of the terminal.
ClearLine clears the current line.
ClearLineLeft clears the line to the left of the cursor.
ClearLineRight clears the line to the right of the cursor.
ClearLines clears a given number of lines.
ClearScreen clears the visible portion of the terminal.
ColorProfile returns the supported color profile: Ascii, ANSI, ANSI256, or TrueColor.
ConvertToRGB converts a Color to a colorful.Color.
Copy copies text to clipboard using OSC 52 escape sequence.
CopyPrimary copies text to primary clipboard (X11) using OSC 52 escape sequence.
CursorBack moves the cursor backwards a given number of cells.
CursorDown moves the cursor down a given number of lines.
CursorForward moves the cursor up a given number of lines.
CursorNextLine moves the cursor down a given number of lines and places it at the beginning of the line.
CursorPrevLine moves the cursor up a given number of lines and places it at the beginning of the line.
CursorUp moves the cursor up a given number of lines.
DefaultOutput returns the default global output.
DeleteLines deletes the given number of lines, pulling any lines in the scrollable region below up.
DisableBracketedPaste disables bracketed paste.
DisableMouse disables Mouse Tracking mode.
DisableMouseAllMotion disables All Motion Mouse mode.
DisableMouseCellMotion disables Cell Motion Mouse Tracking mode.
DisableMouseHilite disables Hilite Mouse Tracking mode.
DisableMousePress disables X10 mouse mode.
EnableBracketedPaste enables bracketed paste.
EnableMouse enables Mouse Tracking mode.
EnableMouseAllMotion enables All Motion Mouse mode.
EnableMouseCellMotion enables Cell Motion Mouse Tracking mode.
EnableMouseHilite enables Hilite Mouse Tracking mode.
EnableMousePress enables X10 mouse mode.
EnableVirtualTerminalProcessing enables virtual terminal processing on Windows for w and returns a function that restores w to its previous state.
EnvColorProfile returns the color profile based on environment variables set Supports NO_COLOR (https://no-color.org/) and CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/) If none of these environment variables are set, this behaves the same as ColorProfile() It will return the Ascii color profile if EnvNoColor() returns true If the terminal does not support any colors, but CLICOLOR_FORCE is set and not "0" then the ANSI color profile will be returned.
EnvNoColor returns true if the environment variables explicitly disable color output by setting NO_COLOR (https://no-color.org/) or CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/) If NO_COLOR is set, this will return true, ignoring CLICOLOR/CLICOLOR_FORCE If CLICOLOR=="0", it will be true only if CLICOLOR_FORCE is also "0" or is unset.
ExitAltScreen exits the alternate screen buffer and returns to the former terminal view.
ForegroundColor returns the terminal's default foreground color.
HasDarkBackground returns whether terminal uses a dark-ish background.
HideCursor hides the cursor.
Hyperlink creates a hyperlink using OSC8.
InsertLines inserts the given number of lines at the top of the scrollable region, pushing lines below down.
MoveCursor moves the cursor to a given position.
NewOutput returns a new Output for the given writer.
Notify triggers a notification using OSC777.
Reset the terminal to its default style, removing any active styles.
RestoreCursorPosition restores a saved cursor position.
RestoreScreen restores a previously saved screen state.
SaveCursorPosition saves the cursor position.
SaveScreen saves the screen state.
SetBackgroundColor sets the default background color.
SetCursorColor sets the cursor color.
SetDefaultOutput sets the default global output.
SetForegroundColor sets the default foreground color.
SetWindowTitle sets the terminal window title.
ShowCursor shows the cursor.
String returns a new Style.
TemplateFuncs contains a few useful template helpers.
WithColorCache returns a new OutputOption with fore- and background color values pre-fetched and cached.
WithEnvironment returns a new OutputOption for the given environment.
WithProfile returns a new OutputOption for the given profile.
WithTTY returns a new OutputOption to assume whether or not the output is a TTY.
WithUnsafe returns a new OutputOption with unsafe mode enabled.

# Constants

Sequence definitions.
ANSI, 4-bit color profile.
ANSI256, 8-bit color profile.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
ANSI color codes.
nolint:revive.
Foreground and Background sequence codes.
Bell.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Control Sequence Introducer.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Cursor positioning.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Bracketed paste.
press, release, move, wheel.
press, release, move on pressed, wheel.
press, release, move, wheel, extended coordinates.
highlight.
press, release, move, wheel, extended pixel coordinates.
press only (X10).
press, release, wheel.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Explicit values for EraseLineSeq.
Sequence definitions.
Escape character.
Sequence definitions.
Sequence definitions.
Foreground and Background sequence codes.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Operating System Command.
timeout for OSC queries.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Screen.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Sequence definitions.
Session.
Sequence definitions.
String Terminator.
Sequence definitions.
TrueColor, 24-bit color profile.
Sequence definitions.

# Variables

ErrInvalidColor gets returned when a color is invalid.
ErrStatusReport gets returned when the terminal can't be queried.

# Structs

NoColor is a nop for terminals that don't support colors.
Output is a terminal output.
Style is a string that various rendering styles can be applied to.

# Interfaces

Color is an interface implemented by all colors that can be converted to an ANSI sequence.
Environ is an interface for getting environment variables.
File represents a file descriptor.

# Type aliases

ANSI256Color is a color (16-255) as defined by the ANSI Standard.
ANSIColor is a color (0-15) as defined by the ANSI Standard.
OutputOption sets an option on Output.
Profile is a color profile: Ascii, ANSI, ANSI256, or TrueColor.
RGBColor is a hex-encoded color, e.g.