Debian Codegraph @

markup/goldmark/toc.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 "regexp"
19 "strings"
20
21 "github.com/microcosm-cc/bluemonday"
22 strikethroughAst "github.com/yuin/goldmark/extension/ast"
23
24 emojiAst "github.com/yuin/goldmark-emoji/ast"
25
26 "github.com/gohugoio/hugo-goldmark-extensions/extras"
27 "github.com/gohugoio/hugo-goldmark-extensions/passthrough"
28 "github.com/gohugoio/hugo/markup/tableofcontents"
29
30 "github.com/yuin/goldmark"
31 "github.com/yuin/goldmark/ast"
32 "github.com/yuin/goldmark/parser"
33 "github.com/yuin/goldmark/renderer"
34 "github.com/yuin/goldmark/text"
35 "github.com/yuin/goldmark/util"
36 )
37
38 var (
39 tocResultKey = parser.NewContextKey()
40 tocEnableKey = parser.NewContextKey()
41 )
42
43 type tocTransformer struct {
44 r renderer.Renderer
45 }
46
47 func (t *tocTransformer) Transform(n *ast.Document, reader text.Reader, pc parser.Context) {
48 if b, ok := pc.Get(tocEnableKey).(bool); !ok || !b {
49 return
50 }
51
52 var (
53 toc tableofcontents.Builder
54 tocHeading = &tableofcontents.Heading{}
55 level int
56 row = -1
57 inHeading bool
58 headingText bytes.Buffer
59 )
60
61 if ids := pc.IDs().(stringValuesProvider).StringValues(); len(ids) > 0 {
62 toc.SetIdentifiers(ids)
63 }
64
65 ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
66 s := ast.WalkStatus(ast.WalkContinue)
67 if n.Kind() == ast.KindHeading {
68 if inHeading && !entering {
69 tocHeading.Title = sanitizeTOCHeadingTitle(headingText.String())
70 headingText.Reset()
71 toc.AddAt(tocHeading, row, level-1)
72 tocHeading = &tableofcontents.Heading{}
73 inHeading = false
74 return s, nil
75 }
76
77 inHeading = true
78 }
79
80 if !(inHeading && entering) {
81 return s, nil
82 }
83
84 switch n.Kind() {
85 case ast.KindHeading:
86 heading := n.(*ast.Heading)
87 level = heading.Level
88
89 if level == 1 || row == -1 {
90 row++
91 }
92
93 id, found := heading.AttributeString("id")
94 if found {
95 tocHeading.ID = string(id.([]byte))
96 tocHeading.Level = level
97 }
98 case
99 ast.KindCodeSpan,
100 ast.KindLink,
101 ast.KindImage,
102 ast.KindEmphasis,
103 strikethroughAst.KindStrikethrough,
104 emojiAst.KindEmoji,
105 extras.KindDelete,
106 extras.KindInsert,
107 extras.KindMark,
108 extras.KindSubscript,
109 extras.KindSuperscript:
110 err := t.r.Render(&headingText, reader.Source(), n)
111 if err != nil {
112 return s, err
113 }
114
115 return ast.WalkSkipChildren, nil
116 case
117 ast.KindAutoLink,
118 ast.KindRawHTML,
119 ast.KindText,
120 ast.KindString,
121 passthrough.KindPassthroughInline,
122 passthrough.KindPassthroughBlock:
123 err := t.r.Render(&headingText, reader.Source(), n)
124 if err != nil {
125 return s, err
126 }
127 }
128
129 return s, nil
130 })
131
132 pc.Set(tocResultKey, toc.Build())
133 }
134
135 type tocExtension struct {
136 options []renderer.Option
137 }
138
139 func newTocExtension(options []renderer.Option) goldmark.Extender {
140 return &tocExtension{
141 options: options,
142 }
143 }
144
145 func (e *tocExtension) Extend(m goldmark.Markdown) {
146 r := goldmark.DefaultRenderer()
147 r.AddOptions(e.options...)
148 m.Parser().AddOptions(parser.WithASTTransformers(util.Prioritized(&tocTransformer{
149 r: r,
150 },
151 // This must run after the ID generation (priority 100).
152 110)))
153 }
154
155 var tocSanitizerPolicy = newTOCSanitizerPolicy()
156
157 // newTOCSanitizerPolicy returns a bluemonday policy for sanitizing TOC heading
158 // titles against an allowlist of inline HTML elements and attributes,
159 // specifically excluding anchor elements to prevent links within TOC heading
160 // titles.
161 func newTOCSanitizerPolicy() *bluemonday.Policy {
162 p := bluemonday.NewPolicy()
163 p.AllowElements(
164 "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "del", "dfn",
165 "em", "i", "ins", "kbd", "mark", "q", "rp", "rt", "ruby", "s", "samp",
166 "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr",
167 )
168 p.AllowStandardAttributes()
169 p.AllowStyling()
170 p.AllowImages()
171 p.AllowAttrs("cite").OnElements("del", "ins", "q")
172 p.AllowAttrs("datetime").OnElements("del", "ins", "time")
173 p.AllowAttrs("value").OnElements("data")
174 return p
175 }
176
177 // tocPassthroughRenderer renders passthrough nodes as raw text for the TOC.
178 type tocPassthroughRenderer struct{}
179
180 func (r *tocPassthroughRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
181 reg.Register(passthrough.KindPassthroughInline, r.render)
182 reg.Register(passthrough.KindPassthroughBlock, r.render)
183 }
184
185 func (r *tocPassthroughRenderer) render(w util.BufWriter, src []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
186 if !entering {
187 return ast.WalkContinue, nil
188 }
189 switch nn := node.(type) {
190 case *passthrough.PassthroughInline:
191 w.Write(nn.Segment.Value(src))
192 case *passthrough.PassthroughBlock:
193 for i := range nn.Lines().Len() {
194 line := nn.Lines().At(i)
195 w.Write(line.Value(src))
196 }
197 }
198 return ast.WalkSkipChildren, nil
199 }
200
201 var whiteSpaceRe = regexp.MustCompile(`\s+`)
202
203 // sanitizeTOCHeadingTitle sanitizes s for use as a TOC heading title.
204 func sanitizeTOCHeadingTitle(s string) string {
205 if strings.IndexByte(s, '<') == -1 {
206 return s
207 }
208
209 // Sanitize the string.
210 ss := tocSanitizerPolicy.Sanitize(s)
211
212 // Remove extraneous whitespace.
213 return whiteSpaceRe.ReplaceAllString(strings.TrimSpace(ss), " ")
214 }