Skip to content

Commit

Permalink
Add CSS style inheritance to WithCustomCSS option
Browse files Browse the repository at this point in the history
  • Loading branch information
CIAvash authored and alecthomas committed May 18, 2022
1 parent 7d77940 commit dea6a13
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
30 changes: 27 additions & 3 deletions formatters/html/html.go
Expand Up @@ -443,13 +443,37 @@ func (f *Formatter) styleToCSS(style *chroma.Style) map[chroma.TokenType]string
if t != chroma.Background {
entry = entry.Sub(bg)
}
if !f.allClasses && entry.IsZero() && f.customCSS[t] == `` {

// Inherit from custom CSS provided by user
tokenCategory := t.Category()
tokenSubCategory := t.SubCategory()
if t != tokenCategory {
if css, ok := f.customCSS[tokenCategory]; ok {
classes[t] = css
}
}
if tokenCategory != tokenSubCategory {
if css, ok := f.customCSS[tokenSubCategory]; ok {
classes[t] += css
}
}
// Add custom CSS provided by user
if css, ok := f.customCSS[t]; ok {
classes[t] += css
}

if !f.allClasses && entry.IsZero() && classes[t] == `` {
continue
}
classes[t] = f.customCSS[t] + StyleEntryToCSS(entry)

styleEntryCSS := StyleEntryToCSS(entry)
if styleEntryCSS != `` {
styleEntryCSS += `;`
}
classes[t] = styleEntryCSS + classes[t]
}
classes[chroma.Background] += f.tabWidthStyle()
classes[chroma.PreWrapper] += classes[chroma.Background] + `;`
classes[chroma.PreWrapper] += classes[chroma.Background]
// Make PreWrapper a grid to show highlight style with full width.
if len(f.highlightRanges) > 0 && f.customCSS[chroma.PreWrapper] == `` {
classes[chroma.PreWrapper] += `display: grid;`
Expand Down
15 changes: 15 additions & 0 deletions formatters/html/html_test.go
Expand Up @@ -120,6 +120,21 @@ func TestWithCustomCSS(t *testing.T) {
assert.Regexp(t, `<span style="display:flex;display:inline;"><span><span style=".*">echo</span> FOO</span></span>`, buf.String())
}

func TestWithCustomCSSStyleInheritance(t *testing.T) {
f := New(WithClasses(false), WithCustomCSS(map[chroma.TokenType]string{
chroma.String: `background: blue;`,
chroma.LiteralStringDouble: `color: tomato;`,
}))
it, err := lexers.Get("bash").Tokenise(nil, `echo "FOO"`)
assert.NoError(t, err)

var buf bytes.Buffer
err = f.Format(&buf, styles.Fallback, it)
assert.NoError(t, err)

assert.Regexp(t, ` <span style=".*;background:blue;color:tomato;">&#34;FOO&#34;</span>`, buf.String())
}

func TestWrapLongLines(t *testing.T) {
f := New(WithClasses(false), WrapLongLines(true))
it, err := lexers.Get("go").Tokenise(nil, "package main\nfunc main()\n{\nprintln(\"hello world\")\n}\n")
Expand Down

0 comments on commit dea6a13

Please sign in to comment.