sgr

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2022 License: BSD-3-Clause Imports: 8 Imported by: 5

README

Package sgr

Go Reference Go Report Card builds.sr.ht status Coverage badge Version badge

Package sgr provides formatters to write ANSI escape sequences that can format and colorize text.

Banner image

Install

The package can be installed from the command line using the go tool. There are no dependencies beyond the standard library. Any version of Go should work.

go get git.sr.ht/~rj/sgr

Getting Started

Package documentation and examples are on Go Reference.

As a small introduction, the following snippet prints to the console using some bold text. You can experiment with the snippet on the go playground.

func main() {
	// The formatter is responsible for deciding when and what escape
	// codes to use.  The call to NewFormatter will return a formatter
	// suitable for use with standard out.
	f := sgr.NewFormatter()

	// Print some text with bold.
	fmt.Println("Hello,", f.Bold("world!"))
}

Contribute

To submit bug reports and suggestions, please use the issue tracker.

Discussions occur using the mailing list. The mailing list can also be used to submit patches.

Scope

This packages does not aim to support a complete list of SGR escape codes, either for all possible terminals or even as defined in the standard. The supported codes should be widely portable across many terminals and operating systems.

Windows: Terminals on windows will increasingly support ANSI escape sequences, but current support may be uneven. The legacy API for setting text attributes has been, if not deprecated, discouraged. Therefore, direct support for the legacy API is not planned. If older terminials must be supported, then go-colorable can be used.

License

BSD (c) Robert Johnstone

Documentation

Overview

Package sgr providers formatters to write ANSI escape sequences that can format and colorize text.

The exact appearance of text, and whether or not various characteristics are even supported, will depend on the terminal capabilities. In particular, writing to a regular file will suppress all ANSI escapes sequences.

Package sgr will default to no-color when there is doubt about whether or not the output stream can support ANSI sequences.

There are some convenience methods to print common options, such as bold or red text. To get full control over the color and formatting of some text, first create a Style, and then use Formatter.Style.

Printing

Calls to functions and methods in this package do not directly result in any io. To get the colorized text, the return values of certain methods must be printed using package fmt.

For methods simply taking a string, such as Formatter.Bold, the returned value must be printed using either the verb %v or %s. All of the options for %s are supported, including width, precision, and flags.

For methods that take a format string plus arguments, such as Formatter.Boldf, the returned value must still be printed using either %v or %s. However, no options are supported. To control options such as width and precision, use the format string passed to Formatter.Boldf

Environment Variables

Selection of the correct formatter depends on several environment variables. Primarily, package sgr checks the value of TERM to see if any color space attributes are present. ANSI compatibility is always assumed, but the color depth will be adjusted. However, if TERM is equal to 'dumb', then all formatting will be suppressed.

Some terminals use COLORTERM to advertise 24-bit capability. If COLORTERM is equal to 'truecolor' or '24bit', then the formatter will support a 24-bit color depth.

Finally, if the environment variable NO_COLOR is present, no matter its value, the color depth will be 1-bit. This does not disable all formatting, so text attributes such as bold and italic are still possible, but all colors will be suppressed.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Color

type Color uint8

Color represents a 4-bit "standard" color from the ANSI specification. The color can be used to set the foreground or background color for text.

const (
	Black Color = iota
	Red
	Green
	Yellow // Also known as brown.  Try BrightYellow.
	Blue
	Magenta
	Cyan
	White
	Default Color = 9

	Gray      Color = 51 + iota // Also known as bright black
	BrightRed                   // Also known as pink
	BrightGreen
	BrightYellow
	BrightBlue
	BrightMagenta
	BrightCyan
	BrightWhite
)

The following colors are the standard color provided by the ANSI standard.

type Formatter

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

A Formatter contains information about the capabilities of the output Writer, such as whether or not it supports ANSI escape sequences, and which sequences are available.

Methods on this type all support being called with a nil pointer. This state suppresses all escape sequences, and, in some cases, allows optimizations where strings are passed through directly.

func NewFormatter

func NewFormatter() *Formatter

NewFormatter returns a formatter suitable for use with Stdout.

func NewFormatterForFile

func NewFormatterForFile(file *os.File) *Formatter

NewFormatterForFile returns a formatter suitable for use with the file.

func NewFormatterForTerm added in v0.10.0

func NewFormatterForTerm(term string) *Formatter

NewFormatterForTerm returns a formatter with the correct color depth based on the terminal identification string.

func NewFormatterForWriter

func NewFormatterForWriter(w io.Writer) *Formatter

NewFormatterForWriter returns a formatter suitable for use with the writer.

func NewFormatterWithANSI

func NewFormatterWithANSI() *Formatter

NewFormatterWithANSI returns a formatter that will always use ANSI escape sequences. This function exists for testing, and should not be used in normal code.

func (*Formatter) Bold

func (f *Formatter) Bold(text string) interface{}

Bold returns an object which will show the text in bold when printed using a function in package fmt.

