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