README

Build Status GoDoc Support me on Patreon Buy me a Coffee Support me on LiberaPay

ansigo

ANSI escape-code library for Golang.

Pretty colors

For the colors and attributes, see the project page.

Usage

package main

import (
	"fmt"

	ansi "github.com/makyo/ansigo"
)

func main() {
	// You can get attributes...
	bold, err := ansi.Attributes.Find("bold")
	if err != nil {
		panic(err)
	}
	fmt.Println(bold.Apply("Some bold text"))
	fmt.Print("\n")

	// Or colors from three different spaces...
	red1, err := ansi.Colors8.Find("red")
	if err != nil {
		panic(err)
	}
	red2, err := ansi.Colors256.Find("DarkRed")
	if err != nil {
		panic(err)
	}
	red3, err := ansi.Colors24bit.Find("#661126")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s %s %s\n", red1.FG("Three"), red2.BG("different"), red3.BG(red1.FG("reds")))
	fmt.Print("\n")

	// Or you can let ansigo figure out the hard work.
	s, err := ansi.ApplyOne("underline", "Some text.")
	if err != nil {
		panic(err)
	}
	fmt.Println(s)
	fmt.Print("\n")

	// But all this error checking is tiresome, and maybe you don't want to
	// have to keep nesting lookups.
	fmt.Println(ansi.MaybeApply("bold+brightyellow+rgb(145, 20, 31):bg+blink", "Warning!"))
}

Documentation

