Top Related Projects
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Golang ultimate ANSI-colors that supports Printf/Sprintf methods
Style definitions for nice terminal layouts 👄
Quick Overview
Termenv is a Go library for advanced ANSI styling and color capabilities in terminal applications. It provides a simple and efficient way to add colors, styles, and other visual enhancements to command-line interfaces, supporting a wide range of terminal emulators and color schemes.
Pros
- Cross-platform compatibility with support for various terminal emulators
- Rich color support, including 24-bit true color
- Easy-to-use API for applying styles and colors to text
- Automatic color degradation for terminals with limited color support
Cons
- Limited to terminal applications, not suitable for GUI development
- Requires terminal emulators that support ANSI escape codes
- May have inconsistent results across different terminal types and configurations
Code Examples
- Printing colored text:
package main
import (
"fmt"
"github.com/muesli/termenv"
)
func main() {
p := termenv.ColorProfile()
s := termenv.String("Hello, colorful world!")
fmt.Println(s.Foreground(p.Color("#ff0000")))
}
- Applying multiple styles:
package main
import (
"fmt"
"github.com/muesli/termenv"
)
func main() {
s := termenv.String("Bold and underlined")
fmt.Println(s.Bold().Underline())
}
- Using predefined colors:
package main
import (
"fmt"
"github.com/muesli/termenv"
)
func main() {
p := termenv.ColorProfile()
s := termenv.String("Blue text on yellow background")
fmt.Println(s.Foreground(p.Color("blue")).Background(p.Color("yellow")))
}
Getting Started
To use termenv in your Go project, follow these steps:
-
Install the library:
go get github.com/muesli/termenv
-
Import it in your Go code:
import "github.com/muesli/termenv"
-
Start using termenv functions to add colors and styles to your terminal output:
p := termenv.ColorProfile() s := termenv.String("Styled text").Foreground(p.Color("green")).Bold() fmt.Println(s)
Competitor Comparisons
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Pros of color
- More comprehensive color manipulation functions (e.g., RGB, HSL, HEX conversions)
- Supports a wider range of color styles and text decorations
- Includes built-in color themes and predefined color constants
Cons of color
- Less focus on terminal environment detection and capabilities
- May have a steeper learning curve due to more extensive API
- Lacks some advanced features like true color support in all scenarios
Code Comparison
termenv:
style := termenv.Style{}.Foreground(termenv.ANSI256Color(202))
fmt.Println(style.Styled("Hello, World!"))
color:
color.Red.Println("Hello, World!")
color.Style{color.FgGreen, color.OpBold}.Println("Bold green text")
Both libraries provide ways to add color to terminal output, but color offers more built-in color options and styles out of the box, while termenv focuses on terminal environment compatibility and simplicity.
Golang ultimate ANSI-colors that supports Printf/Sprintf methods
Pros of aurora
- Simpler API with fewer functions, making it easier to learn and use
- Supports both 8-color and 256-color modes
- Includes built-in support for common color names (e.g., "red", "blue")
Cons of aurora
- Less comprehensive color support compared to termenv
- Lacks advanced features like color profiles and true color support
- No built-in terminal capability detection
Code comparison
aurora:
fmt.Println(aurora.Red("This is red"))
fmt.Println(aurora.BgBlue("This has a blue background"))
termenv:
p := termenv.ColorProfile()
s := termenv.String("This is red").Foreground(p.Color("red"))
fmt.Println(s)
s = termenv.String("This has a blue background").Background(p.Color("blue"))
fmt.Println(s)
Summary
Aurora offers a simpler API and basic color support, making it suitable for projects with straightforward terminal coloring needs. Termenv, on the other hand, provides more advanced features and comprehensive color support, including true color and color profiles. Termenv is better suited for projects requiring more sophisticated terminal output styling and cross-platform compatibility.
Style definitions for nice terminal layouts 👄
Pros of Lipgloss
- More comprehensive styling options, including borders, padding, and alignment
- Higher-level abstractions for creating complex layouts
- Built-in support for responsive designs
Cons of Lipgloss
- Steeper learning curve due to more complex API
- Potentially higher memory usage for complex layouts
- May be overkill for simple styling needs
Code Comparison
Termenv:
s := termenv.String("Hello, World!").Foreground(termenv.ColorProfile().Color("204"))
fmt.Println(s)
Lipgloss:
style := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("#FAFAFA")).
Background(lipgloss.Color("#7D56F4")).
PaddingTop(2).
PaddingLeft(4)
fmt.Println(style.Render("Hello, World!"))
Both Termenv and Lipgloss are Go libraries for terminal styling, but they differ in their approach and feature set. Termenv focuses on providing a simpler, more low-level API for basic color and style manipulation. Lipgloss, on the other hand, offers a more comprehensive set of styling options and higher-level abstractions for creating complex layouts.
While Lipgloss provides more powerful features, it may have a steeper learning curve and could be considered overkill for simple styling needs. Termenv's simpler API might be more suitable for basic use cases or when performance is a critical concern.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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 onlytermenv.ANSI
- 16 color ANSI supporttermenv.ANSI256
- Extended 256 color ANSI supporttermenv.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
Terminal | Query Color Scheme | Query Cursor Position | Set Window Title | Change Cursor Color | Change Default Foreground Setting | Change Default Background Setting | Bracketed Paste | Extended Mouse (SGR) | Pixels Mouse (SGR-Pixels) |
---|---|---|---|---|---|---|---|---|---|
alacritty | â | â | â | â | â | â | â | â | â |
foot | â | â | â | â | â | â | â | â | â |
kitty | â | â | â | â | â | â | â | â | â |
Konsole | â | â | â | â | â | â | â | â | â |
rxvt | â | â | â | â | â | â | â | â | â |
urxvt | â | â | â | â | â | â | â | â | â |
screen | â1 | â | â | â | â | â | â | â | â |
st | â | â | â | â | â | â | â | â | â |
tmux | â1 | â | â | â | â | â | â | â | â |
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
Terminal | Copy to Clipboard (OSC52) | Hyperlinks (OSC8) | Notifications (OSC777) |
---|---|---|---|
alacritty | â | â 3 | â |
foot | â | â | â |
kitty | â | â | â |
Konsole | â4 | â | â |
rxvt | â | â | â |
urxvt | â 5 | â | â |
screen | â | â6 | â |
st | â | â | â |
tmux | â | â7 | â |
vte-based2 | â2 | â | â |
wezterm | â | â | â |
xterm | â | â | â |
Linux Console | â | â | â |
Apple Terminal | â 8 | â | â |
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
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
Footnotes
-
Unavailable as multiplexers (like tmux or screen) can be connected to multiple terminals (with different color settings) at the same time. ↩ ↩2
-
This covers all vte-based terminals, including Gnome Terminal, guake, Pantheon Terminal, Terminator, Tilix, XFCE Terminal. ↩ ↩2 ↩3
-
OSC52 is not supported, for more info see bug#372116. ↩
-
Workaround for urxvt not supporting OSC52. See this for more information. ↩
-
OSC52 works with a workaround. ↩
Top Related Projects
🎨 Terminal color rendering library, support 8/16 colors, 256 colors, RGB color rendering output, support Print/Sprintf methods, compatible with Windows. GO CLI 控制台颜色渲染工具库,支持16色,256色,RGB色彩渲染输出,使用类似于 Print/Sprintf,兼容并支持 Windows 环境的色彩渲染
Golang ultimate ANSI-colors that supports Printf/Sprintf methods
Style definitions for nice terminal layouts 👄
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot