fix(ansi): reset transparent on override end

resolves #4280
This commit is contained in:
Jan De Dobbeleer 2023-09-24 09:16:26 +02:00 committed by Jan De Dobbeleer
parent f2101e668d
commit 2b51623bda
2 changed files with 22 additions and 9 deletions

View file

@ -482,9 +482,6 @@ func (w *Writer) writeColorOverrides(match map[string]string, background string,
}
func (w *Writer) endColorOverride(position int) int {
// pop the last colors from the stack
defer w.current.Pop()
// make sure to reset the colors if needed
position += len([]rune(resetStyle.AnchorEnd)) - 1
@ -493,26 +490,36 @@ func (w *Writer) endColorOverride(position int) int {
return position
}
// reset colors to previous when we have >= 2 in stack
// reset colors to previous when we have more than 1 in stack
// as soon as we have more than 1, we can pop the last one
// and print the previous override as it wasn't ended yet
if w.current.Len() >= 2 {
if w.current.Len() > 1 {
fg := w.current.Foreground()
bg := w.current.Background()
w.current.Pop()
if w.current.Background() != bg {
w.writeEscapedAnsiString(fmt.Sprintf(colorise, w.current.Background()))
previousBg := w.current.Background()
previousFg := w.current.Foreground()
if w.transparent {
w.writeEscapedAnsiString(transparentEnd)
}
if w.current.Foreground() != fg {
w.writeEscapedAnsiString(fmt.Sprintf(colorise, w.current.Foreground()))
if previousBg != bg {
w.writeEscapedAnsiString(fmt.Sprintf(colorise, previousBg))
}
if previousFg != fg {
w.writeEscapedAnsiString(fmt.Sprintf(colorise, previousFg))
}
return position
}
// pop the last colors from the stack
defer w.current.Pop()
// do not reset when colors are identical
if w.current.Background() == w.background && w.current.Foreground() == w.foreground {
return position

View file

@ -200,6 +200,12 @@ func TestWriteANSIColors(t *testing.T) {
Expected: "\x1b[47m\x1b[30mhello, \x1b[31mworld, \x1b[37mrabbit\x1b[31m hello\x1b[0m",
Colors: &Colors{Foreground: "black", Background: "white"},
},
{
Case: "Transparent override",
Input: "home<transparent> / </>code<transparent> / </>src ",
Expected: "\x1b[47m\x1b[30mhome\x1b[0m\x1b[37;49m\x1b[7m / \x1b[27m\x1b[47m\x1b[30mcode\x1b[0m\x1b[37;49m\x1b[7m / \x1b[27m\x1b[47m\x1b[30msrc \x1b[0m",
Colors: &Colors{Foreground: "black", Background: "white"},
},
}
for _, tc := range cases {