Skip to content

Commit

Permalink
[html formatter] Add option to let users provide custom CSS styles
Browse files Browse the repository at this point in the history
Example: WithCustomCSS(map[chroma.TokenType]string{chroma.Line: `display: inline;`})
  • Loading branch information
CIAvash authored and alecthomas committed May 18, 2022
1 parent 7cc13cf commit 7d77940
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
14 changes: 11 additions & 3 deletions formatters/html/html.go
Expand Up @@ -25,6 +25,13 @@ func WithClasses(b bool) Option { return func(f *Formatter) { f.Classes = b } }
// WithAllClasses disables an optimisation that omits redundant CSS classes.
func WithAllClasses(b bool) Option { return func(f *Formatter) { f.allClasses = b } }

// WithCustomCSS sets user's custom CSS styles.
func WithCustomCSS(css map[chroma.TokenType]string) Option {
return func(f *Formatter) {
f.customCSS = css
}
}

// TabWidth sets the number of characters for a tab. Defaults to 8.
func TabWidth(width int) Option { return func(f *Formatter) { f.tabWidth = width } }

Expand Down Expand Up @@ -160,6 +167,7 @@ type Formatter struct {
prefix string
Classes bool // Exported field to detect when classes are being used
allClasses bool
customCSS map[chroma.TokenType]string
preWrapper PreWrapper
tabWidth int
wrapLongLines bool
Expand Down Expand Up @@ -435,15 +443,15 @@ func (f *Formatter) styleToCSS(style *chroma.Style) map[chroma.TokenType]string
if t != chroma.Background {
entry = entry.Sub(bg)
}
if !f.allClasses && entry.IsZero() {
if !f.allClasses && entry.IsZero() && f.customCSS[t] == `` {
continue
}
classes[t] = StyleEntryToCSS(entry)
classes[t] = f.customCSS[t] + StyleEntryToCSS(entry)
}
classes[chroma.Background] += f.tabWidthStyle()
classes[chroma.PreWrapper] += classes[chroma.Background] + `;`
// Make PreWrapper a grid to show highlight style with full width.
if len(f.highlightRanges) > 0 {
if len(f.highlightRanges) > 0 && f.customCSS[chroma.PreWrapper] == `` {
classes[chroma.PreWrapper] += `display: grid;`
}
// Make PreWrapper wrap long lines.
Expand Down
12 changes: 12 additions & 0 deletions formatters/html/html_test.go
Expand Up @@ -108,6 +108,18 @@ func TestTableLineNumberNewlines(t *testing.T) {
</span>`)
}

func TestWithCustomCSS(t *testing.T) {
f := New(WithClasses(false), WithCustomCSS(map[chroma.TokenType]string{chroma.Line: `display: inline;`}))
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="display:flex;display:inline;"><span><span style=".*">echo</span> FOO</span></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 7d77940

Please sign in to comment.