trim.go

 1package text
 2
 3import (
 4	"strings"
 5	"unicode"
 6)
 7
 8// TrimSpace remove the leading and trailing whitespace while ignoring the
 9// terminal escape sequences.
10// Returns the number of trimmed space on both side.
11func TrimSpace(line string) string {
12	cleaned, escapes := ExtractTermEscapes(line)
13
14	// trim left while counting
15	left := 0
16	trimmed := strings.TrimLeftFunc(cleaned, func(r rune) bool {
17		if unicode.IsSpace(r) {
18			left++
19			return true
20		}
21		return false
22	})
23
24	trimmed = strings.TrimRightFunc(trimmed, unicode.IsSpace)
25
26	escapes = OffsetEscapes(escapes, -left)
27	return ApplyTermEscapes(trimmed, escapes)
28}