76 lines
1.2 KiB
Go
76 lines
1.2 KiB
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 lineLength(words []string) int {
|
||
|
|
if len(words) == 0 {
|
||
|
|
return 0
|
||
|
|
}
|
||
|
|
|
||
|
|
var l int
|
||
|
|
for _, w := range words {
|
||
|
|
r := []rune(w)
|
||
|
|
l += len(r)
|
||
|
|
}
|
||
|
|
|
||
|
|
return l + len(words) - 1
|
||
|
|
}
|
||
|
|
|
||
|
|
func singleLine(text string) string {
|
||
|
|
var l []string
|
||
|
|
p := strings.Split(text, "\n")
|
||
|
|
for _, part := range p {
|
||
|
|
part = strings.TrimSpace(part)
|
||
|
|
if part == "" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
l = append(l, part)
|
||
|
|
}
|
||
|
|
|
||
|
|
return strings.Join(l, " ")
|
||
|
|
}
|
||
|
|
|
||
|
|
func wrap(text string, width, firstIndent, restIndent int) string {
|
||
|
|
var (
|
||
|
|
lines []string
|
||
|
|
currentLine []string
|
||
|
|
currentLen int
|
||
|
|
)
|
||
|
|
|
||
|
|
words := getWords(text)
|
||
|
|
for _, w := range words {
|
||
|
|
maxw := width - restIndent
|
||
|
|
if len(lines) == 0 {
|
||
|
|
maxw = width - firstIndent
|
||
|
|
}
|
||
|
|
|
||
|
|
currentLine = append(currentLine, w)
|
||
|
|
if lineLength(currentLine) > maxw {
|
||
|
|
currentLine = currentLine[:len(currentLine)-1]
|
||
|
|
lines = append(lines, strings.Join(currentLine, " "))
|
||
|
|
currentLine = []string{w}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if len(currentLine) > 0 {
|
||
|
|
lines = append(lines, strings.Join(currentLine, " "))
|
||
|
|
}
|
||
|
|
|
||
|
|
return strings.Join(lines, "\n")
|
||
|
|
}
|