1
0
mirror of https://github.com/alecthomas/chroma.git synced 2025-07-01 00:35:06 +02:00

Add new TokeniseOption EnsureLF (#336)

* Add new TokeniseOption EnsureLF

ref #329

* Use efficient process suggested by @chmike
This commit is contained in:
satotake
2020-03-04 16:56:47 +09:00
committed by GitHub
parent e5d9650a20
commit 34d9c7143b
3 changed files with 84 additions and 1 deletions

View File

@ -410,6 +410,9 @@ func (r *RegexLexer) Tokenise(options *TokeniseOptions, text string) (Iterator,
if options == nil {
options = defaultOptions
}
if options.EnsureLF {
text = ensureLF(text)
}
if !options.Nested && r.config.EnsureNL && !strings.HasSuffix(text, "\n") {
text += "\n"
}
@ -437,3 +440,22 @@ func matchRules(text []rune, pos int, rules []*CompiledRule) (int, *CompiledRule
}
return 0, &CompiledRule{}, nil
}
// replace \r and \r\n with \n
// same as strings.ReplaceAll but more efficient
func ensureLF(text string) string {
buf := make([]byte, len(text))
var j int
for i := 0; i < len(text); i++ {
c := text[i]
if c == '\r' {
if i < len(text)-1 && text[i+1] == '\n' {
continue
}
c = '\n'
}
buf[j] = c
j++
}
return string(buf[:j])
}