Last active
July 10, 2020 00:10
-
-
Save ef2k/66c500032067d6daa3177da14d715c7d to your computer and use it in GitHub Desktop.
Chroma renderer for Blackfriday
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package build | |
import ( | |
"io" | |
"github.com/alecthomas/chroma" | |
"github.com/alecthomas/chroma/formatters/html" | |
"github.com/alecthomas/chroma/lexers" | |
"github.com/alecthomas/chroma/styles" | |
"github.com/russross/blackfriday" | |
) | |
func NewChromaRenderer(theme string) *ChromaRenderer { | |
return &ChromaRenderer{ | |
html: blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{}), | |
theme: theme, | |
} | |
} | |
type ChromaRenderer struct { | |
html *blackfriday.HTMLRenderer | |
theme string | |
} | |
func (r *ChromaRenderer) RenderNode(w io.Writer, node *blackfriday.Node, | |
entering bool) blackfriday.WalkStatus { | |
switch node.Type { | |
case blackfriday.CodeBlock: | |
var lexer chroma.Lexer | |
lang := string(node.CodeBlockData.Info) | |
if lang != "" { | |
lexer = lexers.Get(lang) | |
} else { | |
lexer = lexers.Analyse(string(node.Literal)) | |
} | |
if lexer == nil { | |
lexer = lexers.Fallback | |
} | |
style := styles.Get(r.theme) | |
if style == nil { | |
style = styles.Fallback | |
} | |
iterator, err := lexer.Tokenise(nil, string(node.Literal)) | |
if err != nil { | |
panic(err) | |
} | |
formatter := html.New() | |
err = formatter.Format(w, style, iterator) | |
if err != nil { | |
panic(err) | |
} | |
return blackfriday.GoToNext | |
} | |
return r.html.RenderNode(w, node, entering) | |
} | |
func (r *ChromaRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {} | |
func (r *ChromaRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment