ANSI Escape Codes colors and print length

I have a string with ansi escape codes in it to print some things in color as well as some runes. I already know to convert the string to a slice of runes to see how many codepoints there are (and give me the print length of the string in characters) but Now I need to know how long it is without the escape character to give me the true print length.

I thought I was close when I found ansi package - github.com/jcorbin/anansi/ansi - Go Packages but I do not see the answer to my issue.

Any help would be appreciated.

If the only ansi escape sequences in the string are for SGRs, then it can be quite simple. Such sequences start with β€œESC[” and end with β€œm”.

So this would be a crude way to count the non-escape runes.

package main

import "fmt"

func main() {
	escaped := "\x1b[1;31mred\x1b[0m\x1b[1;32mgreen\x1b[0m"

	withinEscapeSequence := false
	runeCount := 0
	for _, r := range escaped {
		if withinEscapeSequence {
			if r == 'm' {
				withinEscapeSequence = false
			}
		} else {
			if r == '\x1b' {
				withinEscapeSequence = true
			} else {
				runeCount++
			}
		}
	}

	fmt.Println(runeCount)
}

playground

2 Likes