1// based on HUGO markup/goldmark/images/transform.go -- Pet
 2
 3package goldmark_extensions
 4
 5/*
 6package images
 7
 8import (
 9    "github.com/yuin/goldmark"
10    "github.com/yuin/goldmark/ast"
11    "github.com/yuin/goldmark/parser"
12    "github.com/yuin/goldmark/text"
13    "github.com/yuin/goldmark/util"
14)
15
16type (
17    imagesExtension struct {
18        wrapStandAloneImageWithinParagraph bool
19    }
20)
21
22const (
23    // Used to signal to the rendering step that an image is used in a block context.
24    // Dont's change this; the prefix must match the internalAttrPrefix in the root goldmark package.
25    AttrIsBlock = "_h__isBlock"
26    AttrOrdinal = "_h__ordinal"
27)
28
29func New(wrapStandAloneImageWithinParagraph bool) goldmark.Extender {
30    return &imagesExtension{wrapStandAloneImageWithinParagraph: wrapStandAloneImageWithinParagraph}
31}
32
33func (e *imagesExtension) Extend(m goldmark.Markdown) {
34    m.Parser().AddOptions(
35        parser.WithASTTransformers(
36            util.Prioritized(&Transformer{wrapStandAloneImageWithinParagraph: e.wrapStandAloneImageWithinParagraph}, 300),
37        ),
38    )
39}
40
41type Transformer struct {
42    wrapStandAloneImageWithinParagraph bool
43}
44
45// Transform transforms the provided Markdown AST.
46func (t *Transformer) Transform(doc *ast.Document, reader text.Reader, pctx parser.Context) {
47    var ordinal int
48    ast.Walk(doc, func(node ast.Node, enter bool) (ast.WalkStatus, error) {
49        if !enter {
50            return ast.WalkContinue, nil
51        }
52
53        if n, ok := node.(*ast.Image); ok {
54            parent := n.Parent()
55            n.SetAttributeString(AttrOrdinal, ordinal)
56            ordinal++
57
58            if !t.wrapStandAloneImageWithinParagraph {
59                isBlock := parent.ChildCount() == 1
60                if isBlock {
61                    n.SetAttributeString(AttrIsBlock, true)
62                }
63
64                if isBlock && parent.Kind() == ast.KindParagraph {
65                    for _, attr := range parent.Attributes() {
66                        // Transfer any attribute set down to the image.
67                        // Image elements does not support attributes on its own,
68                        // so it's safe to just set without checking first.
69                        n.SetAttribute(attr.Name, attr.Value)
70                    }
71                    grandParent := parent.Parent()
72                    grandParent.ReplaceChild(grandParent, parent, n)
73                }
74            }
75
76        }
77
78        return ast.WalkContinue, nil
79    })
80}
81*/