• Stars
    star
    1,712
  • Rank 27,256 (Top 0.6 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 5 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Advanced ANSI style & color support for your terminal applications

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

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. โ†ฉ

More Repositories

1

duf

Disk Usage/Free Utility - a better 'df' alternative
Go
10,935
star
2

beehive

A flexible event/agent & automation system with lots of bees ๐Ÿ
Go
6,298
star
3

cache2go

Concurrency-safe Go caching library with expiration capabilities and access counters
Go
2,009
star
4

smartcrop

smartcrop finds good image crops for arbitrary crop sizes
Go
1,808
star
5

gitomatic

A tool to monitor git repositories and automatically pull & push changes
Go
1,014
star
6

gamut

Go package to generate and manage color palettes & schemes ๐ŸŽจ
Go
510
star
7

reflow

A collection of (ANSI-sequence aware) text reflow operations & algorithms
Go
450
star
8

gitty

Contextual information about your git projects, right on the command-line
Go
447
star
9

kmeans

k-means clustering algorithm implementation written in Go
Go
418
star
10

readme-scribe

A GitHub Action that automatically generates & updates markdown content (like your README.md)
396
star
11

crunchy

Finds common flaws in passwords. Like cracklib, but written in Go.
Go
378
star
12

obs-cli

OBS-cli is a command-line remote control for OBS
Go
306
star
13

regommend

Recommendation engine for Go
Go
303
star
14

markscribe

Your personal markdown scribe with template-engine and Git(Hub) & RSS powers ๐Ÿ“œ
Go
286
star
15

mango

mango is a man-page generator for the Go flag, pflag, cobra, coral, and kong packages
Go
229
star
16

docker-backup

A tool to create & restore complete, self-contained backups of Docker containers
Go
201
star
17

telephant

A lightweight but modern Mastodon client for the desktop
QML
193
star
18

go-app-paths

Lets you retrieve platform-specific paths (like directories for app-data, cache, config, and logs)
Go
175
star
19

deckmaster

An application to control your Elgato Stream Deck on Linux
Go
169
star
20

prism

An RTMP stream recaster / splitter
Go
150
star
21

asciicam

Displays your webcam... on the terminal
Go
124
star
22

gitflux

Track your GitHub projects in InfluxDB and create beautiful graphs with Grafana
Go
117
star
23

cancelreader

A cancelable reader for Go
Go
102
star
24

service-tools

A growing collection of convenient little tools to work with systemd services
Go
91
star
25

mastotool

A collection of command-line tools to work with your Mastodon account
Go
89
star
26

thunder

BoltDB's Interactive Shell
Go
80
star
27

sticker

A Golang lib to generate placeholder images with text
Go
79
star
28

toktok

Typo/error resilient, human-readable token generator
Go
67
star
29

sasquatch

A simple data encryption library
Go
56
star
30

combinator

Generates a slice of all possible value combinations for any given struct and a set of its potential member values
Go
48
star
31

lighthouse

A fully modular, parametric, and customizable case design. Built with OpenSCAD.
OpenSCAD
43
star
32

roff

roff lets you write roff documents in Go
Go
42
star
33

pam-beacon

PAM module for multi-factor authentication with Bluetooth Devices & Beacons
Go
41
star
34

streamdeck

An application and Go library to control your Elgato Stream Deck on Linux
Go
41
star
35

marky

Generate markdown programmatically
Go
40
star
36

sync3c

A little tool to sync/download media from https://media.ccc.de
Go
36
star
37

muesli

My secret muesli repo
33
star
38

huephp

PHP library to control the Philips Hue lighting system
PHP
33
star
39

obs-scene-switcher

Tracks your active window and switches OBS scenes accordingly
Go
32
star
40

mango-cobra

cobra adapter for mango
Go
31
star
41

scratchy

Quickly bootstrap a Linux distro in a (non-Docker) container and interactively execute something in it
Go
27
star
42

gitcha

Go helpers to work with git repositories
Go
25
star
43

ansi

Raw ANSI sequence helpers
Go
19
star
44

goprogressbar

Print progress bars on the console with Go
Go
19
star
45

ircflu

ircflu is an IRC bot written in Go
Go
19
star
46

go-razer

Go library to control Razer (Chroma) devices
Go
18
star
47

magicwand

MagicWand makes your input devices context sensitive
Go
17
star
48

gotable

Go helper to print a table of data to stdout
Go
15
star
49

goefa

A Go client for EFA APIs (Elektronische Fahrplan Auskunft)
Go
15
star
50

ydl

A simple youtube-dl library for Go
Go
15
star
51

xray

xray compares media files by their perceptual hash and identifies dupes
C++
15
star
52

clusters

Data structs and algorithms for clustering data observations and basic computations in n-dimensional spaces
Go
14
star
53

dotfiles

My dotfiles
Shell
14
star
54

saloon

Saloon, an Arduino/ESP-based Information Monitor
C++
13
star
55

cap-generator

OpenSCAD cap with thread generator
OpenSCAD
13
star
56

elvish-libs

Libs / Themes for elvish
13
star
57

ms-pacman

Handy scripts for Arch Linux users
Shell
12
star
58

silhouette

Silhouette cluster analysis implementation in Go
Go
11
star
59

penpal

A Linux daemon to sync Wacom Bamboo devices
Go
10
star
60

code-server

My code-server Docker image
Dockerfile
10
star
61

beehive-admin

Admin interface to Beehive - https://github.com/muesli/beehive
JavaScript
9
star
62

smolder

smolder makes it easy to write restful Golang JSON APIs
Go
9
star
63

mango-coral

coral adapter for mango
Go
8
star
64

deckmaster-emojis

A deck of emojis for Deckmaster
8
star
65

configaro

The Marriage of (Con)Figaro - A small but flexible config system that's XDG-compliant
6
star
66

smartcrop-samples

Sample images to test the smartcrop algorithm with
6
star
67

gominatim

Go library to access nominatim geocoding services
Go
5
star
68

go-pkg-rss

go-pkg-rss
Go
5
star
69

go-crashcourse

A Crash-Course in Learning Go
Go
5
star
70

homebrew-tap

muesli's Homebrew tap
Ruby
4
star
71

bones

A Golang Code Doctor
Go
4
star
72

mango-pflag

pflag adapter for mango
Go
3
star
73

polly

Polly wants a cracker
Go
3
star
74

maker-coin

A simple Maker Coin designed in OpenSCAD
Python
3
star
75

quaint

Image & static content HTTP server written in Go
Go
3
star
76

videowall

An interactive wall of live videos
C++
2
star
77

filament-swatch

Parameterized Filament Swatch / Sample Tag in OpenSCAD
OpenSCAD
2
star
78

flipdots

Go library to access OpenLab's flipdot matrix
Go
2
star
79

pkgbuilds

My collection of Arch Linux PKGBUILDs
Shell
2
star
80

beehive-vendor

Vendor files for Beehive
Go
2
star
81

QtGaugeWidget

Gauge widget for Qt
C++
1
star
82

go-pkg-xmlx

go-pkg-xmlx
Go
1
star
83

jigo

A set of #golang jigs
1
star
84

nibbler

Network logging daemon written in Go
Go
1
star
85

comunit

PASCAL interface to access serial COM ports
Pascal
1
star
86

tomahawk-iOS

Tomahawk iOS Player
Objective-C
1
star