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