1
0
textfmt/wrap.go

53 lines
920 B
Go

package textfmt
import "strings"
func getWords(text string) []string {
var words []string
raw := strings.Split(text, " ")
for _, r := range raw {
if r == "" {
continue
}
words = append(words, r)
}
return words
}
func wrap(text string, width, firstIndent, restIndent int) string {
var (
lines []string
currentLine []string
lineLen int
)
words := getWords(text)
for _, w := range words {
if len(currentLine) == 0 {
currentLine = []string{w}
lineLen = len(w)
continue
}
maxw := width - restIndent
if len(lines) == 0 {
maxw = width - firstIndent
}
if lineLen+1+len(w) > maxw {
lines = append(lines, strings.Join(currentLine, " "))
currentLine = []string{w}
lineLen = len(w)
continue
}
currentLine = append(currentLine, w)
lineLen += 1 + len(w)
}
lines = append(lines, strings.Join(currentLine, " "))
return strings.Join(lines, "\n")
}