From 16e7c1120346bd853cf6510ffac8e94824bf2c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Sun, 5 Jan 2020 11:52:00 +0100 Subject: markup/goldmark: Add an optional Blackfriday auto ID strategy Fixes #6707 --- markup/blackfriday/convert.go | 24 +++++++++++++++++++++- markup/blackfriday/convert_test.go | 42 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) (limited to 'markup/blackfriday') diff --git a/markup/blackfriday/convert.go b/markup/blackfriday/convert.go index bbbc2b377..d844c5554 100644 --- a/markup/blackfriday/convert.go +++ b/markup/blackfriday/convert.go @@ -15,6 +15,8 @@ package blackfriday import ( + "unicode" + "github.com/gohugoio/hugo/identity" "github.com/gohugoio/hugo/markup/blackfriday/blackfriday_config" "github.com/gohugoio/hugo/markup/converter" @@ -61,7 +63,27 @@ type blackfridayConverter struct { } func (c *blackfridayConverter) SanitizeAnchorName(s string) string { - return blackfriday.SanitizedAnchorName(s) + return SanitizedAnchorName(s) +} + +// SanitizedAnchorName is how Blackfriday sanitizes anchor names. +// Implementation borrowed from https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L1464 +func SanitizedAnchorName(text string) string { + var anchorName []rune + futureDash := false + for _, r := range text { + switch { + case unicode.IsLetter(r) || unicode.IsNumber(r): + if futureDash && len(anchorName) > 0 { + anchorName = append(anchorName, '-') + } + futureDash = false + anchorName = append(anchorName, unicode.ToLower(r)) + default: + futureDash = true + } + } + return string(anchorName) } func (c *blackfridayConverter) AnchorSuffix() string { diff --git a/markup/blackfriday/convert_test.go b/markup/blackfriday/convert_test.go index b4d66dec6..d2d8d927e 100644 --- a/markup/blackfriday/convert_test.go +++ b/markup/blackfriday/convert_test.go @@ -179,3 +179,45 @@ This is a footnote.[^1] And then some. c.Assert(s, qt.Contains, "This is a footnote.1") c.Assert(s, qt.Contains, "[return]") } + +// Tests borrowed from https://github.com/russross/blackfriday/blob/a925a152c144ea7de0f451eaf2f7db9e52fa005a/block_test.go#L1817 +func TestSanitizedAnchorName(t *testing.T) { + tests := []struct { + text string + want string + }{ + { + text: "This is a header", + want: "this-is-a-header", + }, + { + text: "This is also a header", + want: "this-is-also-a-header", + }, + { + text: "main.go", + want: "main-go", + }, + { + text: "Article 123", + want: "article-123", + }, + { + text: "<- Let's try this, shall we?", + want: "let-s-try-this-shall-we", + }, + { + text: " ", + want: "", + }, + { + text: "Hello, 世界", + want: "hello-世界", + }, + } + for _, test := range tests { + if got := SanitizedAnchorName(test.text); got != test.want { + t.Errorf("SanitizedAnchorName(%q):\ngot %q\nwant %q", test.text, got, test.want) + } + } +} -- cgit v1.2.3