Debian Codegraph @

markup/goldmark/convert.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 converts Markdown to HTML using Goldmark.
15 package goldmark
16
17 import (
18 "bytes"
19
20 "github.com/gohugoio/hugo-goldmark-extensions/extras"
21 "github.com/gohugoio/hugo/markup/goldmark/blockquotes"
22 "github.com/gohugoio/hugo/markup/goldmark/codeblocks"
23 "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
24 "github.com/gohugoio/hugo/markup/goldmark/hugocontext"
25 "github.com/gohugoio/hugo/markup/goldmark/images"
26 "github.com/gohugoio/hugo/markup/goldmark/internal/extensions/attributes"
27 "github.com/gohugoio/hugo/markup/goldmark/internal/render"
28 "github.com/gohugoio/hugo/markup/goldmark/passthrough"
29 "github.com/gohugoio/hugo/markup/goldmark/tables"
30 "github.com/yuin/goldmark/util"
31
32 "github.com/yuin/goldmark"
33 emoji "github.com/yuin/goldmark-emoji"
34 "github.com/yuin/goldmark/ast"
35 "github.com/yuin/goldmark/extension"
36 "github.com/yuin/goldmark/parser"
37 "github.com/yuin/goldmark/renderer"
38 "github.com/yuin/goldmark/renderer/html"
39 "github.com/yuin/goldmark/text"
40
41 "github.com/gohugoio/hugo/markup/converter"
42 "github.com/gohugoio/hugo/markup/tableofcontents"
43 )
44
45 const (
46 // Don't change this. This pattern is lso used in the image render hooks.
47 internalAttrPrefix = "_h__"
48 )
49
50 // Provider is the package entry point.
51 var Provider converter.ProviderProvider = provide{}
52
53 type provide struct{}
54
55 func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) {
56 md := newMarkdown(cfg)
57
58 return converter.NewProvider("goldmark", func(ctx converter.DocumentContext) (converter.Converter, error) {
59 return &goldmarkConverter{
60 ctx: ctx,
61 cfg: cfg,
62 md: md,
63 sanitizeAnchorName: func(s string) string {
64 return sanitizeAnchorNameString(s, cfg.MarkupConfig().Goldmark.Parser.AutoIDType)
65 },
66 }, nil
67 }), nil
68 }
69
70 var _ converter.AnchorNameSanitizer = (*goldmarkConverter)(nil)
71
72 type goldmarkConverter struct {
73 md goldmark.Markdown
74 ctx converter.DocumentContext
75 cfg converter.ProviderConfig
76
77 sanitizeAnchorName func(s string) string
78 }
79
80 func (c *goldmarkConverter) SanitizeAnchorName(s string) string {
81 return c.sanitizeAnchorName(s)
82 }
83
84 func newMarkdown(pcfg converter.ProviderConfig) goldmark.Markdown {
85 mcfg := pcfg.MarkupConfig()
86 cfg := mcfg.Goldmark
87 var rendererOptions []renderer.Option
88
89 if cfg.Renderer.HardWraps {
90 rendererOptions = append(rendererOptions, html.WithHardWraps())
91 }
92
93 if cfg.Renderer.XHTML {
94 rendererOptions = append(rendererOptions, html.WithXHTML())
95 }
96
97 if cfg.Renderer.Unsafe {
98 rendererOptions = append(rendererOptions, html.WithUnsafe())
99 }
100
101 tocRendererOptions := make([]renderer.Option, len(rendererOptions))
102 if rendererOptions != nil {
103 copy(tocRendererOptions, rendererOptions)
104 }
105
106 tocRendererOptions = append(tocRendererOptions,
107 renderer.WithNodeRenderers(util.Prioritized(extension.NewStrikethroughHTMLRenderer(), 500)),
108 renderer.WithNodeRenderers(util.Prioritized(emoji.NewHTMLRenderer(), 200)),
109 )
110
111 inlineTags := []extras.InlineTag{
112 extras.DeleteTag,
113 extras.InsertTag,
114 extras.MarkTag,
115 extras.SubscriptTag,
116 extras.SuperscriptTag,
117 }
118
119 for _, tag := range inlineTags {
120 tocRendererOptions = append(tocRendererOptions,
121 renderer.WithNodeRenderers(util.Prioritized(extras.NewInlineTagHTMLRenderer(tag), tag.RenderPriority)),
122 )
123 }
124
125 if cfg.Extensions.Passthrough.Enable {
126 tocRendererOptions = append(tocRendererOptions,
127 renderer.WithNodeRenderers(util.Prioritized(&tocPassthroughRenderer{}, 90)),
128 )
129 }
130
131 var (
132 extensions = []goldmark.Extender{
133 hugocontext.New(pcfg.Logger),
134 newLinks(cfg),
135 newTocExtension(tocRendererOptions),
136 blockquotes.New(),
137 }
138 parserOptions []parser.Option
139 )
140
141 extensions = append(extensions, images.New(cfg.Parser.WrapStandAloneImageWithinParagraph))
142
143 extensions = append(extensions, extras.New(
144 extras.Config{
145 Delete: extras.DeleteConfig{Enable: cfg.Extensions.Extras.Delete.Enable},
146 Insert: extras.InsertConfig{Enable: cfg.Extensions.Extras.Insert.Enable},
147 Mark: extras.MarkConfig{Enable: cfg.Extensions.Extras.Mark.Enable},
148 Subscript: extras.SubscriptConfig{Enable: cfg.Extensions.Extras.Subscript.Enable},
149 Superscript: extras.SuperscriptConfig{Enable: cfg.Extensions.Extras.Superscript.Enable},
150 },
151 ))
152
153 if mcfg.Highlight.CodeFences {
154 extensions = append(extensions, codeblocks.New())
155 }
156
157 if cfg.Extensions.Table {
158 extensions = append(extensions, extension.Table)
159 extensions = append(extensions, tables.New())
160 }
161
162 if cfg.Extensions.Strikethrough {
163 extensions = append(extensions, extension.Strikethrough)
164 }
165
166 if cfg.Extensions.Linkify {
167 extensions = append(extensions, extension.Linkify)
168 }
169
170 if cfg.Extensions.TaskList {
171 extensions = append(extensions, extension.TaskList)
172 }
173
174 if !cfg.Extensions.Typographer.Disable {
175 t := extension.NewTypographer(
176 extension.WithTypographicSubstitutions(toTypographicPunctuationMap(cfg.Extensions.Typographer)),
177 )
178 extensions = append(extensions, t)
179 }
180
181 if cfg.Extensions.DefinitionList {
182 extensions = append(extensions, extension.DefinitionList)
183 }
184
185 if cfg.Extensions.Footnote.Enable {
186 opts := []extension.FootnoteOption{}
187 opts = append(opts, extension.WithFootnoteBacklinkHTML(cfg.Extensions.Footnote.BacklinkHTML))
188 if cfg.Extensions.Footnote.EnableAutoIDPrefix {
189 opts = append(opts,
190 extension.WithFootnoteIDPrefixFunction(func(n ast.Node) []byte {
191 documentID := n.OwnerDocument().Meta()["documentID"].(string)
192 return []byte("h" + documentID)
193 }))
194 }
195 f := extension.NewFootnote(opts...)
196 extensions = append(extensions, f)
197 }
198
199 if cfg.Extensions.CJK.Enable {
200 opts := []extension.CJKOption{}
201 if cfg.Extensions.CJK.EastAsianLineBreaks {
202 if cfg.Extensions.CJK.EastAsianLineBreaksStyle == "css3draft" {
203 opts = append(opts, extension.WithEastAsianLineBreaks(extension.EastAsianLineBreaksCSS3Draft))
204 } else {
205 opts = append(opts, extension.WithEastAsianLineBreaks())
206 }
207 }
208
209 if cfg.Extensions.CJK.EscapedSpace {
210 opts = append(opts, extension.WithEscapedSpace())
211 }
212 c := extension.NewCJK(opts...)
213 extensions = append(extensions, c)
214 }
215
216 if cfg.Extensions.Passthrough.Enable {
217 extensions = append(extensions, passthrough.New(cfg.Extensions.Passthrough))
218 }
219
220 if pcfg.Conf.EnableEmoji() {
221 extensions = append(extensions, emoji.Emoji)
222 }
223
224 if cfg.Parser.Attribute.Title {
225 parserOptions = append(parserOptions, parser.WithAttribute())
226 }
227
228 if cfg.Parser.Attribute.Block || cfg.Parser.AutoHeadingID || cfg.Parser.AutoDefinitionTermID {
229 extensions = append(extensions, attributes.New(cfg.Parser))
230 }
231
232 md := goldmark.New(
233 goldmark.WithExtensions(
234 extensions...,
235 ),
236 goldmark.WithParserOptions(
237 parserOptions...,
238 ),
239 goldmark.WithRendererOptions(
240 rendererOptions...,
241 ),
242 )
243
244 return md
245 }
246
247 type parserResult struct {
248 doc any
249 toc *tableofcontents.Fragments
250 }
251
252 func (p parserResult) Doc() any {
253 return p.doc
254 }
255
256 func (p parserResult) TableOfContents() *tableofcontents.Fragments {
257 return p.toc
258 }
259
260 type renderResult struct {
261 converter.ResultRender
262 }
263
264 type converterResult struct {
265 converter.ResultRender
266 tableOfContentsProvider
267 }
268
269 type tableOfContentsProvider interface {
270 TableOfContents() *tableofcontents.Fragments
271 }
272
273 func (c *goldmarkConverter) Parse(ctx converter.RenderContext) (converter.ResultParse, error) {
274 pctx := c.newParserContext(ctx)
275 reader := text.NewReader(ctx.Src)
276
277 doc := c.md.Parser().Parse(
278 reader,
279 parser.WithContext(pctx),
280 )
281 doc.OwnerDocument().AddMeta("documentID", c.ctx.DocumentID)
282
283 return parserResult{
284 doc: doc,
285 toc: pctx.TableOfContents(),
286 }, nil
287 }
288
289 func (c *goldmarkConverter) Render(ctx converter.RenderContext, doc any) (converter.ResultRender, error) {
290 n := doc.(ast.Node)
291 buf := &render.BufWriter{Buffer: &bytes.Buffer{}}
292
293 rcx := &render.RenderContextDataHolder{
294 Rctx: ctx,
295 Dctx: c.ctx,
296 }
297
298 w := &render.Context{
299 BufWriter: buf,
300 ContextData: rcx,
301 }
302
303 if err := c.md.Renderer().Render(w, ctx.Src, n); err != nil {
304 return nil, err
305 }
306
307 return renderResult{
308 ResultRender: buf,
309 }, nil
310 }
311
312 func (c *goldmarkConverter) Convert(ctx converter.RenderContext) (converter.ResultRender, error) {
313 parseResult, err := c.Parse(ctx)
314 if err != nil {
315 return nil, err
316 }
317 renderResult, err := c.Render(ctx, parseResult.Doc())
318 if err != nil {
319 return nil, err
320 }
321 return converterResult{
322 ResultRender: renderResult,
323 tableOfContentsProvider: parseResult,
324 }, nil
325 }
326
327 func (c *goldmarkConverter) newParserContext(rctx converter.RenderContext) *parserContext {
328 ctx := parser.NewContext(parser.WithIDs(newIDFactory(c.cfg.MarkupConfig().Goldmark.Parser.AutoIDType)))
329 ctx.Set(tocEnableKey, rctx.RenderTOC)
330 return &parserContext{
331 Context: ctx,
332 }
333 }
334
335 type parserContext struct {
336 parser.Context
337 }
338
339 func (p *parserContext) TableOfContents() *tableofcontents.Fragments {
340 if v := p.Get(tocResultKey); v != nil {
341 return v.(*tableofcontents.Fragments)
342 }
343 return nil
344 }
345
346 // Note: It's tempting to put this in the config package, but that doesn't work.
347 // TODO(bep) create upstream issue.
348 func toTypographicPunctuationMap(t goldmark_config.Typographer) map[extension.TypographicPunctuation][]byte {
349 return map[extension.TypographicPunctuation][]byte{
350 extension.LeftSingleQuote: []byte(t.LeftSingleQuote),
351 extension.RightSingleQuote: []byte(t.RightSingleQuote),
352 extension.LeftDoubleQuote: []byte(t.LeftDoubleQuote),
353 extension.RightDoubleQuote: []byte(t.RightDoubleQuote),
354 extension.EnDash: []byte(t.EnDash),
355 extension.EmDash: []byte(t.EmDash),
356 extension.Ellipsis: []byte(t.Ellipsis),
357 extension.LeftAngleQuote: []byte(t.LeftAngleQuote),
358 extension.RightAngleQuote: []byte(t.RightAngleQuote),
359 extension.Apostrophe: []byte(t.Apostrophe),
360 }
361 }