Concatenation of strings with ANSI escape codes breaks styling in Golang

Viewed 53

I have a string that may contain substrings closed in square brackets. I need to make whole string italic and additionally make substring closed in brackets blue and underlined. Here i'm using jwalton/gchalk but i also tried using fatih/color

package main

import (
    "fmt"
    "strings"

    "github.com/jwalton/gchalk"
)

var (
    ExampleStyle    = gchalk.StyleMust("italic")
    RefExampleStyle = gchalk.StyleMust("italic", "blue", "underline")
)

func StylizeExample(in string) string {
    if !strings.ContainsAny(in, "[]") {
        return ExampleStyle(in)
    }
    text := in
    out := ""
    for {
        token, rest, fnd := strings.Cut(text, "[")
        if token != "" {
            out += ExampleStyle(token)
        }
        if !fnd { break }
        token, rest, fnd = strings.Cut(rest, "]")
        if token != "" {
            out += RefExampleStyle(token)
        }
        if !fnd { break }
        text = rest
    }
    return out
}
func main() {
    text := "[Lorem] ipsum [dolor] sit amet, consectetur adipiscing elit. [Aenean] ut convallis velit. Aenean vitae ante."
    fmt.Println(StylizeExample(text))
}

Running this code i get this output.

But if instead of concatenating strings i return slice of string and print them one-by-one, they are correct.4 And joining them together breaks it again.

My current theory is that go's strings are not usual array of cha..."runes" but somehow encoded under a hood, and this encoding breaks ANSI codes.

Does anybody know any way to deal with this?

Update: apparently it's not about string encoding. If i make ExampleStyle = gchalk.StyleMust("italic", "bold") it's works fine. Weird.

0 Answers
Related