diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-11-06 20:10:47 +0100 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2019-11-23 14:12:24 +0100 |
commit | bfb9613a14ab2d93a4474e5486d22e52a9d5e2b3 (patch) | |
tree | 81c4dbd10505e952489e1dbcf1d7bafc88b57c28 /markup | |
parent | a3fe5e5e35f311f22b6b4fc38abfcf64cd2c7d6f (diff) |
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
Diffstat (limited to 'markup')
30 files changed, 2686 insertions, 240 deletions
diff --git a/markup/asciidoc/convert.go b/markup/asciidoc/convert.go index 9e63911d8..65fdde0f5 100644 --- a/markup/asciidoc/convert.go +++ b/markup/asciidoc/convert.go @@ -24,19 +24,18 @@ import ( ) // Provider is the package entry point. -var Provider converter.NewProvider = provider{} +var Provider converter.ProviderProvider = provider{} type provider struct { } func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) { - var n converter.NewConverter = func(ctx converter.DocumentContext) (converter.Converter, error) { + return converter.NewProvider("asciidoc", func(ctx converter.DocumentContext) (converter.Converter, error) { return &asciidocConverter{ ctx: ctx, cfg: cfg, }, nil - } - return n, nil + }), nil } type asciidocConverter struct { diff --git a/markup/blackfriday/blackfriday_config/config.go b/markup/blackfriday/blackfriday_config/config.go new file mode 100644 index 000000000..f26f7c570 --- /dev/null +++ b/markup/blackfriday/blackfriday_config/config.go @@ -0,0 +1,70 @@ +// 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 helpers implements general utility functions that work with +// and on content. The helper functions defined here lay down the +// foundation of how Hugo works with files and filepaths, and perform +// string operations on content. + +package blackfriday_config + +import ( + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" +) + +// Default holds the default BlackFriday config. +// Do not change! +var Default = Config{ + Smartypants: true, + AngledQuotes: false, + SmartypantsQuotesNBSP: false, + Fractions: true, + HrefTargetBlank: false, + NofollowLinks: false, + NoreferrerLinks: false, + SmartDashes: true, + LatexDashes: true, + PlainIDAnchors: true, + TaskLists: true, + SkipHTML: false, +} + +// Config holds configuration values for BlackFriday rendering. +// It is kept here because it's used in several packages. +type Config struct { + Smartypants bool + SmartypantsQuotesNBSP bool + AngledQuotes bool + Fractions bool + HrefTargetBlank bool + NofollowLinks bool + NoreferrerLinks bool + SmartDashes bool + LatexDashes bool + TaskLists bool + PlainIDAnchors bool + Extensions []string + ExtensionsMask []string + SkipHTML bool + + FootnoteAnchorPrefix string + FootnoteReturnLinkContents string +} + +func UpdateConfig(b Config, m map[string]interface{}) (Config, error) { + if err := mapstructure.Decode(m, &b); err != nil { + return b, errors.WithMessage(err, "failed to decode rendering config") + } + return b, nil +} diff --git a/markup/blackfriday/convert.go b/markup/blackfriday/convert.go index f9d957a4e..350defcb6 100644 --- a/markup/blackfriday/convert.go +++ b/markup/blackfriday/convert.go @@ -15,36 +15,27 @@ package blackfriday import ( + "github.com/gohugoio/hugo/markup/blackfriday/blackfriday_config" "github.com/gohugoio/hugo/markup/converter" - "github.com/gohugoio/hugo/markup/internal" "github.com/russross/blackfriday" ) // Provider is the package entry point. -var Provider converter.NewProvider = provider{} +var Provider converter.ProviderProvider = provider{} type provider struct { } func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) { - defaultBlackFriday, err := internal.NewBlackfriday(cfg) - if err != nil { - return nil, err - } - - defaultExtensions := getMarkdownExtensions(defaultBlackFriday) - - pygmentsCodeFences := cfg.Cfg.GetBool("pygmentsCodeFences") - pygmentsCodeFencesGuessSyntax := cfg.Cfg.GetBool("pygmentsCodeFencesGuessSyntax") - pygmentsOptions := cfg.Cfg.GetString("pygmentsOptions") + defaultExtensions := getMarkdownExtensions(cfg.MarkupConfig.BlackFriday) - var n converter.NewConverter = func(ctx converter.DocumentContext) (converter.Converter, error) { - b := defaultBlackFriday + return converter.NewProvider("blackfriday", func(ctx converter.DocumentContext) (converter.Converter, error) { + b := cfg.MarkupConfig.BlackFriday extensions := defaultExtensions if ctx.ConfigOverrides != nil { var err error - b, err = internal.UpdateBlackFriday(b, ctx.ConfigOverrides) + b, err = blackfriday_config.UpdateConfig(b, ctx.ConfigOverrides) if err != nil { return nil, err } @@ -56,27 +47,16 @@ func (p provider) New(cfg converter.ProviderConfig) (converter.Provider, error) bf: b, extensions: extensions, cfg: cfg, - - pygmentsCodeFences: pygmentsCodeFences, - pygmentsCodeFencesGuessSyntax: pygmentsCodeFencesGuessSyntax, - pygmentsOptions: pygmentsOptions, }, nil - } - - return n, nil + }), nil } type blackfridayConverter struct { ctx converter.DocumentContext - bf *internal.BlackFriday + bf blackfriday_config.Config extensions int - - pygmentsCodeFences bool - pygmentsCodeFencesGuessSyntax bool - pygmentsOptions string - - cfg converter.ProviderConfig + cfg converter.ProviderConfig } func (c *blackfridayConverter) AnchorSuffix() string { @@ -90,7 +70,6 @@ func (c *blackfridayConverter) Convert(ctx converter.RenderContext) (converter.R r := c.getHTMLRenderer(ctx.RenderTOC) return converter.Bytes(blackfriday.Markdown(ctx.Src, r, c.extensions)), nil - } func (c *blackfridayConverter) getHTMLRenderer(renderTOC bool) blackfriday.Renderer { @@ -114,7 +93,7 @@ func (c *blackfridayConverter) getHTMLRenderer(renderTOC bool) blackfriday.Rende } } -func getFlags(renderTOC bool, cfg *internal.BlackFriday) int { +func getFlags(renderTOC bool, cfg blackfriday_config.Config) int { var flags int @@ -168,7 +147,7 @@ func getFlags(renderTOC bool, cfg *internal.BlackFriday) int { return flags } -func getMarkdownExtensions(cfg *internal.BlackFriday) int { +func getMarkdownExtensions(cfg blackfriday_config.Config) int { // Default Blackfriday common extensions commonExtensions := 0 | blackfriday.EXTENSION_NO_INTRA_EMPHASIS | diff --git a/markup/blackfriday/convert_test.go b/markup/blackfriday/convert_test.go index 094edf35f..b4d66dec6 100644 --- a/markup/blackfriday/convert_test.go +++ b/markup/blackfriday/convert_test.go @@ -18,19 +18,15 @@ import ( "github.com/spf13/viper" - "github.com/gohugoio/hugo/markup/internal" - "github.com/gohugoio/hugo/markup/converter" qt "github.com/frankban/quicktest" + "github.com/gohugoio/hugo/markup/blackfriday/blackfriday_config" "github.com/russross/blackfriday" ) func TestGetMarkdownExtensionsMasksAreRemovedFromExtensions(t *testing.T) { - c := qt.New(t) - b, err := internal.NewBlackfriday(converter.ProviderConfig{Cfg: viper.New()}) - c.Assert(err, qt.IsNil) - + b := blackfriday_config.Default b.Extensions = []string{"headerId"} b.ExtensionsMask = []string{"noIntraEmphasis"} @@ -45,9 +41,7 @@ func TestGetMarkdownExtensionsByDefaultAllExtensionsAreEnabled(t *testing.T) { testFlag int } - c := qt.New(t) - b, err := internal.NewBlackfriday(converter.ProviderConfig{Cfg: viper.New()}) - c.Assert(err, qt.IsNil) + b := blackfriday_config.Default b.Extensions = []string{""} b.ExtensionsMask = []string{""} @@ -79,9 +73,7 @@ func TestGetMarkdownExtensionsByDefaultAllExtensionsAreEnabled(t *testing.T) { } func TestGetMarkdownExtensionsAddingFlagsThroughRenderingContext(t *testing.T) { - c := qt.New(t) - b, err := internal.NewBlackfriday(converter.ProviderConfig{Cfg: viper.New()}) - c.Assert(err, qt.IsNil) + b := blackfriday_config.Default b.Extensions = []string{"definitionLists"} b.ExtensionsMask = []string{""} @@ -93,10 +85,7 @@ func TestGetMarkdownExtensionsAddingFlagsThroughRenderingContext(t *testing.T) { } func TestGetFlags(t *testing.T) { - c := qt.New(t) - cfg := converter.ProviderConfig{Cfg: viper.New()} - b, err := internal.NewBlackfriday(cfg) - c.Assert(err, qt.IsNil) + b := blackfriday_config.Default flags := getFlags(false, b) if flags&blackfriday.HTML_USE_XHTML != blackfriday.HTML_USE_XHTML { t.Errorf("Test flag: %d was not found amongs set flags:%d; Result: %d", blackfriday.HTML_USE_XHTML, flags, flags&blackfriday.HTML_USE_XHTML) @@ -105,9 +94,8 @@ func TestGetFlags(t *testing.T) { func TestGetAllFlags(t *testing.T) { c := qt.New(t) - cfg := converter.ProviderConfig{Cfg: viper.New()} - b, err := internal.NewBlackfriday(cfg) - c.Assert(err, qt.IsNil) + + b := blackfriday_config.Default type data struct { testFlag int @@ -145,9 +133,8 @@ func TestGetAllFlags(t *testing.T) { for _, d := range allFlags { expectedFlags |= d.testFlag } - if expectedFlags != actualFlags { - t.Errorf("Expected flags (%d) did not equal actual (%d) flags.", expectedFlags, actualFlags) - } + + c.Assert(actualFlags, qt.Equals, expectedFlags) } func TestConvert(t *testing.T) { diff --git a/markup/blackfriday/renderer.go b/markup/blackfriday/renderer.go index 9f4d44e02..a46e46b55 100644 --- a/markup/blackfriday/renderer.go +++ b/markup/blackfriday/renderer.go @@ -30,10 +30,9 @@ type hugoHTMLRenderer struct { // BlockCode renders a given text as a block of code. // Pygments is used if it is setup to handle code fences. func (r *hugoHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string) { - if r.c.pygmentsCodeFences && (lang != "" || r.c.pygmentsCodeFencesGuessSyntax) { - opts := r.c.pygmentsOptions + if r.c.cfg.MarkupConfig.Highlight.CodeFences { str := strings.Trim(string(text), "\n\r") - highlighted, _ := r.c.cfg.Highlight(str, lang, opts) + highlighted, _ := r.c.cfg.Highlight(str, lang, "") out.WriteString(highlighted) } else { r.Renderer.BlockCode(out, text, lang) diff --git a/markup/converter/converter.go b/markup/converter/converter.go index 809efca8e..a1141f65c 100644 --- a/markup/converter/converter.go +++ b/markup/converter/converter.go @@ -16,33 +16,51 @@ package converter import ( "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/config" + "github.com/gohugoio/hugo/markup/markup_config" + "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/spf13/afero" ) // ProviderConfig configures a new Provider. type ProviderConfig struct { + MarkupConfig markup_config.Config + Cfg config.Provider // Site config ContentFs afero.Fs Logger *loggers.Logger Highlight func(code, lang, optsStr string) (string, error) } -// NewProvider creates converter providers. -type NewProvider interface { +// ProviderProvider creates converter providers. +type ProviderProvider interface { New(cfg ProviderConfig) (Provider, error) } // Provider creates converters. type Provider interface { New(ctx DocumentContext) (Converter, error) + Name() string +} + +// NewProvider creates a new Provider with the given name. +func NewProvider(name string, create func(ctx DocumentContext) (Converter, error)) Provider { + return newConverter{ + name: name, + create: create, + } +} + +type newConverter struct { + name string + create func(ctx DocumentContext) (Converter, error) } -// NewConverter is an adapter that can be used as a ConverterProvider. -type NewConverter func(ctx DocumentContext) (Converter, error) +func (n newConverter) New(ctx DocumentContext) (Converter, error) { + return n.create(ctx) +} -// New creates a new Converter for the given ctx. -func (n NewConverter) New(ctx DocumentContext) (Converter, error) { - return n(ctx) +func (n newConverter) Name() string { + return n.name } // Converter wraps the Convert method that converts some markup into @@ -61,6 +79,11 @@ type DocumentInfo interface { AnchorSuffix() string } +// TableOfContentsProvider provides the content as a ToC structure. +type TableOfContentsProvider interface { + TableOfContents() tableofcontents.Root +} + // Bytes holds a byte slice and implements the Result interface. type Bytes []byte diff --git a/markup/goldmark/convert.go b/markup/goldmark/convert.go new file mode 100644 index 000000000..6c9a3771a --- /dev/null +++ b/markup/goldmark/convert.go @@ -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 +} diff --git a/markup/goldmark/convert_test.go b/markup/goldmark/convert_test.go new file mode 100644 index 000000000..47798660d --- /dev/null +++ b/markup/goldmark/convert_test.go @@ -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 |