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}
|
|
|
|
|
lineLen = len(w)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-11 21:16:09 +02:00
|
|
|
maxw := width - restIndent
|
|
|
|
|
if len(lines) == 0 {
|
|
|
|
|
maxw = width - firstIndent
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-10 15:47:36 +02:00
|
|
|
if lineLen+1+len(w) > maxw {
|
2025-09-11 21:16:09 +02:00
|
|
|
lines = append(lines, strings.Join(currentLine, " "))
|
|
|
|
|
currentLine = []string{w}
|
2025-10-10 15:47:36 +02:00
|
|
|
lineLen = len(w)
|
|
|
|
|
continue
|
2025-09-11 21:16:09 +02:00
|
|
|
}
|
|
|
|
|
|
2025-10-10 15:47:36 +02:00
|
|
|
currentLine = append(currentLine, w)
|
|
|
|
|
lineLen += 1 + len(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")
|
|
|
|
|
}
|