toolbox/tui/stringutil.go

69 lines
918 B
Go
Raw Normal View History

2021-03-31 08:27:54 +00:00
package tui
import (
"strings"
"unicode"
)
// Split text into words or newlines.
func splitText(s string) [][]rune {
s = strings.TrimSpace(s)
r := []rune(s)
out := [][]rune{}
nextWord := func() []rune {
for i := range r {
if unicode.IsSpace(r[i]) {
ret := r[:i]
r = r[i:]
return ret
}
}
ret := r
r = r[:0]
return ret
}
nextSpaces := func() []rune {
for i := range r {
if !unicode.IsSpace(r[i]) {
ret := r[:i]
r = r[i:]
return ret
}
}
// Code should never reach these lines.
ret := r
r = r[:0]
return ret
}
for len(r) > 0 {
word := nextWord()
if len(word) != 0 {
out = append(out, word)
}
if len(r) == 0 {
break
}
spaces := nextSpaces()
count := 0
for _, x := range spaces {
if x == '\n' {
count++
}
if count > 1 {
break
}
}
if count > 1 {
out = append(out, []rune{'\n'})
}
}
return out
}