toolbox/tui/wordwrap.go
2021-03-31 10:27:54 +02:00

61 lines
1.1 KiB
Go

package tui
import "strings"
// WrapText takes the text in s and wraps it to the width. It returns the
// individual wrapped lines, and the length of the longest wrapped line.
//
// If the width is less than or equal to zero, it is set to the terminal width.
//
// In order to wrap the text in a reasonable way, white space is trimmed and
// collapsed througout the text.
func WrapText(s string, width int) ([]string, int) {
w := width
if w <= 0 {
w, _ = TermSize()
}
maxLine := 0
parts := splitText(s)
nextLine := func() (string, int) {
if parts[0][0] == '\n' {
parts = parts[1:]
return "", 0
}
words := append([]string{}, string(parts[0]))
length := len(parts[0])
parts = parts[1:]
for len(parts) > 0 {
p := parts[0]
if p[0] == '\n' {
break
}
if length+len(p)+1 > w {
break
}
length += len(p) + 1
words = append(words, string(p))
parts = parts[1:]
}
return strings.Join(words, " "), length
}
lines := make([]string, 0, 2)
for len(parts) > 0 {
line, lineLen := nextLine()
if lineLen > maxLine {
maxLine = lineLen
}
lines = append(lines, line)
}
return lines, maxLine
}