Debian Codegraph @

markup/goldmark/render_hooks.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package goldmark
15
16 import (
17 "bytes"
18 "strings"
19
20 "github.com/gohugoio/hugo/common/types/hstring"
21 "github.com/gohugoio/hugo/markup/converter/hooks"
22 "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
23 "github.com/gohugoio/hugo/markup/goldmark/images"
24 "github.com/gohugoio/hugo/markup/goldmark/internal/render"
25 "github.com/gohugoio/hugo/markup/internal/attributes"
26
27 "github.com/yuin/goldmark"
28 "github.com/yuin/goldmark/ast"
29 "github.com/yuin/goldmark/renderer"
30 "github.com/yuin/goldmark/renderer/html"
31 "github.com/yuin/goldmark/util"
32 )
33
34 var _ renderer.SetOptioner = (*hookedRenderer)(nil)
35
36 func newLinkRenderer(cfg goldmark_config.Config) renderer.NodeRenderer {
37 r := &hookedRenderer{
38 linkifyProtocol: []byte(cfg.Extensions.LinkifyProtocol),
39 Config: html.Config{
40 Writer: html.DefaultWriter,
41 },
42 }
43 return r
44 }
45
46 func newLinks(cfg goldmark_config.Config) goldmark.Extender {
47 return &links{cfg: cfg}
48 }
49
50 type linkContext struct {
51 hooks.BaseContext
52 destination string
53 title string
54 text hstring.HTML
55 plainText string
56 *attributes.AttributesHolder
57 }
58
59 func (ctx linkContext) Destination() string {
60 return ctx.destination
61 }
62
63 func (ctx linkContext) Text() hstring.HTML {
64 return ctx.text
65 }
66
67 func (ctx linkContext) PlainText() string {
68 return ctx.plainText
69 }
70
71 func (ctx linkContext) Title() string {
72 return ctx.title
73 }
74
75 type imageLinkContext struct {
76 linkContext
77 isBlock bool
78 }
79
80 func (ctx imageLinkContext) IsBlock() bool {
81 return ctx.isBlock
82 }
83
84 type headingContext struct {
85 hooks.BaseContext
86 level int
87 anchor string
88 text hstring.HTML
89 plainText string
90 *attributes.AttributesHolder
91 }
92
93 func (ctx headingContext) Level() int {
94 return ctx.level
95 }
96
97 func (ctx headingContext) Anchor() string {
98 return ctx.anchor
99 }
100
101 func (ctx headingContext) Text() hstring.HTML {
102 return ctx.text
103 }
104
105 func (ctx headingContext) PlainText() string {
106 return ctx.plainText
107 }
108
109 type hookedRenderer struct {
110 linkifyProtocol []byte
111 html.Config
112 }
113
114 func (r *hookedRenderer) SetOption(name renderer.OptionName, value any) {
115 r.Config.SetOption(name, value)
116 }
117
118 // RegisterFuncs implements NodeRenderer.RegisterFuncs.
119 func (r *hookedRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
120 reg.Register(ast.KindLink, r.renderLink)
121 reg.Register(ast.KindAutoLink, r.renderAutoLink)
122 reg.Register(ast.KindImage, r.renderImage)
123 reg.Register(ast.KindHeading, r.renderHeading)
124 }
125
126 func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
127 n := node.(*ast.Image)
128 var lr hooks.LinkRenderer
129
130 ctx, ok := w.(*render.Context)
131 if ok {
132 h := ctx.RenderContext().GetRenderer(hooks.ImageRendererType, nil)
133 ok = h != nil
134 if ok {
135 lr = h.(hooks.LinkRenderer)
136 }
137 }
138
139 if !ok {
140 return r.renderImageDefault(w, source, node, entering)
141 }
142
143 if entering {
144 // Store the current pos so we can capture the rendered text.
145 ctx.PushPos(ctx.Buffer.Len())
146 return ast.WalkContinue, nil
147 }
148
149 text := ctx.PopRenderedString()
150
151 var (
152 isBlock bool
153 ordinal int
154 )
155 if b, ok := n.AttributeString(images.AttrIsBlock); ok && b.(bool) {
156 isBlock = true
157 }
158 if n, ok := n.AttributeString(images.AttrOrdinal); ok {
159 ordinal = n.(int)
160 }
161
162 // We use the attributes to signal from the parser whether the image is in
163 // a block context or not.
164 // We may find a better way to do that, but for now, we'll need to remove any
165 // internal attributes before rendering.
166 attrs := r.filterInternalAttributes(n.Attributes())
167
168 err := lr.RenderLink(
169 ctx.RenderContext().Ctx,
170 w,
171 imageLinkContext{
172 linkContext: linkContext{
173 BaseContext: render.NewBaseContext(ctx, lr, node, source, ordinal),
174 destination: string(n.Destination),
175 title: string(n.Title),
176 text: hstring.HTML(text),
177 plainText: render.TextPlain(n, source),
178 AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerGeneral),
179 },
180 isBlock: isBlock,
181 },
182 )
183
184 return ast.WalkContinue, err
185 }
186
187 func (r *hookedRenderer) filterInternalAttributes(attrs []ast.Attribute) []ast.Attribute {
188 n := 0
189 for _, x := range attrs {
190 if !bytes.HasPrefix(x.Name, []byte(internalAttrPrefix)) {
191 attrs[n] = x
192 n++
193 }
194 }
195 return attrs[:n]
196 }
197
198 // Fall back to the default Goldmark render funcs. Method below borrowed from:
199 // https://github.com/yuin/goldmark
200 func (r *hookedRenderer) renderImageDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
201 if !entering {
202 return ast.WalkContinue, nil
203 }
204 n := node.(*ast.Image)
205 _, _ = w.WriteString("<img src=\"")
206 dest := util.URLEscape(n.Destination, true)
207 if r.Unsafe || !html.IsDangerousURL(dest) {
208 _, _ = w.Write(util.EscapeHTML(dest))
209 }
210 _, _ = w.WriteString(`" alt="`)
211 r.renderTexts(w, source, n)
212 _ = w.WriteByte('"')
213 if n.Title != nil {
214 _, _ = w.WriteString(` title="`)
215 r.Writer.Write(w, n.Title)
216 _ = w.WriteByte('"')
217 }
218 if n.Attributes() != nil {
219 html.RenderAttributes(w, n, html.ImageAttributeFilter)
220 }
221 if r.XHTML {
222 _, _ = w.WriteString(" />")
223 } else {
224 _, _ = w.WriteString(">")
225 }
226 return ast.WalkSkipChildren, nil
227 }
228
229 func (r *hookedRenderer) renderLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
230 n := node.(*ast.Link)
231 var lr hooks.LinkRenderer
232
233 ctx, ok := w.(*render.Context)
234 if ok {
235 h := ctx.RenderContext().GetRenderer(hooks.LinkRendererType, nil)
236 ok = h != nil
237 if ok {
238 lr = h.(hooks.LinkRenderer)
239 }
240 }
241
242 if !ok {
243 return r.renderLinkDefault(w, source, node, entering)
244 }
245
246 if entering {
247 // Store the current pos so we can capture the rendered text.
248 ctx.PushPos(ctx.Buffer.Len())
249 return ast.WalkContinue, nil
250 }
251
252 text := ctx.PopRenderedString()
253 ordinal := ctx.GetAndIncrementOrdinal(node.Kind())
254
255 err := lr.RenderLink(
256 ctx.RenderContext().Ctx,
257 w,
258 linkContext{
259 BaseContext: render.NewBaseContext(ctx, lr, node, source, ordinal),
260 destination: string(n.Destination),
261 title: string(n.Title),
262 text: hstring.HTML(text),
263 plainText: render.TextPlain(n, source),
264 AttributesHolder: attributes.Empty,
265 },
266 )
267
268 return ast.WalkContinue, err
269 }
270
271 // Borrowed from Goldmark's HTML renderer.
272 func (r *hookedRenderer) renderTexts(w util.BufWriter, source []byte, n ast.Node) {
273 for c := n.FirstChild(); c != nil; c = c.NextSibling() {
274 if s, ok := c.(*ast.String); ok {
275 _, _ = r.renderString(w, source, s, true)
276 } else if t, ok := c.(*ast.Text); ok {
277 _, _ = r.renderText(w, source, t, true)
278 } else {
279 r.renderTexts(w, source, c)
280 }
281 }
282 }
283
284 // Borrowed from Goldmark's HTML renderer.
285 func (r *hookedRenderer) renderString(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
286 if !entering {
287 return ast.WalkContinue, nil
288 }
289 n := node.(*ast.String)
290 if n.IsCode() {
291 _, _ = w.Write(n.Value)
292 } else {
293 if n.IsRaw() {
294 r.Writer.RawWrite(w, n.Value)
295 } else {
296 r.Writer.Write(w, n.Value)
297 }
298 }
299 return ast.WalkContinue, nil
300 }
301
302 // Borrowed from Goldmark's HTML renderer.
303 func (r *hookedRenderer) renderText(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
304 if !entering {
305 return ast.WalkContinue, nil
306 }
307 n := node.(*ast.Text)
308 segment := n.Segment
309 if n.IsRaw() {
310 r.Writer.RawWrite(w, segment.Value(source))
311 } else {
312 value := segment.Value(source)
313 r.Writer.Write(w, value)
314 if n.HardLineBreak() || (n.SoftLineBreak() && r.HardWraps) {
315 if r.XHTML {
316 _, _ = w.WriteString("<br />\n")
317 } else {
318 _, _ = w.WriteString("<br>\n")
319 }
320 } else if n.SoftLineBreak() {
321 // TODO(bep) we use these methods a fallback to default rendering when no image/link hooks are defined.
322 // I don't think the below is relevant in these situations, but if so, we need to create a PR
323 // upstream to export softLineBreak.
324 /*if r.EastAsianLineBreaks != html.EastAsianLineBreaksNone && len(value) != 0 {
325 sibling := node.NextSibling()
326 if sibling != nil && sibling.Kind() == ast.KindText {
327 if siblingText := sibling.(*ast.Text).Value(source); len(siblingText) != 0 {
328 thisLastRune := util.ToRune(value, len(value)-1)
329 siblingFirstRune, _ := utf8.DecodeRune(siblingText)
330 if r.EastAsianLineBreaks.softLineBreak(thisLastRune, siblingFirstRune) {
331 _ = w.WriteByte('\n')
332 }
333 }
334 }
335 } else {
336 _ = w.WriteByte('\n')
337 }*/
338 _ = w.WriteByte('\n')
339 }
340 }
341 return ast.WalkContinue, nil
342 }
343
344 // Fall back to the default Goldmark render funcs. Method below borrowed from:
345 // https://github.com/yuin/goldmark/blob/b611cd333a492416b56aa8d94b04a67bf0096ab2/renderer/html/html.go#L404
346 func (r *hookedRenderer) renderLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
347 n := node.(*ast.Link)
348 if entering {
349 _, _ = w.WriteString("<a href=\"")
350 dest := util.URLEscape(n.Destination, true)
351 if r.Unsafe || !html.IsDangerousURL(dest) {
352 _, _ = w.Write(util.EscapeHTML(dest))
353 }
354 _ = w.WriteByte('"')
355 if n.Title != nil {
356 _, _ = w.WriteString(` title="`)
357 r.Writer.Write(w, n.Title)
358 _ = w.WriteByte('"')
359 }
360 _ = w.WriteByte('>')
361 } else {
362 _, _ = w.WriteString("</a>")
363 }
364 return ast.WalkContinue, nil
365 }
366
367 func (r *hookedRenderer) renderAutoLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
368 if !entering {
369 return ast.WalkContinue, nil
370 }
371
372 n := node.(*ast.AutoLink)
373 var lr hooks.LinkRenderer
374
375 ctx, ok := w.(*render.Context)
376 if ok {
377 h := ctx.RenderContext().GetRenderer(hooks.LinkRendererType, nil)
378 ok = h != nil
379 if ok {
380 lr = h.(hooks.LinkRenderer)
381 }
382 }
383
384 if !ok {
385 return r.renderAutoLinkDefault(w, source, node, entering)
386 }
387
388 url := string(r.autoLinkURL(n, source))
389 label := string(n.Label(source))
390 if n.AutoLinkType == ast.AutoLinkEmail && !strings.HasPrefix(strings.ToLower(url), "mailto:") {
391 url = "mailto:" + url
392 }
393
394 ordinal := ctx.GetAndIncrementOrdinal(n.Kind())
395
396 err := lr.RenderLink(
397 ctx.RenderContext().Ctx,
398 w,
399 linkContext{
400 BaseContext: render.NewBaseContext(ctx, lr, node, source, ordinal),
401 destination: url,
402 text: hstring.HTML(label),
403 plainText: label,
404 AttributesHolder: attributes.Empty,
405 },
406 )
407
408 return ast.WalkContinue, err
409 }
410
411 // Fall back to the default Goldmark render funcs. Method below borrowed from:
412 // https://github.com/yuin/goldmark/blob/5588d92a56fe1642791cf4aa8e9eae8227cfeecd/renderer/html/html.go#L439
413 func (r *hookedRenderer) renderAutoLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
414 n := node.(*ast.AutoLink)
415 if !entering {
416 return ast.WalkContinue, nil
417 }
418
419 _, _ = w.WriteString(`<a href="`)
420 url := util.URLEscape(r.autoLinkURL(n, source), false)
421
422 label := n.Label(source)
423 if n.AutoLinkType == ast.AutoLinkEmail && !bytes.HasPrefix(bytes.ToLower(url), []byte("mailto:")) {
424 _, _ = w.WriteString("mailto:")
425 }
426 if r.Unsafe || !html.IsDangerousURL(url) {
427 _, _ = w.Write(util.EscapeHTML(url))
428 }
429 if n.Attributes() != nil {
430 _ = w.WriteByte('"')
431 html.RenderAttributes(w, n, html.LinkAttributeFilter)
432 _ = w.WriteByte('>')
433 } else {
434 _, _ = w.WriteString(`">`)
435 }
436 _, _ = w.Write(util.EscapeHTML(label))
437 _, _ = w.WriteString(`</a>`)
438 return ast.WalkContinue, nil
439 }
440
441 func (r *hookedRenderer) autoLinkURL(n *ast.AutoLink, source []byte) []byte {
442 url := n.URL(source)
443 if len(n.Protocol) > 0 && !bytes.Equal(n.Protocol, r.linkifyProtocol) {
444 // The CommonMark spec says "http" is the correct protocol for links,
445 // but this doesn't make much sense (the fact that they should care about the rendered output).
446 // Note that n.Protocol is not set if protocol is provided by user.
447 url = append(r.linkifyProtocol, url[len(n.Protocol):]...)
448 }
449 return url
450 }
451
452 func (r *hookedRenderer) renderHeading(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
453 n := node.(*ast.Heading)
454 var hr hooks.HeadingRenderer
455
456 ctx, ok := w.(*render.Context)
457 if ok {
458 h := ctx.RenderContext().GetRenderer(hooks.HeadingRendererType, nil)
459 ok = h != nil
460 if ok {
461 hr = h.(hooks.HeadingRenderer)
462 }
463 }
464
465 if !ok {
466 return r.renderHeadingDefault(w, source, node, entering)
467 }
468
469 if entering {
470 // Store the current pos so we can capture the rendered text.
471 ctx.PushPos(ctx.Buffer.Len())
472 return ast.WalkContinue, nil
473 }
474
475 text := ctx.PopRenderedString()
476
477 var anchor []byte
478 if anchori, ok := n.AttributeString("id"); ok {
479 anchor, _ = anchori.([]byte)
480 }
481 ordinal := ctx.GetAndIncrementOrdinal(n.Kind())
482
483 err := hr.RenderHeading(
484 ctx.RenderContext().Ctx,
485 w,
486 headingContext{
487 BaseContext: render.NewBaseContext(ctx, hr, node, source, ordinal),
488 level: n.Level,
489 anchor: string(anchor),
490 text: hstring.HTML(text),
491 plainText: render.TextPlain(n, source),
492 AttributesHolder: attributes.New(n.Attributes(), attributes.AttributesOwnerGeneral),
493 },
494 )
495
496 return ast.WalkContinue, err
497 }
498
499 func (r *hookedRenderer) renderHeadingDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
500 n := node.(*ast.Heading)
501 if entering {
502 _, _ = w.WriteString("<h")
503 _ = w.WriteByte("0123456"[n.Level])
504 if n.Attributes() != nil {
505 attributes.RenderASTAttributes(w, node.Attributes()...)
506 }
507 _ = w.WriteByte('>')
508 } else {
509 _, _ = w.WriteString("</h")
510 _ = w.WriteByte("0123456"[n.Level])
511 _, _ = w.WriteString(">\n")
512 }
513 return ast.WalkContinue, nil
514 }
515
516 type links struct {
517 cfg goldmark_config.Config
518 }
519
520 // Extend implements goldmark.Extender.
521 func (e *links) Extend(m goldmark.Markdown) {
522 m.Renderer().AddOptions(renderer.WithNodeRenderers(
523 util.Prioritized(newLinkRenderer(e.cfg), 100),
524 ))
525 }