Overview

    Package ansigo provides control over ANSI escape codes for terminal apps.

    There are a few entry points to the library, but most commonly, one will just use `Apply` or `MaybeApply`, which accept a spec string and a string to format. `Apply` returns an error if any bit of the spec string failed to match and bails as soon as a failure occurs, while `MaybeApply` simply returns the string with all successful formatting applied (after all, it's just text, it'll still be text at the end).

    The spec string is simply a list of formatting steps to take separated by +. For instance, one could have bold green text with `bold+green`. Additionally, colors can be specified as background rather than foreground colors by appending `:bg` so we could have the previous on a blue background with `bold+green+blue:bg`.

    ansigo supports all SGR codes from the ANSI specification. This includes attributes such as bold and underline, as well as three different color spaces: 3/4-bit[0] (`Colors8`), 8-bit (`Colors256`), and 24-bit true-color (`Colors24bit`).

    For the list of which attributes and colors are available, as well as to see which your terminal supports,

    go run _examples/capability_check.go
    

    `Attributes` and all three color spaces above, as implementers of `Collection`, implement a `Find` method which returns a `Formatter`, if one is found, and an error if one is not. For `Attributes` and `Colors8`, the search term is just a name ("bold", "green", etc), but `Colors256` and `Colors24bit`, you have more leeway. For the former, you can search by color name (though note that there are some duplicate names in there, which will lead to you getting the first match back), color ID[1], and the color's CSS-style hex code (e.g: "#ff0000"), rgb function (e.g: "rgb(255, 0, 0)"), and hsl function (e.g: "hsl(0,100%,50%)"). However, all of those are strictly specified. If you search `Colors256` for, say, "#123512", you won't find it, despite that being a valid hex code. For that, use `Colors24bit`, which will succeed for any valid CSS hex/rgb/hsl function that uses whole numbers.

    That's a lot of choices, though, so it's usually better to just use `(Maybe)Apply` :)

    For a list of attributes and colors, see https://ansigo.projects.makyo.io .

    [0]: Despite the name, `Colors8` contains 16 colors, the 8 original colors, and their "bright" variants: "green" + "brightgreen", etc.

    [1]: Which the author was personally quite fascinated with:

      0-  7:  standard colors (as in ESC [ 30–37 m)
      8- 15:  high intensity colors (as in ESC [ 90–97 m)
     16-231:  6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
    232-255:  grayscale from black to white in 24 steps
    

    Index

    Constants

    View Source
    const (
    	FGEnd string = "\x1b[39m"
    	BGEnd        = "\x1b[49m"
    )
    View Source
    const Reset string = "\x1b[0m"

      Reset is the ANSI code to reset all attributes and colors of a string.

      Variables

      View Source
      var (
      	Bold                    attribute = attribute{/* contains filtered or unexported fields */}
      	Faint                             = attribute{/* contains filtered or unexported fields */}
      	Italic                            = attribute{/* contains filtered or unexported fields */}
      	Underline                         = attribute{/* contains filtered or unexported fields */}
      	Blink                             = attribute{/* contains filtered or unexported fields */}
      	Flash                             = attribute{/* contains filtered or unexported fields */}
      	Reverse                           = attribute{/* contains filtered or unexported fields */}
      	Conceal                           = attribute{/* contains filtered or unexported fields */}
      	CrossedOut                        = attribute{/* contains filtered or unexported fields */}
      	AltFont1                          = attribute{/* contains filtered or unexported fields */}
      	AltFont2                          = attribute{/* contains filtered or unexported fields */}
      	AltFont3                          = attribute{/* contains filtered or unexported fields */}
      	AltFont4                          = attribute{/* contains filtered or unexported fields */}
      	AltFont5                          = attribute{/* contains filtered or unexported fields */}
      	AltFont6                          = attribute{/* contains filtered or unexported fields */}
      	AltFont7                          = attribute{/* contains filtered or unexported fields */}
      	AltFont8                          = attribute{/* contains filtered or unexported fields */}
      	AltFont9                          = attribute{/* contains filtered or unexported fields */}
      	Fraktur                           = attribute{/* contains filtered or unexported fields */}
      	DoubleUnderline                   = attribute{/* contains filtered or unexported fields */}
      	Framed                            = attribute{/* contains filtered or unexported fields */}
      	Encircled                         = attribute{/* contains filtered or unexported fields */}
      	Overlined                         = attribute{/* contains filtered or unexported fields */}
      	IdeogramUnderline                 = attribute{/* contains filtered or unexported fields */}
      	IdeogramDoubleUnderline           = attribute{/* contains filtered or unexported fields */}
      	IdeogramOverline                  = attribute{/* contains filtered or unexported fields */}
      	IdeogramDoubleOverline            = attribute{/* contains filtered or unexported fields */}
      	IdeogramStressMarking             = attribute{/* contains filtered or unexported fields */}
      )
      View Source
      var (
      	AllCaps other = func(s string) string {
      		return strings.ToUpper(s)
      	}
      	TitleCase other = func(s string) string {
      		var builder strings.Builder
      		capNext := true
      		for _, r := range s {
      			chr := string(r)
      			if wsRE.MatchString(chr) {
      				capNext = true
      			} else if capNext {
      				capNext = false
      				chr = strings.ToUpper(chr)
      			}
      			builder.WriteString(chr)
      		}
      		return builder.String()
      	}
      	CamelCase other = func(s string) string {
      		var builder strings.Builder
      		capNext := false
      		started := false
      		for _, r := range s {
      			chr := string(r)
      			if !wsRE.MatchString(chr) {
      				started = true
      				if capNext {
      					capNext = false
      					chr = strings.ToUpper(chr)
      				}
      			} else {
      				if started {
      					capNext = true
      				}
      				continue
      			}
      			builder.WriteString(chr)
      		}
      		return builder.String()
      	}
      	UpperCamelCase other = func(s string) string {
      		var builder strings.Builder
      		capNext := true
      		for _, r := range s {
      			chr := string(r)
      			if wsRE.MatchString(chr) {
      				capNext = true
      				continue
      			} else if capNext {
      				capNext = false
      				chr = strings.ToUpper(chr)
      			}
      			builder.WriteString(chr)
      		}
      		return builder.String()
      	}
      	SnakeCase other = func(s string) string {
      		return underRE.ReplaceAllString(wsRE.ReplaceAllString(s, "_"), "_")
      	}
      	KebabCase other = func(s string) string {
      		return dashRE.ReplaceAllString(wsRE.ReplaceAllString(s, "-"), "-")
      	}
      )
      View Source
      var Attributes attributes = map[string]attribute{
      	"bold":                    Bold,
      	"faint":                   Faint,
      	"italic":                  Italic,
      	"underline":               Underline,
      	"blink":                   Blink,
      	"flash":                   Flash,
      	"reverse":                 Reverse,
      	"conceal":                 Conceal,
      	"crossedout":              CrossedOut,
      	"altfont1":                AltFont1,
      	"altfont2":                AltFont2,
      	"altfont3":                AltFont3,
      	"altfont4":                AltFont4,
      	"altfont5":                AltFont5,
      	"altfont6":                AltFont6,
      	"altfont7":                AltFont7,
      	"altfont8":                AltFont8,
      	"altfont9":                AltFont9,
      	"fraktur":                 Fraktur,
      	"doubleunderline":         DoubleUnderline,
      	"framed":                  Framed,
      	"encircled":               Encircled,
      	"overlined":               Overlined,
      	"ideogramunderline":       IdeogramUnderline,
      	"ideogramdoubleunderline": IdeogramDoubleUnderline,
      	"ideogramoverline":        IdeogramOverline,
      	"ideogramdoubleoverline":  IdeogramDoubleOverline,
      	"ideogramstressmarking":   IdeogramStressMarking,
      }

        Attributes is the list of available attributes.

        View Source
        var CapabilityCheck = capabilityCheck()

          CapabilityCheck is a map of all ANSI codes that gotui knows about. It is intended to be used as a reference to see what capabilities one's terminal supports.

          View Source
          var CodeNotFound error = errors.New("ANSI code not found")

            CodeNotFound is returned when an ANSI code is requested which does not exist.

            View Source
            var Colors24bit colors24bit
            View Source
            var Colors256 colors256 = []color256{}/* 256 elements not displayed */
            
            View Source
            var Colors8 colors8 = map[string]uint8{
            	"black":   0,
            	"red":     1,
            	"green":   2,
            	"yellow":  3,
            	"blue":    4,
            	"magenta": 5,
            	"cyan":    6,
            	"white":   7,
            
            	"brightblack":   60,
            	"brightred":     61,
            	"brightgreen":   62,
            	"brightyellow":  63,
            	"brightblue":    64,
            	"brightmagenta": 65,
            	"brightcyan":    66,
            	"brightwhite":   67,
            }
            View Source
            var (
            	// InvalidColorSpec is returned when calling Find with an invalid string.
            	InvalidColorSpec = errors.New("invalid color spec")
            )
            View Source
            var Others others = map[string]other{
            	"allcaps":        AllCaps,
            	"titlecase":      TitleCase,
            	"camelcase":      CamelCase,
            	"uppercamelcase": UpperCamelCase,
            	"snakecase":      SnakeCase,
            	"kebabcase":      KebabCase,
            }

            Functions

            func ANSIAtIndex

            func ANSIAtIndex(s string, index int) []string

              ANSIAtIndex accepts a string and an index within that string and returns a list of ANSI codes which are currently active at that string. That is, if a character at that index is green and bold with a blue background, it will return the color codes for green foreground, blue background, and bold, regardless of any additional ANSIfication that takes place before or after that index.

              func Apply

              func Apply(specs, s string) (string, error)

                Apply attempts to apply all of the codes requested to the string, separated by +. If any of them fail, it stops and returns an error.

                func ApplyOne

                func ApplyOne(spec, s string) (string, error)

                  ApplyOne applies one code to a string. If it fails, it returns an error.

                  func ApplyOneWithReset

                  func ApplyOneWithReset(spec, s string) (string, error)

                    ApplyOneWithReset applies one code to a string. If it fails, it returns an error.

                    func ApplyWithReset

                    func ApplyWithReset(specs, s string) (string, error)

                      ApplyWithReset attempts to apply all of the codes requested to the string, separated by +. If any of them fail, it stops and returns an error.

                      func MaybeApply

                      func MaybeApply(specs, s string) string

                        MaybeApply attempts to apply all of the codes requested to the string, separated by +. If any of them fail, it ignores the failure and continues on.

                        func MaybeApplyOne

                        func MaybeApplyOne(spec, s string) string

                          MaybeApplyOne attempts to apply a code; if it fails, it just returns the string.

                          func MaybeApplyOneWithReset

                          func MaybeApplyOneWithReset(spec, s string) string

                            MaybeApplyOneWithReset attempts to apply a code; if it fails, it just returns the string.

                            func MaybeApplyWithReset

                            func MaybeApplyWithReset(specs, s string) string

                              MaybeApplyWithReset attempts to apply all of the codes requested to the string, separated by +. If any of them fail, it ignores the failure and continues on.

                              Types

                              type Attribute

                              type Attribute interface {
                              	Start() string
                              	End() string
                              	Apply(string) string
                              	ApplyWithReset(string) string
                              }

                                Attribute describes a string-modifying code that's not a color.

                                type Collection

                                type Collection interface {
                                	Find(string) (Formatter, error)
                                }

                                  Collection represents something which can be used to find a formatter.

                                  type Color

                                  type Color interface {
                                  	FGStart() string
                                  	BGStart() string
                                  	FG(string) string
                                  	BG(string) string
                                  	Apply(string, string) string
                                  	ApplyWithReset(string, string) string
                                  }

                                    Color describes a color that a string of runes might have. This can be applied to both foreground and background.

                                    type Formatter

                                    type Formatter interface {
                                    	Apply(string) string
                                    	ApplyWithReset(string) string
                                    }

                                      Formatter represents something which can apply formatting to a string.

                                      type Other

                                      type Other interface {
                                      	Apply(string) string
                                      }

                                      Directories

                                      Path Synopsis