mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-28 22:19:59 +02:00
Add Goldmark as the new default markdown handler
This commit adds the fast and CommonMark compliant Goldmark as the new default markdown handler in Hugo. If you want to continue using BlackFriday as the default for md/markdown extensions, you can use this configuration: ```toml [markup] defaultMarkdownHandler="blackfriday" ``` Fixes #5963 Fixes #1778 Fixes #6355
This commit is contained in:
233
markup/goldmark/convert.go
Normal file
233
markup/goldmark/convert.go
Normal file
@@ -0,0 +1,233 @@
|
||||
// Copyright 2019 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package goldmark converts Markdown to HTML using Goldmark.
|
||||
package goldmark
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
|
||||
"github.com/gohugoio/hugo/hugofs"
|
||||
|
||||
"github.com/alecthomas/chroma/styles"
|
||||
"github.com/gohugoio/hugo/markup/converter"
|
||||
"github.com/gohugoio/hugo/markup/highlight"
|
||||
hl "github.com/gohugoio/hugo/markup/highlight/temphighlighting"
|
||||
"github.com/gohugoio/hugo/markup/markup_config"
|
||||
"github.com/gohugoio/hugo/markup/tableofcontents"
|
||||
"github.com/yuin/goldmark"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/renderer"
|
||||
"github.com/yuin/goldmark/renderer/html"
|
||||
"github.com/yuin/goldmark/text"
|
||||
"github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
// Provider is the package entry point.
|
||||
var Provider converter.ProviderProvider = provide{}
|
||||
|
||||
type provide struct {
|
||||
}
|
||||
|
||||
func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) {
|
||||
md := newMarkdown(cfg.MarkupConfig)
|
||||
return converter.NewProvider("goldmark", func(ctx converter.DocumentContext) (converter.Converter, error) {
|
||||
return &goldmarkConverter{
|
||||
ctx: ctx,
|
||||
cfg: cfg,
|
||||
md: md,
|
||||
}, nil
|
||||
}), nil
|
||||
}
|
||||
|
||||
type goldmarkConverter struct {
|
||||
md goldmark.Markdown
|
||||
ctx converter.DocumentContext
|
||||
cfg converter.ProviderConfig
|
||||
}
|
||||
|
||||
func newMarkdown(mcfg markup_config.Config) goldmark.Markdown {
|
||||
cfg := mcfg.Goldmark
|
||||
|
||||
var (
|
||||
extensions = []goldmark.Extender{
|
||||
newTocExtension(),
|
||||
}
|
||||
rendererOptions []renderer.Option
|
||||
parserOptions []parser.Option
|
||||
)
|
||||
|
||||
if cfg.Renderer.HardWraps {
|
||||
rendererOptions = append(rendererOptions, html.WithHardWraps())
|
||||
}
|
||||
|
||||
if cfg.Renderer.XHTML {
|
||||
rendererOptions = append(rendererOptions, html.WithXHTML())
|
||||
}
|
||||
|
||||
if cfg.Renderer.Unsafe {
|
||||
rendererOptions = append(rendererOptions, html.WithUnsafe())
|
||||
}
|
||||
|
||||
if mcfg.Highlight.CodeFences {
|
||||
extensions = append(extensions, newHighlighting(mcfg.Highlight))
|
||||
}
|
||||
|
||||
if cfg.Extensions.Table {
|
||||
extensions = append(extensions, extension.Table)
|
||||
}
|
||||
|
||||
if cfg.Extensions.Strikethrough {
|
||||
extensions = append(extensions, extension.Strikethrough)
|
||||
}
|
||||
|
||||
if cfg.Extensions.Linkify {
|
||||
extensions = append(extensions, extension.Linkify)
|
||||
}
|
||||
|
||||
if cfg.Extensions.TaskList {
|
||||
extensions = append(extensions, extension.TaskList)
|
||||
}
|
||||
|
||||
if cfg.Extensions.Typographer {
|
||||
extensions = append(extensions, extension.Typographer)
|
||||
}
|
||||
|
||||
if cfg.Extensions.DefinitionList {
|
||||
extensions = append(extensions, extension.DefinitionList)
|
||||
}
|
||||
|
||||
if cfg.Extensions.Footnote {
|
||||
extensions = append(extensions, extension.Footnote)
|
||||
}
|
||||
|
||||
if cfg.Parser.AutoHeadingID {
|
||||
parserOptions = append(parserOptions, parser.WithAutoHeadingID())
|
||||
}
|
||||
|
||||
if cfg.Parser.Attribute {
|
||||
parserOptions = append(parserOptions, parser.WithAttribute())
|
||||
}
|
||||
|
||||
md := goldmark.New(
|
||||
goldmark.WithExtensions(
|
||||
extensions...,
|
||||
),
|
||||
goldmark.WithParserOptions(
|
||||
parserOptions...,
|
||||
),
|
||||
goldmark.WithRendererOptions(
|
||||
rendererOptions...,
|
||||
),
|
||||
)
|
||||
|
||||
return md
|
||||
|
||||
}
|
||||
|
||||
type converterResult struct {
|
||||
converter.Result
|
||||
toc tableofcontents.Root
|
||||
}
|
||||
|
||||
func (c converterResult) TableOfContents() tableofcontents.Root {
|
||||
return c.toc
|
||||
}
|
||||
|
||||
func (c *goldmarkConverter) Convert(ctx converter.RenderContext) (result converter.Result, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
dir := afero.GetTempDir(hugofs.Os, "hugo_bugs")
|
||||
name := fmt.Sprintf("goldmark_%s.txt", c.ctx.DocumentID)
|
||||
filename := filepath.Join(dir, name)
|
||||
afero.WriteFile(hugofs.Os, filename, ctx.Src, 07555)
|
||||
err = errors.Errorf("[BUG] goldmark: create an issue on GitHub attaching the file in: %s", filename)
|
||||
|
||||
}
|
||||
}()
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
result = buf
|
||||
pctx := parser.NewContext()
|
||||
pctx.Set(tocEnableKey, ctx.RenderTOC)
|
||||
|
||||
reader := text.NewReader(ctx.Src)
|
||||
|
||||
doc := c.md.Parser().Parse(
|
||||
reader,
|
||||
parser.WithContext(pctx),
|
||||
)
|
||||
|
||||
if err := c.md.Renderer().Render(buf, ctx.Src, doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if toc, ok := pctx.Get(tocResultKey).(tableofcontents.Root); ok {
|
||||
return converterResult{
|
||||
Result: buf,
|
||||
toc: toc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func newHighlighting(cfg highlight.Config) goldmark.Extender {
|
||||
style := styles.Get(cfg.Style)
|
||||
if style == nil {
|
||||
style = styles.Fallback
|
||||
}
|
||||
|
||||
e := hl.NewHighlighting(
|
||||
hl.WithStyle(cfg.Style),
|
||||
hl.WithCodeBlockOptions(highlight.GetCodeBlockOptions()),
|
||||
hl.WithFormatOptions(
|
||||
cfg.ToHTMLOptions()...,
|
||||
),
|
||||
|
||||
hl.WithWrapperRenderer(func(w util.BufWriter, ctx hl.CodeBlockContext, entering bool) {
|
||||
l, hasLang := ctx.Language()
|
||||
var language string
|
||||
if hasLang {
|
||||
language = string(l)
|
||||
}
|
||||
|
||||
if entering {
|
||||
if !ctx.Highlighted() {
|
||||
w.WriteString(`<pre>`)
|
||||
highlight.WriteCodeTag(w, language)
|
||||
return
|
||||
}
|
||||
w.WriteString(`<div class="highlight">`)
|
||||
return
|
||||
}
|
||||
|
||||
if !ctx.Highlighted() {
|
||||
w.WriteString(`</code></pre>`)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteString("</div>")
|
||||
|
||||
}),
|
||||
)
|
||||
|
||||
return e
|
||||
}
|
219
markup/goldmark/convert_test.go
Normal file
219
markup/goldmark/convert_test.go
Normal file
@@ -0,0 +1,219 @@
|
||||
// Copyright 2019 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package goldmark
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/highlight"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/markup_config"
|
||||
|
||||
"github.com/gohugoio/hugo/common/loggers"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/converter"
|
||||
|
||||
qt "github.com/frankban/quicktest"
|
||||
)
|
||||
|
||||
func TestConvert(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
|
||||
// Smoke test of the default configuration.
|
||||
content := `
|
||||
## Code Fences
|
||||
|
||||
§§§bash
|
||||
LINE1
|
||||
§§§
|
||||
|
||||
## Code Fences No Lexer
|
||||
|
||||
§§§moo
|
||||
LINE1
|
||||
§§§
|
||||
|
||||
## Custom ID {#custom}
|
||||
|
||||
## Auto ID
|
||||
|
||||
* Autolink: https://gohugo.io/
|
||||
* Strikethrough:~~Hi~~ Hello, world!
|
||||
|
||||
## Table
|
||||
|
||||
| foo | bar |
|
||||
| --- | --- |
|
||||
| baz | bim |
|
||||
|
||||
## Task Lists (default on)
|
||||
|
||||
- [x] Finish my changes[^1]
|
||||
- [ ] Push my commits to GitHub
|
||||
- [ ] Open a pull request
|
||||
|
||||
|
||||
## Smartypants (default on)
|
||||
|
||||
* Straight double "quotes" and single 'quotes' into “curly” quote HTML entities
|
||||
* Dashes (“--” and “---”) into en- and em-dash entities
|
||||
* Three consecutive dots (“...”) into an ellipsis entity
|
||||
|
||||
## Footnotes
|
||||
|
||||
That's some text with a footnote.[^1]
|
||||
|
||||
## Definition Lists
|
||||
|
||||
date
|
||||
: the datetime assigned to this page.
|
||||
|
||||
description
|
||||
: the description for the content.
|
||||
|
||||
|
||||
[^1]: And that's the footnote.
|
||||
|
||||
`
|
||||
|
||||
// Code fences
|
||||
content = strings.Replace(content, "§§§", "```", -1)
|
||||
|
||||
mconf := markup_config.Default
|
||||
mconf.Highlight.NoClasses = false
|
||||
|
||||
p, err := Provider.New(
|
||||
converter.ProviderConfig{
|
||||
MarkupConfig: mconf,
|
||||
Logger: loggers.NewErrorLogger(),
|
||||
},
|
||||
)
|
||||
c.Assert(err, qt.IsNil)
|
||||
conv, err := p.New(converter.DocumentContext{})
|
||||
c.Assert(err, qt.IsNil)
|
||||
b, err := conv.Convert(converter.RenderContext{Src: []byte(content)})
|
||||
c.Assert(err, qt.IsNil)
|
||||
|
||||
got := string(b.Bytes())
|
||||
|
||||
// Header IDs
|
||||
c.Assert(got, qt.Contains, `<h2 id="custom">Custom ID</h2>`, qt.Commentf(got))
|
||||
c.Assert(got, qt.Contains, `<h2 id="auto-id">Auto ID</h2>`, qt.Commentf(got))
|
||||
|
||||
// Code fences
|
||||
c.Assert(got, qt.Contains, "<div class=\"highlight\"><pre class=\"chroma\"><code class=\"language-bash\" data-lang=\"bash\">LINE1\n</code></pre></div>")
|
||||
c.Assert(got, qt.Contains, "Code Fences No Lexer</h2>\n<pre><code class=\"language-moo\" data-lang=\"moo\">LINE1\n</code></pre>")
|
||||
|
||||
// Extensions
|
||||
c.Assert(got, qt.Contains, `Autolink: <a href="https://gohugo.io/">https://gohugo.io/</a>`)
|
||||
c.Assert(got, qt.Contains, `Strikethrough:<del>Hi</del> Hello, world`)
|
||||
c.Assert(got, qt.Contains, `<th>foo</th>`)
|
||||
c.Assert(got, qt.Contains, `<li><input disabled="" type="checkbox">Push my commits to GitHub</li>`)
|
||||
|
||||
c.Assert(got, qt.Contains, `Straight double “quotes” and single ‘quotes’`)
|
||||
c.Assert(got, qt.Contains, `Dashes (“–” and “—”) `)
|
||||
c.Assert(got, qt.Contains, `Three consecutive dots (“…”)`)
|
||||
c.Assert(got, qt.Contains, `footnote.<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>`)
|
||||
c.Assert(got, qt.Contains, `<section class="footnotes" role="doc-endnotes">`)
|
||||
c.Assert(got, qt.Contains, `<dt>date</dt>`)
|
||||
|
||||
}
|
||||
|
||||
func TestCodeFence(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
|
||||
lines := `LINE1
|
||||
LINE2
|
||||
LINE3
|
||||
LINE4
|
||||
LINE5
|
||||
`
|
||||
|
||||
convertForConfig := func(c *qt.C, conf highlight.Config, code, language string) string {
|
||||
mconf := markup_config.Default
|
||||
mconf.Highlight = conf
|
||||
|
||||
p, err := Provider.New(
|
||||
converter.ProviderConfig{
|
||||
MarkupConfig: mconf,
|
||||
Logger: loggers.NewErrorLogger(),
|
||||
},
|
||||
)
|
||||
|
||||
content := "```" + language + "\n" + code + "\n```"
|
||||
|
||||
c.Assert(err, qt.IsNil)
|
||||
conv, err := p.New(converter.DocumentContext{})
|
||||
c.Assert(err, qt.IsNil)
|
||||
b, err := conv.Convert(converter.RenderContext{Src: []byte(content)})
|
||||
c.Assert(err, qt.IsNil)
|
||||
|
||||
return string(b.Bytes())
|
||||
}
|
||||
|
||||
c.Run("Basic", func(c *qt.C) {
|
||||
cfg := highlight.DefaultConfig
|
||||
cfg.NoClasses = false
|
||||
|
||||
result := convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "bash")
|
||||
// TODO(bep) there is a whitespace mismatch (\n) between this and the highlight template func.
|
||||
c.Assert(result, qt.Equals, `<div class="highlight"><pre class="chroma"><code class="language-bash" data-lang="bash"><span class="nb">echo</span> <span class="s2">"Hugo Rocks!"</span>
|
||||
</code></pre></div>`)
|
||||
result = convertForConfig(c, cfg, `echo "Hugo Rocks!"`, "unknown")
|
||||
c.Assert(result, qt.Equals, "<pre><code class=\"language-unknown\" data-lang=\"unknown\">echo "Hugo Rocks!"\n</code></pre>")
|
||||
|
||||
})
|
||||
|
||||
c.Run("Highlight lines, default config", func(c *qt.C) {
|
||||
cfg := highlight.DefaultConfig
|
||||
cfg.NoClasses = false
|
||||
|
||||
result := convertForConfig(c, cfg, lines, `bash {linenos=table,hl_lines=[2 "4-5"],linenostart=3}`)
|
||||
c.Assert(result, qt.Contains, "<div class=\"highlight\"><div class=\"chroma\">\n<table class=\"lntable\"><tr><td class=\"lntd\">\n<pre class=\"chroma\"><code><span class")
|
||||
c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">4")
|
||||
|
||||
result = convertForConfig(c, cfg, lines, "bash {linenos=inline,hl_lines=[2]}")
|
||||
c.Assert(result, qt.Contains, "<span class=\"ln\">2</span>LINE2\n</span>")
|
||||
c.Assert(result, qt.Not(qt.Contains), "<table")
|
||||
|
||||
result = convertForConfig(c, cfg, lines, "bash {linenos=true,hl_lines=[2]}")
|
||||
c.Assert(result, qt.Contains, "<table")
|
||||
c.Assert(result, qt.Contains, "<span class=\"hl\"><span class=\"lnt\">2\n</span>")
|
||||
})
|
||||
|
||||
c.Run("Highlight lines, linenumbers default on", func(c *qt.C) {
|
||||
cfg := highlight.DefaultConfig
|
||||
cfg.NoClasses = false
|
||||
cfg.LineNos = true
|
||||
|
||||
result := convertForConfig(c, cfg, lines, "bash")
|
||||
c.Assert(result, qt.Contains, "<span class=\"lnt\">2\n</span>")
|
||||
|
||||
result = convertForConfig(c, cfg, lines, "bash {linenos=false,hl_lines=[2]}")
|
||||
c.Assert(result, qt.Not(qt.Contains), "class=\"lnt\"")
|
||||
})
|
||||
|
||||
c.Run("Highlight lines, linenumbers default on, linenumbers in table default off", func(c *qt.C) {
|
||||
cfg := highlight.DefaultConfig
|
||||
cfg.NoClasses = false
|
||||
cfg.LineNos = true
|
||||
cfg.LineNumbersInTable = false
|
||||
|
||||
result := convertForConfig(c, cfg, lines, "bash")
|
||||
c.Assert(result, qt.Contains, "<span class=\"ln\">2</span>LINE2\n<")
|
||||
result = convertForConfig(c, cfg, lines, "bash {linenos=table}")
|
||||
c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>")
|
||||
})
|
||||
}
|
74
markup/goldmark/goldmark_config/config.go
Normal file
74
markup/goldmark/goldmark_config/config.go
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright 2019 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package goldmark_config holds Goldmark related configuration.
|
||||
package goldmark_config
|
||||
|
||||
// DefaultConfig holds the default Goldmark configuration.
|
||||
var Default = Config{
|
||||
Extensions: Extensions{
|
||||
Typographer: true,
|
||||
Footnote: true,
|
||||
DefinitionList: true,
|
||||
Table: true,
|
||||
Strikethrough: true,
|
||||
Linkify: true,
|
||||
TaskList: true,
|
||||
},
|
||||
Renderer: Renderer{
|
||||
Unsafe: false,
|
||||
},
|
||||
Parser: Parser{
|
||||
AutoHeadingID: true,
|
||||
Attribute: true,
|
||||
},
|
||||
}
|
||||
|
||||
// Config configures Goldmark.
|
||||
type Config struct {
|
||||
Renderer Renderer
|
||||
Parser Parser
|
||||
Extensions Extensions
|
||||
}
|
||||
|
||||
type Extensions struct {
|
||||
Typographer bool
|
||||
Footnote bool
|
||||
DefinitionList bool
|
||||
|
||||
// GitHub flavored markdown
|
||||
Table bool
|
||||
Strikethrough bool
|
||||
Linkify bool
|
||||
TaskList bool
|
||||
}
|
||||
|
||||
type Renderer struct {
|
||||
// Whether softline breaks should be rendered as '<br>'
|
||||
HardWraps bool
|
||||
|
||||
// XHTML instead of HTML5.
|
||||
XHTML bool
|
||||
|
||||
// Allow raw HTML etc.
|
||||
Unsafe bool
|
||||
}
|
||||
|
||||
type Parser struct {
|
||||
// Enables custom heading ids and
|
||||
// auto generated heading ids.
|
||||
AutoHeadingID bool
|
||||
|
||||
// Enables custom attributes.
|
||||
Attribute bool
|
||||
}
|
102
markup/goldmark/toc.go
Normal file
102
markup/goldmark/toc.go
Normal file
@@ -0,0 +1,102 @@
|
||||
// Copyright 2019 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package goldmark
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/tableofcontents"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
"github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
"github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
var (
|
||||
tocResultKey = parser.NewContextKey()
|
||||
tocEnableKey = parser.NewContextKey()
|
||||
)
|
||||
|
||||
type tocTransformer struct {
|
||||
}
|
||||
|
||||
func (t *tocTransformer) Transform(n *ast.Document, reader text.Reader, pc parser.Context) {
|
||||
if b, ok := pc.Get(tocEnableKey).(bool); !ok || !b {
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
toc tableofcontents.Root
|
||||
header tableofcontents.Header
|
||||
level int
|
||||
row = -1
|
||||
inHeading bool
|
||||
headingText bytes.Buffer
|
||||
)
|
||||
|
||||
ast.Walk(n, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
s := ast.WalkStatus(ast.WalkContinue)
|
||||
if n.Kind() == ast.KindHeading {
|
||||
if inHeading && !entering {
|
||||
header.Text = headingText.String()
|
||||
headingText.Reset()
|
||||
toc.AddAt(header, row, level-1)
|
||||
header = tableofcontents.Header{}
|
||||
inHeading = false
|
||||
return s, nil
|
||||
}
|
||||
|
||||
inHeading = true
|
||||
}
|
||||
|
||||
if !(inHeading && entering) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
switch n.Kind() {
|
||||
case ast.KindHeading:
|
||||
heading := n.(*ast.Heading)
|
||||
level = heading.Level
|
||||
|
||||
if level == 1 || row == -1 {
|
||||
row++
|
||||
}
|
||||
|
||||
id, found := heading.AttributeString("id")
|
||||
if found {
|
||||
header.ID = string(id.([]byte))
|
||||
}
|
||||
case ast.KindText:
|
||||
textNode := n.(*ast.Text)
|
||||
headingText.Write(textNode.Text(reader.Source()))
|
||||
}
|
||||
|
||||
return s, nil
|
||||
})
|
||||
|
||||
pc.Set(tocResultKey, toc)
|
||||
}
|
||||
|
||||
type tocExtension struct {
|
||||
}
|
||||
|
||||
func newTocExtension() goldmark.Extender {
|
||||
return &tocExtension{}
|
||||
}
|
||||
|
||||
func (e *tocExtension) Extend(m goldmark.Markdown) {
|
||||
m.Parser().AddOptions(parser.WithASTTransformers(util.Prioritized(&tocTransformer{}, 10)))
|
||||
}
|
76
markup/goldmark/toc_test.go
Normal file
76
markup/goldmark/toc_test.go
Normal file
@@ -0,0 +1,76 @@
|
||||
// Copyright 2019 The Hugo Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package goldmark converts Markdown to HTML using Goldmark.
|
||||
package goldmark
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/markup_config"
|
||||
|
||||
"github.com/gohugoio/hugo/common/loggers"
|
||||
|
||||
"github.com/gohugoio/hugo/markup/converter"
|
||||
|
||||
qt "github.com/frankban/quicktest"
|
||||
)
|
||||
|
||||
func TestToc(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
|
||||
content := `
|
||||
# Header 1
|
||||
|
||||
## First h2
|
||||
|
||||
Some text.
|
||||
|
||||
### H3
|
||||
|
||||
Some more text.
|
||||
|
||||
## Second h2
|
||||
|
||||
And then some.
|
||||
|
||||
### Second H3
|
||||
|
||||
#### First H4
|
||||
|
||||
`
|
||||
p, err := Provider.New(
|
||||
converter.ProviderConfig{
|
||||
MarkupConfig: markup_config.Default,
|
||||
Logger: loggers.NewErrorLogger()})
|
||||
c.Assert(err, qt.IsNil)
|
||||
conv, err := p.New(converter.DocumentContext{})
|
||||
c.Assert(err, qt.IsNil)
|
||||
b, err := conv.Convert(converter.RenderContext{Src: []byte(content), RenderTOC: true})
|
||||
c.Assert(err, qt.IsNil)
|
||||
got := b.(converter.TableOfContentsProvider).TableOfContents().ToHTML(2, 3)
|
||||
c.Assert(got, qt.Equals, `<nav id="TableOfContents">
|
||||
<ul>
|
||||
<li><a href="#first-h2">First h2</a>
|
||||
<ul>
|
||||
<li><a href="#h3">H3</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a href="#second-h2">Second h2</a>
|
||||
<ul>
|
||||
<li><a href="#second-h3">Second H3</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>`, qt.Commentf(got))
|
||||
}
|
Reference in New Issue
Block a user