-
-
Save mattyoho/b8abd48b5d65a30a0d80544ff6c6c2fd to your computer and use it in GitHub Desktop.
A complete example of a custom Blackfriday v2 renderer with pygmentizing CodeBlock handler
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 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