termenv

package module
Version: v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2021 License: MIT Imports: 12 Imported by: 121

README

termenv Logo
Latest Release GoDoc Build Status Coverage Status Go ReportCard

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.

Example output

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

Query Terminal Support

termenv can query the terminal it is running in, so you can safely use advanced features, like RGB colors. ColorProfile returns the color profile supported by the terminal:

profile := termenv.ColorProfile()

This returns one of the supported color profiles:

  • 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

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 := termenv.ForegroundColor()

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

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

Colors

termenv supports multiple color profiles: 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 := termenv.String("Hello World")

// Retrieve color profile supported by terminal
p := termenv.ColorProfile()

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

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

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

Styles

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

s := termenv.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

// load template helpers
f := termenv.TemplateFuncs(termenv.ColorProfile())
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.

Screen

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

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

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

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

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

// Hide the cursor
termenv.HideCursor()

// Show the cursor
termenv.ShowCursor()

// Save the cursor position
termenv.SaveCursorPosition()

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

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

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

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

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

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

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

// Clear the current line
termenv.ClearLine()

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

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

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

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

Mouse

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

// Disable X10 mouse mode
termenv.DisableMousePress()

// Enable Mouse Tracking mode
termenv.EnableMouse()

// Disable Mouse Tracking mode
termenv.DisableMouse()

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

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

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

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

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

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

Color Chart

ANSI color chart

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

  • reflow - ANSI-aware text operations
  • Glow - a markdown renderer for the command-line, which uses termenv

License

MIT

Documentation

Index

Constants

View Source
const (
	Foreground = "38"
	Background = "48"
)
View Source
const (
	CursorUpSeq              = "%dA"
	CursorDownSeq            = "%dB"
	CursorForwardSeq         = "%dC"
	CursorBackSeq            = "%dD"
	CursorNextLineSeq        = "%dE"
	CursorPreviousLineSeq    = "%dF"
	CursorHorizontalSeq      = "%dG"
	CursorPositionSeq        = "%d;%dH"
	EraseDisplaySeq          = "%dJ"
	EraseLineSeq             = "%dK"
	ScrollUpSeq              = "%dS"
	ScrollDownSeq            = "%dT"
	SaveCursorPositionSeq    = "s"
	RestoreCursorPositionSeq = "u"
	ChangeScrollingRegionSeq = "%d;%dr"
	InsertLineSeq            = "%dL"
	DeleteLineSeq            = "%dM"

	// Explicit values for EraseLineSeq.
	EraseLineRightSeq  = "0K"
	EraseLineLeftSeq   = "1K"
	EraseEntireLineSeq = "2K"

	ShowCursorSeq             = "?25h"
	HideCursorSeq             = "?25l"
	EnableMousePressSeq       = "?9h" // press only (X10)
	DisableMousePressSeq      = "?9l"
	EnableMouseSeq            = "?1000h" // press, release, wheel
	DisableMouseSeq           = "?1000l"
	EnableMouseHiliteSeq      = "?1001h" // highlight
	DisableMouseHiliteSeq     = "?1001l"
	EnableMouseCellMotionSeq  = "?1002h" // press, release, move on pressed, wheel
	DisableMouseCellMotionSeq = "?1002l"
	EnableMouseAllMotionSeq   = "?1003h" // press, release, move, wheel
	DisableMouseAllMotionSeq  = "?1003l"
	AltScreenSeq              = "?1049h"
	ExitAltScreenSeq          = "?1049l"
)
View Source
const (
	ResetSeq     = "0"
	BoldSeq      = "1"
	FaintSeq     = "2"
	ItalicSeq    = "3"
	UnderlineSeq = "4"
	BlinkSeq     = "5"
	ReverseSeq   = "7"
	CrossOutSeq  = "9"
	OverlineSeq  = "53"
)
View Source
const (
	CSI = "\x1b["

	Ascii = Profile(iota)
	ANSI
	ANSI256
	TrueColor
)

Variables

View Source
var (
	ErrInvalidColor = errors.New("invalid color")
)
View Source
var (
	ErrStatusReport = errors.New("unable to retrieve status report")
)

Functions

func AltScreen added in v0.5.0

func AltScreen()

AltScreen switches to the alternate screen buffer. The former view can be restored with ExitAltScreen().

func ChangeScrollingRegion added in v0.6.0

func ChangeScrollingRegion(top, bottom int)

ChangeScrollingRegion sets the scrolling region of the terminal.

func ClearLine added in v0.5.0

func ClearLine()

ClearLine clears the current line.

func ClearLineLeft added in v0.9.0

func ClearLineLeft()

ClearLineLeft clears the line to the left of the cursor.

func ClearLineRight added in v0.9.0

func ClearLineRight()

ClearLineRight clears the line to the right of the cursor.

func ClearLines added in v0.5.0

func ClearLines(n int)

ClearLines clears a given number of lines.

func ClearScreen added in v0.5.0

func ClearScreen()

ClearScreen clears the visible portion of the terminal.

func ConvertToRGB

func ConvertToRGB(c Color) colorful.Color

func CursorBack added in v0.6.0

func CursorBack(n int)

CursorBack moves the cursor backwards a given number of cells.

func CursorDown added in v0.5.2

func CursorDown(n int)

CursorDown moves the cursor down a given number of lines.

func CursorForward added in v0.6.0

func CursorForward(n int)

CursorForward moves the cursor up a given number of lines.

func CursorNextLine added in v0.5.0

func CursorNextLine(n int)

CursorNextLine moves the cursor down a given number of lines and places it at the beginning of the line.

func CursorPrevLine added in v0.5.0

func CursorPrevLine(n int)

CursorPrevLine moves the cursor up a given number of lines and places it at the beginning of the line.

func CursorUp added in v0.5.2

func CursorUp(n int)

CursorUp moves the cursor up a given number of lines.

func DeleteLines added in v0.6.0

func DeleteLines(n int)

DeleteLines deletes the given number of lines, pulling any lines in the scrollable region below up.

func DisableMouse added in v0.6.0

func DisableMouse()

DisableMouse disables Mouse Tracking mode.

func DisableMouseAllMotion added in v0.6.0

func DisableMouseAllMotion()

DisableMouseAllMotion disables All Motion Mouse mode.

func DisableMouseCellMotion added in v0.6.0

func DisableMouseCellMotion()

DisableMouseCellMotion disables Cell Motion Mouse Tracking mode.

func DisableMouseHilite added in v0.6.0

func DisableMouseHilite()

DisableMouseHilite disables Hilite Mouse Tracking mode.

func DisableMousePress added in v0.6.0

func DisableMousePress()

DisableMousePress disables X10 mouse mode.

func EnableMouse added in v0.6.0

func EnableMouse()

EnableMouse enables Mouse Tracking mode.

func EnableMouseAllMotion added in v0.6.0

func EnableMouseAllMotion()

EnableMouseAllMotion enables All Motion Mouse mode.

func EnableMouseCellMotion added in v0.6.0

func EnableMouseCellMotion()

EnableMouseCellMotion enables Cell Motion Mouse Tracking mode.

func EnableMouseHilite added in v0.6.0

func EnableMouseHilite()

EnableMouseHilite enables Hilite Mouse Tracking mode.

func EnableMousePress added in v0.6.0

func EnableMousePress()

EnableMousePress enables X10 mouse mode. Button press events are sent only.

func EnvNoColor added in v0.7.2

func EnvNoColor() bool

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.

func ExitAltScreen added in v0.5.0

func ExitAltScreen()

ExitAltScreen exits the alternate screen buffer and returns to the former terminal view.

func HasDarkBackground

func HasDarkBackground() bool

HasDarkBackground returns whether terminal uses a dark-ish background.

func HideCursor added in v0.5.0

func HideCursor()

HideCursor hides the cursor.

func InsertLines added in v0.6.0

func InsertLines(n int)

InsertLines inserts the given number of lines at the top of the scrollable region, pushing lines below down.

func MoveCursor added in v0.5.0

func MoveCursor(row int, column int)

MoveCursor moves the cursor to a given position.

func Reset added in v0.5.1

func Reset()

Reset the terminal to its default style, removing any active styles.

func RestoreCursorPosition added in v0.6.0

func RestoreCursorPosition()

RestoreCursorPosition restores a saved cursor position.

func SaveCursorPosition added in v0.6.0

func SaveCursorPosition()

SaveCursorPosition saves the cursor position.

func ShowCursor added in v0.5.0

func ShowCursor()

ShowCursor shows the cursor.

func TemplateFuncs

func TemplateFuncs(p Profile) template.FuncMap

TemplateFuncs contains a few useful template helpers.

Types

type ANSI256Color

type ANSI256Color int

ANSI256Color is a color (16-255) as defined by the ANSI Standard.

func (ANSI256Color) Sequence

func (c ANSI256Color) Sequence(bg bool) string

type ANSIColor

type ANSIColor int

ANSIColor is a color (0-15) as defined by the ANSI Standard.

const (
	ANSIBlack ANSIColor = iota
	ANSIRed
	ANSIGreen
	ANSIYellow
	ANSIBlue
	ANSIMagenta
	ANSICyan
	ANSIWhite
	ANSIBrightBlack
	ANSIBrightRed
	ANSIBrightGreen
	ANSIBrightYellow
	ANSIBrightBlue
	ANSIBrightMagenta
	ANSIBrightCyan
	ANSIBrightWhite
)

func (ANSIColor) Sequence

func (c ANSIColor) Sequence(bg bool) string

type Color

type Color interface {
	Sequence(bg bool) string
}

func BackgroundColor

func BackgroundColor() Color

BackgroundColor returns the terminal's default background color.

func ForegroundColor

func ForegroundColor() Color

ForegroundColor returns the terminal's default foreground color.

type NoColor

type NoColor struct{}

func (NoColor) Sequence

func (c NoColor) Sequence(bg bool) string

type Profile

type Profile int

func ColorProfile

func ColorProfile() Profile

ColorProfile returns the supported color profile: Ascii, ANSI, ANSI256, or TrueColor.

func EnvColorProfile added in v0.7.2

func EnvColorProfile() Profile

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.

func (Profile) Color

func (p Profile) Color(s string) Color

func (Profile) Convert

func (p Profile) Convert(c Color) Color

func (Profile) FromColor added in v0.8.0

func (p Profile) FromColor(c color.Color) Color

type RGBColor

type RGBColor string

RGBColor is a hex-encoded color, e.g. "#abcdef".

func (RGBColor) Sequence

func (c RGBColor) Sequence(bg bool) string

type Style

type Style struct {
	// contains filtered or unexported fields
}

Style is a string that various rendering styles can be applied to.

func String

func String(s ...string) Style

String returns a new Style.

func (Style) Background

func (t Style) Background(c Color) Style

Background sets a background color.

func (t Style) Blink() Style

Blink enables blink mode.

func (Style) Bold

func (t Style) Bold() Style

Bold enables bold rendering.

func (Style) CrossOut

func (t Style) CrossOut() Style

CrossOut enables crossed-out rendering.

func (Style) Faint

func (t Style) Faint() Style

Faint enables faint rendering.

func (Style) Foreground

func (t Style) Foreground(c Color) Style

Foreground sets a foreground color.

func (Style) Italic

func (t Style) Italic() Style

Italic enables italic rendering.

func (Style) Overline

func (t Style) Overline() Style

Overline enables overline rendering.

func (Style) Reverse

func (t Style) Reverse() Style

Reverse enables reverse color mode.

func (Style) String

func (t Style) String() string

func (Style) Styled

func (t Style) Styled(s string) string

Styled renders s with all applied styles.

func (Style) Underline

func (t Style) Underline() Style

Underline enables underline rendering.

func (Style) Width added in v0.6.0

func (t Style) Width() int

Width returns the width required to print all runes in Style.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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