termcols

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2024 License: MIT Imports: 6 Imported by: 0

README

logo

Colorful text in your terminal implemented in Go

The termcols package implements ANSI color codes that can be used to color text on the terminal. Different styles and foreground/background colors can be chained together through an intuitive package API to arrive at some cool visual effects.

The selection of style and color control sequences implemented by the package was largely based on an exhaustive list of Select Graphic Rendition (SGR) control sequences available at Wikipedia ANSI. It is a great resource in case one or more elements appear not to be supported in a given terminal.

The Escape sequence for termcols is set to \033, which means that it should work without any issues with Bash, Zsh or Dash. Other shells might not support it.

The same applies to 8-bit and 24-bit colors: there is no guarantee that these escape sequences are supported will be rendered properly on some terminals. Results may vary, so it is good practice to test it first for compatibility.

Consult the package documentation or see Usage section below to check how to use the public API of the termcols package.

Installation

Use the following command to add the package to an existing project.

go get github.com/mdm-code/termcols

Install the package to use the command-line tcols command to colorize text on the terminal.

go install github.com/mdm-code/termcols@latest

Usage

Here is an example of how to use the public API of the termcols package.

package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	s := termcols.Colorize(
		"Colorized text!",
		termcols.RedFg,
		termcols.Underline,
		termcols.Rgb24(termcols.BG, 120, 255, 54),
	)
	fmt.Println(s)
}

Aside from using the termcols package API that can be used in your Go project, can use the tcols terminal command:

tcols --style 'redfg underline rgb24=bg:120:255:54' < <(echo -n 'Hello, world!')

Type tcols -h to get a list of styles and colors to (1) see what is implemented and (2) what is supported by your terminal.

Alternatively, tcols can be run from inside of the Docker container:

docker run -i ghcr.io/mdm-code/tcols:latest tcols -s 'redfg bluebg' < <(echo -n 'Hello, world!')

Development

Consult Makefile to see how to format, examine code with go vet, run unit test, run code linter with golint get test coverage and check if the package builds all right.

Remember to install golint before you try to run tests and test the build:

go install golang.org/x/lint/golint@latest

In order to run the benchmark test on unsafe pointers in the tercmols package, fire up the following command:

go test -bench=.

This will give you ns/op value for the setup it's been benchmarked on.

License

Copyright (c) 2024 Michał Adamczyk.

This project is licensed under the MIT license. See LICENSE for more details.

Documentation

Overview

Package termcols implements ANSI color codes that can be used to color text on the terminal. Different styles and foreground/background colors can be chained together through an intuitive package API to arrive at some cool visual effects.

The selection of style and color control sequences implemented by the package was largely based on an exhaustive list of Select Graphic Rendition (SGR) control sequences available at Wikipedia ANSI. It is a great resource in case one or more elements appear not to be supported in a given terminal.

The Escape sequence for termcols is set to \033, which means that it should work without any issues with Bash, Zsh or Dash. Other shells might not support it.

The same applies to 8-bit and 24-bit colors: there is no guarantee that these escape sequences are supported will be rendered properly on some terminals. Results may vary, so it is good practice to test it first for compatibility.

The package has two public functions MapColor and MapColors that accept string values to try and map it onto a valid SgrAttr, however, it has been made implemented to simplify the terminal tcols command.

Usage

package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	s := termcols.Colorize(
		"Colorized text!",
		termcols.RedFg,
		termcols.Underline,
		termcols.Rgb24(termcols.BG, 120, 255, 54),
	)
	fmt.Println(s)
}

Index

Examples

Constants

View Source
const (
	// Esc octal sequence \033 works with Bash, Zsh and Dash (appears not to in
	// Ksh and Csh). There are other escape sequence code representations: the
	// ctrl-key ^[ sequence, unicode \u001b, hexadecimal \x1b, \0x1B, decimal
	// 27 and \e are the ones that I came across.
	Esc = "\033"

	// Csi stands for Control Sequence Introducer
	Csi = Esc + "["
)

Variables

View Source
var (
	// ErrMap indicates that there were issues with disambiguating color names.
	ErrMap = errors.New("Color mapping error")
)

Functions

func Colorize

func Colorize(s string, attrs ...SgrAttr) string

Colorize returns a string literal s with attrs SGR control sequences prepended and the reset control sequence appended at the end. The sequence of attrs passed to the function call is preserved, so colors and styles can (un)intentionally cancel out one another.

Example

ExampleColorize shows how to use termcols public API Colorize function. It uses a combination of style, foreground and colors to stylize the “Colorize text\!” string.

package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	s := termcols.Colorize(
		"Colorized text!",
		termcols.RedFg,
		termcols.Underline,
		termcols.Rgb24(termcols.BG, 120, 255, 54),
	)
	fmt.Println(s)
}
Output:

