mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-30 22:39:58 +02:00
markup/goldmark: Add an optional Blackfriday auto ID strategy
Fixes #6707
This commit is contained in:
@@ -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 {
|
||||
|
@@ -179,3 +179,45 @@ This is a footnote.[^1] And then some.
|
||||
c.Assert(s, qt.Contains, "This is a footnote.<sup class=\"footnote-ref\" id=\"fnref:testid:1\"><a href=\"#fn:testid:1\">1</a></sup>")
|
||||
c.Assert(s, qt.Contains, "<a class=\"footnote-return\" href=\"#fnref:testid:1\"><sup>[return]</sup></a>")
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user