Replies: 2 comments
-
i was trying to do something similar. i'm rendering markdown for a git web frontend and i wanted to make some modifications. this code works for me: type rewriter struct {
Repo string
Ref string
}
func (t *rewriter) Transform(doc *ast.Document, reader text.Reader, pctx parser.Context) {
ast.Walk(doc, func(node ast.Node, enter bool) (ast.WalkStatus, error) {
if !enter {
return ast.WalkContinue, nil
}
kind := node.Kind().String()
switch kind {
case "Image":
// Rewrite relative image source to point to raw file within the repo
img, _ := node.(*ast.Image)
dest := string(img.Destination)
if !strings.HasPrefix(dest, "http") && !strings.HasPrefix(dest, "/") {
img.Destination = []byte("/"+t.Repo+"/raw/"+t.Ref+"/"+dest)
}
case "TableHeader":
// Remove empty table headers
text := node.Text([]byte{})
if len(text) == 0 {
node.Parent().RemoveChild(node.Parent(), node)
}
}
return ast.WalkContinue, nil
})
} i am loading the it also works regardless of the case statement order. i'm over a year late but i hope this helps someone! edit: |
Beta Was this translation helpful? Give feedback.
-
This is because the walk function in goldmark is too simplistic:
If you remove My workaround in gohugoio/hugo-goldmark-extensions#6 is to anchor the walk on the parent of the node you want to remove, and walk the children like this: for c := n.FirstChild(); c != nil; {
// Have to eagerly fetch this because `c` may be removed from the tree,
// destroying its link to the next sibling.
next := c.NextSibling()
if c.Kind() == ast.KindParagraph {
...
n.RemoveChild(n, c)
}
c = next
} |
Beta Was this translation helpful? Give feedback.
-
I've been using
ast.Walk()
to comb through a parsed markdown document and extract (and in cases relevant to my issue, remove) nodes of certain types under certain conditions.Here's a sample of the sort of thing I'm trying to do:
It might be important to note that I'm using a type switch over
child.Kind()
in this sample because of additional processing involved with specific node types in my actual code (e.g.child.Destination
for images).It seems like the walker coming across a heading before an image comes up results in only the heading being walked through, but the other way around results in correct output.
I kind of assume it's some anomaly I've managed to overlook with my half-awake programmer tunnel-vision, but I am interested if anyone has any advice, solutions or can otherwise comment on this before I get ahead of myself too much.
Beta Was this translation helpful? Give feedback.
All reactions