�[31m�[4m�[48;2;120;255;54mColorized text!�[0m

Types

type Layer

type Layer string

Layer is used to specify whether the color should be applied to either foreground or background. The default format for the RGB set foreground/background color control sequence for 24-bit colors is {Layer};2;{R};{G};{B}m, and for 8-bit colors this is {Layer};5;{Color}m as implemented in Rgb8 and Rgb24 public functions respectively.

const (
	FG Layer = Csi + "38"
	BG Layer = Csi + "48"
)

Layer

type SgrAttr

type SgrAttr string

SgrAttr corresponds to an SGR (Select Graphic Rendition) control sequence. It sets display attributes. Each SGR parameter remains active until it is reset with the `CSI 0m` [RESET] control sequence.

const (
	Bold         SgrAttr = Csi + "1m"
	Faint        SgrAttr = Csi + "2m"
	Italic       SgrAttr = Csi + "3m"
	Underline    SgrAttr = Csi + "4m"
	Blink        SgrAttr = Csi + "5m"
	Reverse      SgrAttr = Csi + "7m"
	Hide         SgrAttr = Csi + "8m"
	Strike       SgrAttr = Csi + "9m"
	DefaultStyle SgrAttr = Csi + "10m"
)

Style

const (
	BlackFg   SgrAttr = Csi + "30m"
	RedFg     SgrAttr = Csi + "31m"
	GreenFg   SgrAttr = Csi + "32m"
	YellowFg  SgrAttr = Csi + "33m"
	BlueFg    SgrAttr = Csi + "34m"
	MagentaFg SgrAttr = Csi + "35m"
	CyanFg    SgrAttr = Csi + "36m"
	WhiteFg   SgrAttr = Csi + "37m"
	DefaultFg SgrAttr = Csi + "39m"
)

Normal foreground

const (
	BlackBfg   SgrAttr = Csi + "90m"
	RedBfg     SgrAttr = Csi + "91m"
	GreenBfg   SgrAttr = Csi + "92m"
	YellowBfg  SgrAttr = Csi + "93m"
	BlueBfg    SgrAttr = Csi + "94m"
	MagentaBfg SgrAttr = Csi + "95m"
	CyanBfg    SgrAttr = Csi + "96m"
	WhiteBfg   SgrAttr = Csi + "97m"
)

Bright foreground

const (
	BlackBg   SgrAttr = Csi + "40m"
	RedBg     SgrAttr = Csi + "41m"
	GreenBg   SgrAttr = Csi + "42m"
	YellowBg  SgrAttr = Csi + "43m"
	BlueBg    SgrAttr = Csi + "44m"
	MagentaBg SgrAttr = Csi + "45m"
	CyanBg    SgrAttr = Csi + "46m"
	WhiteBg   SgrAttr = Csi + "47m"
	DefaultBg SgrAttr = Csi + "49m"
)

Normal background

const (
	BlackBbg   SgrAttr = Csi + "100m"
	RedBbg     SgrAttr = Csi + "101m"
	GreenBbg   SgrAttr = Csi + "102m"
	YellowBbg  SgrAttr = Csi + "103m"
	BlueBbg    SgrAttr = Csi + "104m"
	MagentaBbg SgrAttr = Csi + "105m"
	CyanBbg    SgrAttr = Csi + "106m"
	WhiteBbg   SgrAttr = Csi + "107m"
)

Bright background

const Reset SgrAttr = Csi + "0m"

Reset control sequence

func MapColor

func MapColor(s string) (SgrAttr, error)

MapColor attempts to interpret the string s as either one of the predefined colors/styles or an RGB8/24 string pattern that is expected to come in the one of the case-insensitive patterns listed below. Otherwise the function returns an empty string of type SgrAttr and errMap.

RGB 8  : rgb8=[fg|bg]:[0-255]
RGB 24 : rgb24=[fg|bg]:[0-255]:[0-255]:[0-255]
Example
package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	attr, _ := termcols.MapColor("bluefg")
	fmt.Printf("%sColorized text!%s", attr, termcols.Reset)
}
Output:

�[34mColorized text!�[0m

func MapColors

func MapColors(ss []string) ([]SgrAttr, error)

MapColors attempts to interpret string elements of the ss slice as a set of predefined colors/styles or an RGB8/24 string pattern that is expected to come in one of the case-insensitive patterns listed below. Otherwise the function returns an empty slice and errMap.

RGB 8  : rgb8=[fg|bg]:[0-255]
RGB 24 : rgb24=[fg|bg]:[0-255]:[0-255]:[0-255]
Example
package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	attrs, _ := termcols.MapColors([]string{"bluefg", "yellowbg", "strike"})
	fmt.Printf("%s%s%sColorized text!%s", attrs[0], attrs[1], attrs[2], termcols.Reset)
}
Output:

�[34m�[43m�[9mColorized text!�[0m

func Rgb24

func Rgb24(l Layer, r, g, b uint8) SgrAttr

Rgb24 returns the set foreground/background 24-bit color control sequence. It accepts the target layer l parameter that can either be set to foreground or background. The next three r, g, b parameters correspond to a 24-bit color sequence split into three 8-bit sets. RGB parameters should be in the range [0, 255].

Example
package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	attr := termcols.Rgb24(termcols.BG, 221, 42, 89)
	fmt.Printf("%sColorized text!%s", attr, termcols.Reset)
}
Output:

�[48;2;221;42;89mColorized text!�[0m

func Rgb8

func Rgb8(l Layer, c uint8) SgrAttr

Rgb8 returns the set foreground/background 8-bit color control sequence. It accepts the target layer l parameter that can either be set to foreground or background. The c parameter stands for the color. It corresponds to one of the colors from a 256-color lookup table, hence the parameter should be in the range [0, 255].

Example
package main

import (
	"fmt"

	"github.com/mdm-code/termcols"
)

func main() {
	attr := termcols.Rgb8(termcols.FG, 12)
	fmt.Printf("%sColorized text!%s", attr, termcols.Reset)
}
Output:

�[38;5;12mColorized text!�[0m

Directories

Path Synopsis
cmd
tcols
tcols - add color to text on the terminal
tcols - add color to text on the terminal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