Example
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// In this case, stdout does not support ANSI escape sequences
	f := sgr.NewFormatter()
	fmt.Printf("%#v\n",
		fmt.Sprintf("Hello, %s!\n", f.Bold("world")))

	// Force the use of ANSI escape sequences
	f = sgr.NewFormatterWithANSI()
	fmt.Printf("%#v\n",
		fmt.Sprintf("Hello, %s!\n", f.Bold("world")))

}
Output:

"Hello, world!\n"
"Hello, \x1b[1mworld\x1b[0m!\n"
Example (Badverb)
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// Force the use of ANSI escape sequences
	f := sgr.NewFormatterWithANSI()
	// Oops.  Wrong verb used.
	fmt.Printf("Found %d items.\n", f.Bold("42"))

}
Output:

Found %!d(sgr.formatter=42) items.
Example (Flags)
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// Force the use of ANSI escape sequences
	f := sgr.NewFormatterWithANSI()
	fmt.Printf("%#v\n%#v\n%#v\n%#v\n",
		fmt.Sprintf(">%s<", f.Bold("Hello, world")),
		fmt.Sprintf(">%20s<", f.Bold("Hello, world")),
		fmt.Sprintf(">%-20s<", f.Bold("Hello, world")),
		fmt.Sprintf(">%.5s<", f.Bold("Hello, world")),
	)

}
Output:

">\x1b[1mHello, world\x1b[0m<"
">\x1b[1m        Hello, world\x1b[0m<"
">\x1b[1mHello, world        \x1b[0m<"
">\x1b[1mHello\x1b[0m<"

func (*Formatter) Boldf

func (f *Formatter) Boldf(format string, a ...interface{}) interface{}

Boldf returns an object which will show the formatted text in bold when printed using a function in package fmt.

Example
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// In this case, stdout does not support ANSI escape sequences
	f := sgr.NewFormatter()
	fmt.Printf("%#v\n",
		fmt.Sprintf("Found %s items.\n", f.Boldf("%d", 42)))

	// Force the use of ANSI escape sequences
	f = sgr.NewFormatterWithANSI()
	fmt.Printf("%#v\n",
		fmt.Sprintf("Found %s items.\n", f.Boldf("%d", 42)))

}
Output:

"Found 42 items.\n"
"Found \x1b[1m42\x1b[0m items.\n"
Example (Badverb)
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// Force the use of ANSI escape sequences
	f := sgr.NewFormatterWithANSI()
	// Oops.  Wrong verb used.
	fmt.Printf("Found %d items.\n", f.Boldf("%d", 42))

}
Output:

Found %!d(format string=%d) items.
Example (Badwidth)
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// Force the use of ANSI escape sequences
	f := sgr.NewFormatterWithANSI()
	// Oops.  Width isn't supported.
	fmt.Printf("%#v\n",
		fmt.Sprintf("Found %20s items.", f.Boldf("%d", 42)))

}
Output:

"Found \x1b[1m%!(BADWIDTH)42\x1b[0m items."

func (*Formatter) ColorDepth added in v0.8.0

func (f *Formatter) ColorDepth() int

ColorDepth returns the bit-depth used by the terminal to represent colors.

Example (Nil)
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// It is safe to call the method ColorDepth on a nil Formatter.
	f := (*sgr.Formatter)(nil)
	fmt.Printf("Color depth: %d", f.ColorDepth())

}
Output:

Color depth: 0

func (*Formatter) Dim

func (f *Formatter) Dim(text string) interface{}

Dim returns an object which will show the text dimmed when printed using a function in package fmt.

func (*Formatter) Dimf

func (f *Formatter) Dimf(format string, a ...interface{}) interface{}

Dimf returns an object which will show the formatted text dimmed when printed using a function in package fmt.

func (*Formatter) Green

func (f *Formatter) Green(text string) interface{}

Green returns an object which will show the text in green when printed using a function in package fmt.

func (*Formatter) Greenf

func (f *Formatter) Greenf(format string, a ...interface{}) interface{}

Greenf returns an object which will show the formatted text in green when printed using a function in package fmt.

func (*Formatter) Italic added in v0.14.0

func (f *Formatter) Italic(text string) interface{}

Italic returns an object which will show the text in italic when printed using a function in package fmt.

func (*Formatter) Italicf added in v0.14.0

func (f *Formatter) Italicf(format string, a ...interface{}) interface{}

Italicf returns an object which will show the formatted text in italic when printed using a function in package fmt.

func (*Formatter) NewStyle added in v0.8.0

func (f *Formatter) NewStyle(ops ...StyleOption) Style

NewStyle creates a new style by combining the specified display attributes. Display attributes can alter formatting, like bold and italic, or specify colors.

Not all terminals will support all attributes. In particular, colors will be mapped to lower color-width values to match the terminal's support.

func (*Formatter) Red

func (f *Formatter) Red(text string) interface{}

Red returns an object which will show the text in red when printed using a function in package fmt.

func (*Formatter) Redf

func (f *Formatter) Redf(format string, a ...interface{}) interface{}

Redf returns an object which will show the formatted text in red when printed using a function in package fmt.

func (*Formatter) Style

func (f *Formatter) Style(style Style, format string, a ...interface{}) interface{}

Style returns an object which will show the formatted text in requested style when printed using a function in package fmt.

Example
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// Force the use of ANSI escape sequences
	f := sgr.NewFormatterWithANSI()

	// Create our fancy, fancy style.
	myStyle := f.NewStyle(sgr.Bold, sgr.Blink, sgr.FG(sgr.Blue))
	// And print something.
	fmt.Printf("%#v\n",
		fmt.Sprintf("Hello, %s\n", f.Style(myStyle, "world!")))

}
Output:

"Hello, \x1b[1;5;34mworld!\x1b[0m\n"

type PaletteColor added in v0.9.0

type PaletteColor uint8

PaletteColor represents an 8-bit color from the ANSI specification. The color can be used to set the foreground or background color for text.

func (PaletteColor) RGBA added in v0.9.0

func (c PaletteColor) RGBA() (r, g, b, a uint32)
Example
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	const color = sgr.PaletteColor(21 /* bright blue*/)

	// PaletteColor implements the color.Color interface.
	r, g, b, a := color.RGBA()
	fmt.Printf("%04x %04x %04x %04x\n", r, g, b, a)

}
Output:

0000 0000 ffff ffff

type Style

type Style []byte

Style represents a set of display attributes to use when printing text. A style can combine attributes such as whether the text is bold or dimmed, as well as setting foreground and background colors.

A Style created by a Formatter should not be used with different Formatters. The style encodes parameters that may be specific to the terminal's capabilities.

Example
package main

import (
	"fmt"

	"git.sr.ht/~rj/sgr"
)

func main() {
	// In this case, stdout does not support ANSI escape sequences
	f := sgr.NewFormatter()
	s := f.NewStyle(sgr.Bold, sgr.FG(sgr.Green), sgr.BG(sgr.Yellow))
	fmt.Printf("%#v\n",
		fmt.Sprintf("Hello, %s!\n", f.Style(s, "world")))

	// Force the use of ANSI escape sequences
	f = sgr.NewFormatterWithANSI()
	s = f.NewStyle(sgr.Bold, sgr.FG(sgr.Green), sgr.BG(sgr.Yellow))
	fmt.Printf("%#v\n",
		fmt.Sprintf("Hello, %s!\n", f.Style(s, "world")))

}
Output:

"Hello, world!\n"
"Hello, \x1b[1;32;43mworld\x1b[0m!\n"

type StyleOption

type StyleOption uint32

StyleOption encodes a single display attribute.

const (
	Bold       StyleOption = 1 // Set the style to bold.
	Dim        StyleOption = 2 // Set the style to dim.
	Italic     StyleOption = 3 // Set the style to italic.
	Underline  StyleOption = 4 // Set the style to underline.
	Blink      StyleOption = 5 // Set the style to blink.
	Reverse    StyleOption = 7 // Set the style to reverse video.
	CrossedOut StyleOption = 9 // Set the style to crossed-out.
)

Display attributes available for use with NewStyle.

func BG

func BG(clr Color) StyleOption

BG creates a StyleOption that will set the background color to one of the colors in the 4-bit palette.

func BG24 added in v0.8.0

func BG24(r, g, b uint8) StyleOption

BG24 creates a StyleOption that will set the background color.

func BG8 added in v0.8.0

func BG8(index PaletteColor) StyleOption

BG8 creates a StyleOption that will set the background color to one of the colors in the 8-bit palette.

func FG

func FG(clr Color) StyleOption

FG creates a StyleOption that will set the foreground color to one of the colors in the 4-bit palette.

func FG24 added in v0.8.0

func FG24(r, g, b uint8) StyleOption

FG24 creates a StyleOption that will set the foreground color.

func FG8 added in v0.8.0

func FG8(index PaletteColor) StyleOption

FG8 creates a StyleOption that will set the foreground color to one of the colors in the 8-bit palette.

Directories

Path Synopsis
example
banner
Package banner creates the banner image shown in the README.
Package banner creates the banner image shown in the README.
color
Package color shows all of the foreground and background color options.
Package color shows all of the foreground and background color options.
horizontalbar
Package horizontalbar shows examples of horizontal bars from package plot.
Package horizontalbar shows examples of horizontal bars from package plot.
progressbar
Package progressbar shows a updating progress bar based on package plot.
Package progressbar shows a updating progress bar based on package plot.
simple
Package simple shows the simple text formatting options.
Package simple shows the simple text formatting options.
style
Package style shows the types of text formatting that are possible.
Package style shows the types of text formatting that are possible.
internal
pad
Package pad writes padding to memory buffers.
Package pad writes padding to memory buffers.
palette
Package palette provides mapping for 24-bit colors to the 8-bit ANSI SGR palette.
Package palette provides mapping for 24-bit colors to the 8-bit ANSI SGR palette.
Package plot providers simple plots using ascii and ANSI escape sequences.
Package plot providers simple plots using ascii and ANSI escape sequences.
Package wcwidth provides functions to determine the number of columns required when printing to a terminal.
Package wcwidth provides functions to determine the number of columns required when printing to a terminal.

Jump to

Keyboard shortcuts

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