53 lines
952 B
Go
53 lines
952 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([]rune(w))
|
|
continue
|
|
}
|
|
|
|
maxw := width - restIndent
|
|
if len(lines) == 0 {
|
|
maxw = width - firstIndent
|
|
}
|
|
|
|
if lineLen+1+len([]rune(w)) > maxw {
|
|
lines = append(lines, strings.Join(currentLine, " "))
|
|
currentLine = []string{w}
|
|
lineLen = len([]rune(w))
|
|
continue
|
|
}
|
|
|
|
currentLine = append(currentLine, w)
|
|
lineLen += 1 + len([]rune(w))
|
|
}
|
|
|
|
lines = append(lines, strings.Join(currentLine, " "))
|
|
return strings.Join(lines, "\n")
|
|
}
|