Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Provide faster version of Formatter.Format that allows for skipping expensive recalculations of CSS #937

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions formatters/html/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,16 +217,29 @@ func (f *Formatter) Format(w io.Writer, style *chroma.Style, iterator chroma.Ite
return f.writeHTML(w, style, iterator.Tokens())
}

var styleCSSCache = make(map[*chroma.Style]map[chroma.TokenType]string)
var styleCSSCacheLock sync.RWMutex // Read/write lock to allow thread-safe concurrent reads.

// We deliberately don't use html/template here because it is two orders of magnitude slower (benchmarked).
//
// OTOH we need to be super careful about correct escaping...
func (f *Formatter) writeHTML(w io.Writer, style *chroma.Style, tokens []chroma.Token) (err error) { // nolint: gocyclo
css := f.styleToCSS(style)
if !f.Classes {
for t, style := range css {
css[t] = compressStyle(style)
// Create a compressed CSS map for the given style and cache it.
styleCSSCacheLock.RLock()
css := styleCSSCache[style]
styleCSSCacheLock.RUnlock()
if css == nil {
styleCSSCacheLock.Lock()
defer styleCSSCacheLock.Unlock()
css = f.styleToCSS(style)
if !f.Classes {
for t, style := range css {
css[t] = compressStyle(style)
}
}
styleCSSCache[style] = css
}

if f.standalone {
fmt.Fprint(w, "<html>\n")
if f.Classes {
Expand Down