1
0
textfmt/wrap.go

53 lines
952 B
Go
Raw Normal View History

2025-09-11 21:16:09 +02:00
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
2025-10-10 15:47:36 +02:00
lineLen int
2025-09-11 21:16:09 +02:00
)
words := getWords(text)
for _, w := range words {
2025-10-10 15:47:36 +02:00
if len(currentLine) == 0 {
currentLine = []string{w}
2025-10-14 20:46:32 +02:00
lineLen = len([]rune(w))
2025-10-10 15:47:36 +02:00
continue
}
2025-09-11 21:16:09 +02:00
maxw := width - restIndent
if len(lines) == 0 {
maxw = width - firstIndent
}
2025-10-14 20:46:32 +02:00
if lineLen+1+len([]rune(w)) > maxw {
2025-09-11 21:16:09 +02:00
lines = append(lines, strings.Join(currentLine, " "))
currentLine = []string{w}
2025-10-14 20:46:32 +02:00
lineLen = len([]rune(w))
2025-10-10 15:47:36 +02:00
continue
2025-09-11 21:16:09 +02:00
}
2025-10-10 15:47:36 +02:00
currentLine = append(currentLine, w)
2025-10-14 20:46:32 +02:00
lineLen += 1 + len([]rune(w))
2025-09-11 21:16:09 +02:00
}
2025-10-10 15:47:36 +02:00
lines = append(lines, strings.Join(currentLine, " "))
2025-09-11 21:16:09 +02:00
return strings.Join(lines, "\n")
}