-
Notifications
You must be signed in to change notification settings - Fork 3
/
wrap.go
45 lines (37 loc) · 1.25 KB
/
wrap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package textplain
import "strings"
// WordWrap searches for logical breakpoints in each line (whitespace) and tries to trim each
// line to the specified length
// Note: this diverges from the regex approach in premailer, which I found to be significantly
// slower in cases with long unbroken lines
// https://github.com/premailer/premailer/blob/7c94e7a/lib/premailer/html_to_plain_text.rb#L116
func WordWrap(txt string, lineLength int) string {
// A line length of zero or less indicates no wrapping
if lineLength <= 0 {
return txt
}
var final []string
for _, line := range strings.Split(txt, "\n") {
var startIndex, endIndex int
for (len(line)-endIndex) > lineLength && startIndex < len(line) {
endIndex += lineLength
if endIndex >= len(line) {
endIndex = len(line) - 1
} else if endIndex < startIndex {
endIndex = startIndex
}
newIndex := strings.LastIndex(line[startIndex:endIndex+1], " ")
if newIndex <= 0 {
continue
}
final = append(final, line[startIndex:startIndex+newIndex])
startIndex += newIndex
endIndex = startIndex
// clear any extra space
for ; startIndex < len(line) && line[startIndex] == ' '; startIndex++ {
}
}
final = append(final, line[startIndex:])
}
return strings.Join(final, "\n")
}