Skip to content

leaanthony/go-ansi-parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


A library for parsing ANSI encoded strings

CodeFactor

Go ANSI Parser converts strings with ANSI escape codes into a slice of structs that represent styled text. Features:

  • Can parse ANSI 16, 256 and TrueColor
  • Supports all styles: Regular, Bold, Faint, Italic, Blinking, Inversed, Invisible, Underlined, Strikethrough
  • Provides RGB, Hex, HSL, ANSI ID and Name for parsed colours
  • Truncation - works with emojis and grapheme clusters
  • Length - works with emojis and grapheme clusters
  • Cleanse - removes the ansi escape codes
  • Configurable colour map for customisation
  • 100% Test Coverage

Installation

go get github.com/leaanthony/go-ansi-parser

Usage

Parse

text, err := ansi.Parse("\u001b[1;31;40mHello World\033[0m")

// is the equivalent of...

text := []*ansi.StyledText{
    {
        Label: "Hello World",
        FgCol: &ansi.Col{
            Id:   9,
            Hex:  "#ff0000",
            Rgb:  &ansi.Rgb{ R: 255, G: 0, B: 0 },
            Hsl:  &ansi.Hsl{ H: 0, S: 100, L: 50 },
            Name: "Red",
        },
        BgCol: &ansi.Col{
            Id:   0,
            Hex:  "#000000",
            Rgb:  &ansi.Rgb{0, 0, 0},
            Hsl:  &ansi.Hsl{0, 0, 0},
            Name: "Black",
        },
        Style: 1,
    },
}

Truncating

shorter, err := ansi.Truncate("\u001b[1;31;40mHello\033[0m \u001b[0;30mWorld!\033[0m", 8)

// is the equivalent of...

shorter := "\u001b[1;31;40mHello\033[0m \u001b[0;30mWo\033[0m"

Cleanse

cleaner, err := ansi.Cleanse("\u001b[1;31;40mHello\033[0m \u001b[0;30mWorld!\033[0m")

// is the equivalent of...

cleaner := "Hello World!"

Length

length, err := ansi.Length("\u001b[1;31;40mHello\033[0m \u001b[0;30mWorld!\033[0m")

// is the equivalent of...

length := 12

// Works with grapheme clusters and emoji
length, err := ansi.Length("\u001b[1;31;40m👩🏽‍🔧😎\033[0m") // 2

About

Go Parser for ANSI strings

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Languages