Support format strings in style elements

This commit is contained in:
Christian Muehlhaeuser
2019-12-07 09:27:12 +01:00
parent fd138a00bd
commit 72978312ce
2 changed files with 31 additions and 1 deletions
+26 -1
View File
@@ -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
}
+5
View File
@@ -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
}