From 72978312ce49469a4115cf83e5c4cbae76c5226b Mon Sep 17 00:00:00 2001 From: Christian Muehlhaeuser Date: Sat, 7 Dec 2019 09:27:12 +0100 Subject: [PATCH] Support format strings in style elements --- baseelement.go | 27 ++++++++++++++++++++++++++- style.go | 5 +++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/baseelement.go b/baseelement.go index 34324a2..0583ce8 100644 --- a/baseelement.go +++ b/baseelement.go @@ -1,11 +1,13 @@ package gold import ( + "bytes" "errors" "fmt" "io" "os" "strconv" + "text/template" "github.com/logrusorgru/aurora" "github.com/lucasb-eyer/go-colorful" @@ -63,6 +65,21 @@ func colorSeq(fg *string, bg *string) (string, error) { return "", errors.New("Invalid color") } +func formatToken(format string, token string) (string, error) { + var b bytes.Buffer + + v := make(map[string]interface{}) + v["text"] = token + + tmpl, err := template.New(format).Parse(format) + if err != nil { + return "", err + } + + err = tmpl.Execute(&b, v) + return b.String(), err +} + func renderText(w io.Writer, rules ElementStyle, s string) { if len(s) == 0 { return @@ -132,6 +149,14 @@ func (e *BaseElement) Render(w io.Writer, node *bf.Node, tr *TermRenderer) error renderText(w, rules, rules.Suffix) }() - renderText(w, rules, e.Token) + s := e.Token + if len(rules.Format) > 0 { + var err error + s, err = formatToken(rules.Format, s) + if err != nil { + return err + } + } + renderText(w, rules, s) return nil } diff --git a/style.go b/style.go index 86b855c..d5dc1bc 100644 --- a/style.go +++ b/style.go @@ -67,6 +67,7 @@ type ElementStyle struct { Theme string `json:"theme"` Prefix string `json:"prefix"` Suffix string `json:"suffix"` + Format string `json:"format"` } func loadStyle(f string) ([]byte, error) { @@ -119,6 +120,7 @@ func cascadeStyle(parent ElementStyle, child ElementStyle, onlyColors bool) Elem s.Blink = parent.Blink s.Prefix = parent.Prefix s.Suffix = parent.Suffix + s.Format = parent.Format } if child.Color != nil { @@ -166,6 +168,9 @@ func cascadeStyle(parent ElementStyle, child ElementStyle, onlyColors bool) Elem if child.Suffix != "" { s.Suffix = child.Suffix } + if child.Format != "" { + s.Format = child.Format + } return s }