2020-01-04 10:28:19 +00:00
|
|
|
// 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 text
|
|
|
|
|
|
|
|
import (
|
2022-02-26 09:42:21 +00:00
|
|
|
"strings"
|
2020-01-04 10:28:19 +00:00
|
|
|
"sync"
|
|
|
|
"unicode"
|
|
|
|
|
|
|
|
"golang.org/x/text/runes"
|
|
|
|
"golang.org/x/text/transform"
|
|
|
|
"golang.org/x/text/unicode/norm"
|
|
|
|
)
|
|
|
|
|
|
|
|
var accentTransformerPool = &sync.Pool{
|
2022-03-17 21:03:27 +00:00
|
|
|
New: func() any {
|
2020-01-04 10:28:19 +00:00
|
|
|
return transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveAccents removes all accents from b.
|
|
|
|
func RemoveAccents(b []byte) []byte {
|
|
|
|
t := accentTransformerPool.Get().(transform.Transformer)
|
|
|
|
b, _, _ = transform.Bytes(t, b)
|
|
|
|
t.Reset()
|
|
|
|
accentTransformerPool.Put(t)
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveAccentsString removes all accents from s.
|
|
|
|
func RemoveAccentsString(s string) string {
|
|
|
|
t := accentTransformerPool.Get().(transform.Transformer)
|
|
|
|
s, _, _ = transform.String(t, s)
|
|
|
|
t.Reset()
|
|
|
|
accentTransformerPool.Put(t)
|
|
|
|
return s
|
|
|
|
}
|
2022-02-26 09:42:21 +00:00
|
|
|
|
|
|
|
// Chomp removes trailing newline characters from s.
|
|
|
|
func Chomp(s string) string {
|
|
|
|
return strings.TrimRightFunc(s, func(r rune) bool {
|
|
|
|
return r == '\n' || r == '\r'
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Puts adds a trailing \n none found.
|
|
|
|
func Puts(s string) string {
|
|
|
|
if s == "" || s[len(s)-1] == '\n' {
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
return s + "\n"
|
|
|
|
}
|
2022-05-28 11:18:50 +00:00
|
|
|
|
|
|
|
// VisitLinesAfter calls the given function for each line, including newlines, in the given string.
|
|
|
|
func VisitLinesAfter(s string, fn func(line string)) {
|
2022-05-29 14:41:57 +00:00
|
|
|
high := strings.IndexRune(s, '\n')
|
2022-05-28 11:18:50 +00:00
|
|
|
for high != -1 {
|
|
|
|
fn(s[:high+1])
|
|
|
|
s = s[high+1:]
|
2022-05-29 14:41:57 +00:00
|
|
|
|
|
|
|
high = strings.IndexRune(s, '\n')
|
2022-05-28 11:18:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if s != "" {
|
|
|
|
fn(s)
|
|
|
|
}
|
|
|
|
}
|