90 lines
1.3 KiB
Go
90 lines
1.3 KiB
Go
package html
|
|
|
|
import (
|
|
"bytes"
|
|
"unicode"
|
|
)
|
|
|
|
func words(buf *bytes.Buffer) []string {
|
|
var (
|
|
words []string
|
|
currentWord []rune
|
|
inTag bool
|
|
)
|
|
|
|
for {
|
|
r, _, err := buf.ReadRune()
|
|
if err != nil {
|
|
break
|
|
}
|
|
|
|
if r == unicode.ReplacementChar {
|
|
continue
|
|
}
|
|
|
|
if !inTag && unicode.IsSpace(r) {
|
|
if len(currentWord) > 0 {
|
|
words, currentWord = append(words, string(currentWord)), nil
|
|
}
|
|
|
|
continue
|
|
}
|
|
|
|
currentWord = append(currentWord, r)
|
|
inTag = inTag && r != '>' || r == '<'
|
|
}
|
|
|
|
if len(currentWord) > 0 {
|
|
words = append(words, string(currentWord))
|
|
}
|
|
|
|
return words
|
|
}
|
|
|
|
func wrap(buf *bytes.Buffer, pwidth int, indent string) *bytes.Buffer {
|
|
var (
|
|
lines [][]string
|
|
currentLine []string
|
|
currentLen int
|
|
)
|
|
|
|
words := words(buf)
|
|
for _, w := range words {
|
|
if currentLen != 0 {
|
|
currentLen++
|
|
}
|
|
|
|
currentLen += len(w)
|
|
if currentLen > pwidth && len(currentLine) > 0 {
|
|
lines = append(lines, currentLine)
|
|
currentLine = []string{w}
|
|
currentLen = len(w)
|
|
continue
|
|
}
|
|
|
|
currentLine = append(currentLine, w)
|
|
}
|
|
|
|
if len(currentLine) > 0 {
|
|
lines = append(lines, currentLine)
|
|
}
|
|
|
|
ret := bytes.NewBuffer(nil)
|
|
for i, l := range lines {
|
|
if i > 0 {
|
|
ret.WriteRune('\n')
|
|
}
|
|
|
|
ret.WriteString(indent)
|
|
for j, w := range l {
|
|
if j > 0 {
|
|
ret.WriteRune(' ')
|
|
}
|
|
|
|
ret.WriteString(w)
|
|
}
|
|
}
|
|
|
|
return ret
|
|
}
|