Last active
September 24, 2017 19:29
-
-
Save kyleconroy/a2741b9e6cf45beb3515d81ee1153985 to your computer and use it in GitHub Desktop.
Syntax highlight fenced code blocks in Markdown
This file contains hidden or 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 main | |
import ( | |
"io" | |
"github.com/alecthomas/chroma/formatters/html" | |
"github.com/alecthomas/chroma/lexers" | |
"github.com/alecthomas/chroma/styles" | |
"github.com/russross/blackfriday" | |
) | |
type Renderer struct { | |
html *blackfriday.HTMLRenderer | |
} | |
func (r *Renderer) RenderHeader(w io.Writer, ast *blackfriday.Node) {} | |
func (r *Renderer) RenderFooter(w io.Writer, ast *blackfriday.Node) {} | |
func (r *Renderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { | |
switch node.Type { | |
case blackfriday.CodeBlock: | |
lexer := lexers.Analyse(string(node.Literal)) | |
if lexer == nil { | |
lexer = lexers.Fallback | |
} | |
style := styles.Get("manni") | |
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) | |
} | |
const markdown = ` | |
package main | |
func main() { | |
fmt.Println("Hello world!") | |
} | |
` | |
func main() { | |
r := Renderer{blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{})} | |
blackfriday.Run([]byte(markdown), blackfriday.WithRenderer(&r)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment