forked from gomarkdown/markdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodify_ast.go
63 lines (49 loc) · 1.49 KB
/
modify_ast.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
// example for https://blog.kowalczyk.info/article/cxn3/advanced-markdown-processing-in-go.html
import (
"fmt"
"github.com/verloop/markdown"
"github.com/verloop/markdown/ast"
"github.com/verloop/markdown/html"
"github.com/verloop/markdown/parser"
"strings"
)
func modifyAst(doc ast.Node) ast.Node {
ast.WalkFunc(doc, func(node ast.Node, entering bool) ast.WalkStatus {
if img, ok := node.(*ast.Image); ok && entering {
attr := img.Attribute
if attr == nil {
attr = &ast.Attribute{}
}
// TODO: might be duplicate
attr.Classes = append(attr.Classes, []byte("blog-img"))
img.Attribute = attr
}
if link, ok := node.(*ast.Link); ok && entering {
isExternalURI := func(uri string) bool {
return (strings.HasPrefix(uri, "https://") || strings.HasPrefix(uri, "http://")) && !strings.Contains(uri, "blog.kowalczyk.info")
}
if isExternalURI(string(link.Destination)) {
link.AdditionalAttributes = append(link.AdditionalAttributes, `target="_blank"`)
}
}
return ast.GoToNext
})
return doc
}
var mds = `[link](http://example.com)`
func modifyAstExample() {
md := []byte(mds)
extensions := parser.CommonExtensions
p := parser.NewWithExtensions(extensions)
doc := p.Parse(md)
doc = modifyAst(doc)
htmlFlags := html.CommonFlags
opts := html.RendererOptions{Flags: htmlFlags}
renderer := html.NewRenderer(opts)
html := markdown.Render(doc, renderer)
fmt.Printf("-- Markdown:\n%s\n\n--- HTML:\n%s\n", md, html)
}
func main() {
modifyAstExample()
}