Debian Codegraph @

markup/goldmark/codeblocks/render.go

raw
1 // Copyright 2024 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 codeblocks
15
16 import (
17 "bytes"
18 "errors"
19 "fmt"
20 "strings"
21
22 "github.com/gohugoio/hugo/common/herrors"
23 htext "github.com/gohugoio/hugo/common/text"
24 "github.com/gohugoio/hugo/markup/converter/hooks"
25 "github.com/gohugoio/hugo/markup/goldmark/internal/render"
26 "github.com/gohugoio/hugo/markup/internal/attributes"
27 "github.com/yuin/goldmark"
28 "github.com/yuin/goldmark/ast"
29 "github.com/yuin/goldmark/parser"
30 "github.com/yuin/goldmark/renderer"
31 "github.com/yuin/goldmark/text"
32 "github.com/yuin/goldmark/util"
33 )
34
35 type (
36 codeBlocksExtension struct{}
37 htmlRenderer struct{}
38 )
39
40 func New() goldmark.Extender {
41 return &codeBlocksExtension{}
42 }
43
44 func (e *codeBlocksExtension) Extend(m goldmark.Markdown) {
45 m.Renderer().AddOptions(renderer.WithNodeRenderers(
46 util.Prioritized(newHTMLRenderer(), 100),
47 ))
48 }
49
50 func newHTMLRenderer() renderer.NodeRenderer {
51 r := &htmlRenderer{}
52 return r
53 }
54
55 func (r *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
56 reg.Register(ast.KindFencedCodeBlock, r.renderCodeBlock)
57 }
58
59 func (r *htmlRenderer) renderCodeBlock(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
60 ctx := w.(*render.Context)
61
62 if entering {
63 return ast.WalkContinue, nil
64 }
65
66 n := node.(*ast.FencedCodeBlock)
67
68 lang := getLang(n, src)
69 renderer := ctx.RenderContext().GetRenderer(hooks.CodeBlockRendererType, lang)
70 if renderer == nil {
71 return ast.WalkStop, fmt.Errorf("no code renderer found for %q", lang)
72 }
73
74 ordinal := ctx.GetAndIncrementOrdinal(ast.KindFencedCodeBlock)
75
76 var buff bytes.Buffer
77
78 l := n.Lines().Len()
79 for i := range l {
80 line := n.Lines().At(i)
81 buff.Write(line.Value(src))
82 }
83
84 s := htext.Chomp(buff.String())
85
86 var info []byte
87 if n.Info != nil {
88 info = n.Info.Segment.Value(src)
89 }
90
91 attrs, attrStr, err := getAttributes(n, info)
92 if err != nil {
93 return ast.WalkStop, &herrors.TextSegmentError{Err: err, Segment: attrStr}
94 }
95
96 cbctx := codeBlockContext{
97 BaseContext: render.NewBaseContext(ctx, renderer, node, src, ordinal),
98 lang: lang,
99 code: s,
100 AttributesHolder: attributes.New(attrs, attributes.AttributesOwnerCodeBlockChroma),
101 }
102
103 cr := renderer.(hooks.CodeBlockRenderer)
104
105 err = cr.RenderCodeblock(
106 ctx.RenderContext().Ctx,
107 w,
108 cbctx,
109 )
110 if err != nil {
111 return ast.WalkContinue, herrors.NewFileErrorFromPos(err, cbctx.Position())
112 }
113
114 return ast.WalkContinue, nil
115 }
116
117 type codeBlockContext struct {
118 hooks.BaseContext
119 lang string
120 code string
121
122 *attributes.AttributesHolder
123 }
124
125 func (c codeBlockContext) Type() string {
126 return c.lang
127 }
128
129 func (c codeBlockContext) Inner() string {
130 return c.code
131 }
132
133 func getLang(node *ast.FencedCodeBlock, src []byte) string {
134 langWithAttributes := string(node.Language(src))
135 lang, _, _ := strings.Cut(langWithAttributes, "{")
136 return lang
137 }
138
139 func getAttributes(node *ast.FencedCodeBlock, infostr []byte) ([]ast.Attribute, string, error) {
140 if node.Attributes() != nil {
141 return node.Attributes(), "", nil
142 }
143 if infostr != nil {
144 attrStartIdx := -1
145 attrEndIdx := -1
146
147 for idx, char := range infostr {
148 if attrEndIdx == -1 && char == '{' {
149 attrStartIdx = idx
150 }
151 if attrStartIdx != -1 && char == '}' {
152 attrEndIdx = idx
153 break
154 }
155 }
156
157 if attrStartIdx != -1 && attrEndIdx != -1 {
158 n := ast.NewTextBlock() // dummy node for storing attributes
159 attrStr := infostr[attrStartIdx : attrEndIdx+1]
160 if attrs, hasAttr := parser.ParseAttributes(text.NewReader(attrStr)); hasAttr {
161 for _, attr := range attrs {
162 n.SetAttribute(attr.Name, attr.Value)
163 }
164 return n.Attributes(), "", nil
165 } else {
166 return nil, string(attrStr), errors.New("failed to parse Markdown attributes; you may need to quote the values")
167 }
168 }
169 }
170 return nil, "", nil
171 }