Change auto heading ID generation logic

- expand to international characters
- change one or more consecutive spaces to hyphen
- change period, hyphen, and underscore to hyphen
This commit is contained in:
jkboxomine 2019-12-06 00:07:40 +09:00
parent 171dbc66a8
commit 2f7a4aa9c4

View file

@ -5,6 +5,8 @@ import (
"fmt" "fmt"
"strings" "strings"
"sync" "sync"
"unicode"
"unicode/utf8"
"github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text" "github.com/yuin/goldmark/text"
@ -76,21 +78,41 @@ func (s *ids) Generate(value []byte, kind ast.NodeKind) []byte {
value = util.TrimLeftSpace(value) value = util.TrimLeftSpace(value)
value = util.TrimRightSpace(value) value = util.TrimRightSpace(value)
result := []byte{} result := []byte{}
for i := 0; i < len(value); { for len(value) > 0 {
v := value[i] r, size := utf8.DecodeRune(value)
l := util.UTF8Len(v) if unicode.IsLetter(r) {
i += int(l) if unicode.IsUpper(r) {
if l != 1 { r = unicode.ToLower(r)
}
buf := make([]byte, size)
utf8.EncodeRune(buf, r)
for i := 0; i < size; i++ {
result = append(result, buf[i])
}
} else if unicode.IsNumber(r) || unicode.IsSymbol(r) {
buf := make([]byte, size)
utf8.EncodeRune(buf, r)
for i := 0; i < size; i++ {
result = append(result, buf[i])
}
} else if unicode.IsSpace(r) {
nr, nsize := utf8.DecodeRune(value[size:])
_ = nsize
if unicode.IsSpace(nr) {
value = value[size:]
continue continue
} } else {
if util.IsAlphaNumeric(v) {
if 'A' <= v && v <= 'Z' {
v += 'a' - 'A'
}
result = append(result, v)
} else if util.IsSpace(v) || v == '-' || v == '_' {
result = append(result, '-') result = append(result, '-')
} }
} else if unicode.IsPunct(r) {
if r == '.' || r == '-' || r == '_' {
result = append(result, '-')
}
} else {
value = value[size:]
continue
}
value = value[size:]
} }
if len(result) == 0 { if len(result) == 0 {
if kind == ast.KindHeading { if kind == ast.KindHeading {