anchors.go (1486B)
1 // Copyright 2022 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 blackfriday holds some copmpability functions for the old Blackfriday v1 Markdown engine.
15 package blackfriday
16
17 import "unicode"
18
19 // SanitizedAnchorName is how Blackfriday sanitizes anchor names.
20 // Implementation borrowed from https://github.com/russross/blackfriday/blob/a477dd1646916742841ed20379f941cfa6c5bb6f/block.go#L1464
21 // Note that Hugo removed its Blackfriday support in v0.100.0, but you can still use this strategy for
22 // auto ID generation.
23 func SanitizedAnchorName(text string) string {
24 var anchorName []rune
25 futureDash := false
26 for _, r := range text {
27 switch {
28 case unicode.IsLetter(r) || unicode.IsNumber(r):
29 if futureDash && len(anchorName) > 0 {
30 anchorName = append(anchorName, '-')
31 }
32 futureDash = false
33 anchorName = append(anchorName, unicode.ToLower(r))
34 default:
35 futureDash = true
36 }
37 }
38 return string(anchorName)
39 }