From df78bad3b546c788b739441a243aada82ffdafd6 Mon Sep 17 00:00:00 2001 From: Jan De Dobbeleer Date: Thu, 16 Dec 2021 10:57:01 +0100 Subject: [PATCH] feat: expand parent colors --- src/writer_ansi.go | 31 ++++++++++++++++++++++++------- src/writer_ansi_test.go | 2 +- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/writer_ansi.go b/src/writer_ansi.go index 914b6f57..a6dfa848 100644 --- a/src/writer_ansi.go +++ b/src/writer_ansi.go @@ -24,7 +24,7 @@ type AnsiWriter struct { ansi *ansiUtils terminalBackground string Colors *Color - ParentColors *Color + ParentColors []*Color ansiColors AnsiColors } @@ -80,10 +80,13 @@ func (a *AnsiWriter) setColors(background, foreground string) { } func (a *AnsiWriter) setParentColors(background, foreground string) { - a.ParentColors = &Color{ + if a.ParentColors == nil { + a.ParentColors = make([]*Color, 0) + } + a.ParentColors = append([]*Color{{ Background: background, Foreground: foreground, - } + }}, a.ParentColors...) } func (a *AnsiWriter) clearParentColors() { @@ -183,16 +186,30 @@ func (a *AnsiWriter) isKeyword(color string) bool { } func (a *AnsiWriter) expandKeyword(keyword string) string { + resolveParentColor := func(keyword string) string { + for _, color := range a.ParentColors { + if color == nil { + return Transparent + } + switch keyword { + case ParentBackground: + keyword = color.Background + case ParentForeground: + keyword = color.Foreground + default: + return keyword + } + } + return keyword + } resolveKeyword := func(keyword string) string { switch { case keyword == Background && a.Colors != nil: return a.Colors.Background case keyword == Foreground && a.Colors != nil: return a.Colors.Foreground - case keyword == ParentBackground && a.ParentColors != nil: - return a.ParentColors.Background - case keyword == ParentForeground && a.ParentColors != nil: - return a.ParentColors.Foreground + case (keyword == ParentBackground || keyword == ParentForeground) && a.ParentColors != nil: + return resolveParentColor(keyword) default: return Transparent } diff --git a/src/writer_ansi_test.go b/src/writer_ansi_test.go index b97db374..5721225f 100644 --- a/src/writer_ansi_test.go +++ b/src/writer_ansi_test.go @@ -175,7 +175,7 @@ func TestWriteANSIColors(t *testing.T) { ansi.init("pwsh") renderer := &AnsiWriter{ ansi: ansi, - ParentColors: tc.Parent, + ParentColors: []*Color{tc.Parent}, Colors: tc.Colors, terminalBackground: tc.TerminalBackground, ansiColors: &DefaultColors{},