Skip to content

Instantly share code, notes, and snippets.

@rtfb
Created July 28, 2017 19:36
Show Gist options
  • Save rtfb/f0ad5013f4c3068b592da205b6542db9 to your computer and use it in GitHub Desktop.
Save rtfb/f0ad5013f4c3068b592da205b6542db9 to your computer and use it in GitHub Desktop.
A complete example of a custom Blackfriday v2 renderer with pygmentizing CodeBlock handler
package main
import (
"fmt"
"io"
"os/exec"
bf "gopkg.in/russross/blackfriday.v2"
)
var md = "This is some sample code.\n\n```\n" +
`func main() {
fmt.Println("Hi")
}
` + "```"
func renderWithPygments(w io.Writer, text []byte) error {
cmd := exec.Command("pygmentize", "-l", "go", "-f", "html")
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
defer stdout.Close()
go func() {
defer stdin.Close()
stdin.Write(text)
}()
if err := cmd.Start(); err != nil {
return err
}
io.Copy(w, stdout)
return cmd.Wait()
}
type pygmentedRenderer struct {
defR *bf.HTMLRenderer
}
func (r *pygmentedRenderer) RenderNode(w io.Writer, node *bf.Node, entering bool) bf.WalkStatus {
switch node.Type {
case bf.CodeBlock:
if err := renderWithPygments(w, node.Literal); err != nil {
return r.defR.RenderNode(w, node, entering)
}
return bf.SkipChildren
default:
return r.defR.RenderNode(w, node, entering)
}
}
func (r *pygmentedRenderer) RenderHeader(w io.Writer, ast *bf.Node) {
r.defR.RenderHeader(w, ast)
}
func (r *pygmentedRenderer) RenderFooter(w io.Writer, ast *bf.Node) {
r.defR.RenderFooter(w, ast)
}
func main() {
r := pygmentedRenderer{
defR: bf.NewHTMLRenderer(bf.HTMLRendererParameters{
Flags: bf.CommonHTMLFlags,
}),
}
html := bf.Run([]byte(md), bf.WithRenderer(&r))
fmt.Println(string(html))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment