1
0
mirror of https://github.com/alecthomas/chroma.git synced 2025-04-25 12:14:41 +02:00

Avoid adding an HTML prefix to empty class names.

This makes the raw markup a bit cleaner when there's lots of `Text`
tokens.
This commit is contained in:
John Millikin 2018-02-24 13:15:48 -08:00 committed by Alec Thomas
parent d7ee3c10b0
commit aaa96c6984
2 changed files with 18 additions and 8 deletions
formatters/html

@ -241,13 +241,18 @@ func (f *Formatter) shouldHighlight(highlightIndex, line int) (bool, bool) {
func (f *Formatter) class(t chroma.TokenType) string { func (f *Formatter) class(t chroma.TokenType) string {
for t != 0 { for t != 0 {
cls, ok := chroma.StandardTypes[t] if cls, ok := chroma.StandardTypes[t]; ok {
if ok { if cls != "" {
return f.prefix + cls return f.prefix + cls
}
return ""
} }
t = t.Parent() t = t.Parent()
} }
return f.prefix + chroma.StandardTypes[t] if cls := chroma.StandardTypes[t]; cls != "" {
return f.prefix + cls
}
return ""
} }
func (f *Formatter) styleAttr(styles map[chroma.TokenType]string, tt chroma.TokenType) string { func (f *Formatter) styleAttr(styles map[chroma.TokenType]string, tt chroma.TokenType) string {

@ -79,15 +79,20 @@ func TestFormatterStyleToCSS(t *testing.T) {
func TestClassPrefix(t *testing.T) { func TestClassPrefix(t *testing.T) {
wantPrefix := "some-prefix-" wantPrefix := "some-prefix-"
f := New(WithClasses(), ClassPrefix(wantPrefix)) withPrefix := New(WithClasses(), ClassPrefix(wantPrefix))
noPrefix := New(WithClasses())
for st := range chroma.StandardTypes { for st := range chroma.StandardTypes {
if got := f.class(st); !strings.HasPrefix(got, wantPrefix) { if noPrefix.class(st) == "" {
t.Errorf("f.class(%v): %q should have a class prefix", st, got) if got := withPrefix.class(st); got != "" {
t.Errorf("Formatter.class(%v): prefix shouldn't be added to empty classes")
}
} else if got := withPrefix.class(st); !strings.HasPrefix(got, wantPrefix) {
t.Errorf("Formatter.class(%v): %q should have a class prefix", st, got)
} }
} }
var styleBuf bytes.Buffer var styleBuf bytes.Buffer
f.WriteCSS(&styleBuf, styles.Fallback) withPrefix.WriteCSS(&styleBuf, styles.Fallback)
if !strings.Contains(styleBuf.String(), ".some-prefix-chroma ") { if !strings.Contains(styleBuf.String(), ".some-prefix-chroma ") {
t.Error("Stylesheets should have a class prefix") t.Error("Stylesheets should have a class prefix")
} }