Debian Codegraph @

markup/goldmark/internal/extensions/attributes/attributes.go

raw
1 package attributes
2
3 import (
4 "strings"
5
6 "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
7 "github.com/gohugoio/hugo/markup/goldmark/internal/render"
8 "github.com/yuin/goldmark"
9 "github.com/yuin/goldmark/ast"
10 east "github.com/yuin/goldmark/extension/ast"
11 "github.com/yuin/goldmark/parser"
12 "github.com/yuin/goldmark/text"
13 "github.com/yuin/goldmark/util"
14 )
15
16 // This extension is based on/inspired by https://github.com/mdigger/goldmark-attributes
17 // MIT License
18 // Copyright (c) 2019 Dmitry Sedykh
19
20 var (
21 kindAttributesBlock = ast.NewNodeKind("AttributesBlock")
22 attrNameID = []byte("id")
23
24 defaultParser = new(attrParser)
25 )
26
27 func New(cfg goldmark_config.Parser) goldmark.Extender {
28 return &attrExtension{cfg: cfg}
29 }
30
31 type attrExtension struct {
32 cfg goldmark_config.Parser
33 }
34
35 func (a *attrExtension) Extend(m goldmark.Markdown) {
36 if a.cfg.Attribute.Block {
37 m.Parser().AddOptions(
38 parser.WithBlockParsers(
39 util.Prioritized(defaultParser, 100)),
40 )
41 }
42 m.Parser().AddOptions(
43 parser.WithASTTransformers(
44 util.Prioritized(&transformer{cfg: a.cfg}, 100),
45 ),
46 )
47 }
48
49 type attrParser struct{}
50
51 func (a *attrParser) CanAcceptIndentedLine() bool {
52 return false
53 }
54
55 func (a *attrParser) CanInterruptParagraph() bool {
56 return true
57 }
58
59 func (a *attrParser) Close(node ast.Node, reader text.Reader, pc parser.Context) {
60 }
61
62 func (a *attrParser) Continue(node ast.Node, reader text.Reader, pc parser.Context) parser.State {
63 return parser.Close
64 }
65
66 func (a *attrParser) Open(parent ast.Node, reader text.Reader, pc parser.Context) (ast.Node, parser.State) {
67 if attrs, ok := parser.ParseAttributes(reader); ok {
68 // add attributes
69 node := &attributesBlock{
70 BaseBlock: ast.BaseBlock{},
71 }
72 for _, attr := range attrs {
73 node.SetAttribute(attr.Name, attr.Value)
74 }
75 return node, parser.NoChildren
76 }
77 return nil, parser.RequireParagraph
78 }
79
80 func (a *attrParser) Trigger() []byte {
81 return []byte{'{'}
82 }
83
84 type attributesBlock struct {
85 ast.BaseBlock
86 }
87
88 func (a *attributesBlock) Dump(source []byte, level int) {
89 attrs := a.Attributes()
90 list := make(map[string]string, len(attrs))
91 for _, attr := range attrs {
92 var (
93 name = util.BytesToReadOnlyString(attr.Name)
94 value = util.BytesToReadOnlyString(util.EscapeHTML(attr.Value.([]byte)))
95 )
96 list[name] = value
97 }
98 ast.DumpHelper(a, source, level, list, nil)
99 }
100
101 func (a *attributesBlock) Kind() ast.NodeKind {
102 return kindAttributesBlock
103 }
104
105 type transformer struct {
106 cfg goldmark_config.Parser
107 }
108
109 func (a *transformer) isFragmentNode(n ast.Node) bool {
110 switch n.Kind() {
111 case east.KindDefinitionTerm, ast.KindHeading:
112 return true
113 default:
114 return false
115 }
116 }
117
118 func (a *transformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
119 var attributes []ast.Node
120 var solitaryAttributeNodes []ast.Node
121 if a.cfg.Attribute.Block {
122 attributes = make([]ast.Node, 0, 100)
123 }
124 ast.Walk(node, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
125 if !entering {
126 return ast.WalkContinue, nil
127 }
128
129 if a.isFragmentNode(node) {
130 if id, found := node.Attribute(attrNameID); !found {
131 a.generateAutoID(node, reader, pc)
132 } else {
133 pc.IDs().Put(id.([]byte))
134 }
135 }
136
137 if a.cfg.Attribute.Block && node.Kind() == kindAttributesBlock {
138 // Attributes for fenced code blocks are handled in their own extension,
139 // but note that we currently only support code block attributes when
140 // CodeFences=true.
141 if node.PreviousSibling() != nil && node.PreviousSibling().Kind() != ast.KindFencedCodeBlock && !node.HasBlankPreviousLines() {
142 attributes = append(attributes, node)
143 return ast.WalkSkipChildren, nil
144 } else {
145 solitaryAttributeNodes = append(solitaryAttributeNodes, node)
146 }
147 }
148
149 return ast.WalkContinue, nil
150 })
151
152 for _, attr := range attributes {
153 if prev := attr.PreviousSibling(); prev != nil &&
154 prev.Type() == ast.TypeBlock {
155 for _, attr := range attr.Attributes() {
156 if _, found := prev.Attribute(attr.Name); !found {
157 prev.SetAttribute(attr.Name, attr.Value)
158 }
159 }
160 }
161 // remove attributes node
162 attr.Parent().RemoveChild(attr.Parent(), attr)
163 }
164
165 // Remove any solitary attribute nodes.
166 for _, n := range solitaryAttributeNodes {
167 n.Parent().RemoveChild(n.Parent(), n)
168 }
169 }
170
171 func (a *transformer) generateAutoID(n ast.Node, reader text.Reader, pc parser.Context) {
172 var text []byte
173 switch n := n.(type) {
174 case *ast.Heading:
175 if a.cfg.AutoHeadingID {
176 text = textHeadingID(n, reader)
177 }
178 case *east.DefinitionTerm:
179 if a.cfg.AutoDefinitionTermID {
180 text = []byte(render.TextPlain(n, reader.Source()))
181 }
182 }
183
184 if len(text) > 0 {
185 headingID := pc.IDs().Generate(text, n.Kind())
186 n.SetAttribute(attrNameID, headingID)
187 }
188 }
189
190 // Markdown settext headers can have multiple lines, use the last line for the ID.
191 func textHeadingID(n *ast.Heading, reader text.Reader) []byte {
192 text := render.TextPlain(n, reader.Source())
193 if n.Lines().Len() > 1 {
194
195 // For multiline headings, Goldmark's extension for headings returns the last line.
196 // We have a slightly different approach, but in most cases the end result should be the same.
197 // Instead of looking at the text segments in Lines (see #13405 for issues with that),
198 // we split the text above and use the last line.
199 parts := strings.Split(text, "\n")
200 text = parts[len(parts)-1]
201 }
202
203 return []byte(text)
204 }