1package text
2
3import (
4 "github.com/mattn/go-runewidth"
5 "strings"
6 "unicode/utf8"
7)
8
9// Force runewidth not to treat ambiguous runes as wide chars, so that things
10// like unicode ellipsis/up/down/left/right glyphs can have correct runewidth
11// and can be displayed correctly in terminals.
12func init() {
13 runewidth.DefaultCondition.EastAsianWidth = false
14}
15
16// Wrap a text for an exact line size
17// Handle properly terminal color escape code
18func Wrap(text string, lineWidth int) (string, int) {
19 return WrapLeftPadded(text, lineWidth, 0)
20}
21
22// Wrap a text for an exact line size with a left padding
23// Handle properly terminal color escape code
24func WrapLeftPadded(text string, lineWidth int, leftPad int) (string, int) {
25 var lines []string
26 nbLine := 0
27 pad := strings.Repeat(" ", leftPad)
28
29 // tabs are formatted as 4 spaces
30 text = strings.Replace(text, "\t", " ", -1)
31 // NOTE: text is first segmented into lines so that softwrapLine can handle.
32 for _, line := range strings.Split(text, "\n") {
33 if line == "" || strings.TrimSpace(line) == "" {
34 lines = append(lines, "")
35 nbLine++
36 } else {
37 wrapped := softwrapLine(line, lineWidth-leftPad)
38 firstLine := true
39 for _, seg := range strings.Split(wrapped, "\n") {
40 if firstLine {
41 lines = append(lines, pad+strings.TrimRight(seg, " "))
42 firstLine = false
43 } else {
44 lines = append(lines, pad+strings.TrimSpace(seg))
45 }
46 nbLine++
47 }
48 }
49 }
50 return strings.Join(lines, "\n"), nbLine
51}
52
53// Break a line into several lines so that each line consumes at most
54// 'textWidth' cells. Lines break at groups of white spaces and multibyte
55// chars. Nothing is removed from the original text so that it behaves like a
56// softwrap.
57//
58// Required: The line shall not contain '\n'
59//
60// WRAPPING ALGORITHM: The line is broken into non-breakable chunks, then line
61// breaks ("\n") are inserted between these groups so that the total length
62// between breaks does not exceed the required width. Words that are longer than
63// the textWidth are broen into pieces no longer than textWidth.
64//
65func softwrapLine(line string, textWidth int) string {
66 // NOTE: terminal escapes are stripped out of the line so the algorithm is
67 // simpler. Do not try to mix them in the wrapping algorithm, as it can get
68 // complicated quickly.
69 line1, termEscapes := extractTermEscapes(line)
70
71 chunks := segmentLine(line1)
72 // Reverse the chunk array so we can use it as a stack.
73 for i, j := 0, len(chunks)-1; i < j; i, j = i+1, j-1 {
74 chunks[i], chunks[j] = chunks[j], chunks[i]
75 }
76 var line2 string = ""
77 var width int = 0
78 for len(chunks) > 0 {
79 thisWord := chunks[len(chunks)-1]
80 wl := wordLen(thisWord)
81 if width+wl <= textWidth {
82 line2 += chunks[len(chunks)-1]
83 chunks = chunks[:len(chunks)-1]
84 width += wl
85 if width == textWidth && len(chunks) > 0 {
86 // NOTE: new line begins when current line is full and there are more
87 // chunks to come.
88 line2 += "\n"
89 width = 0
90 }
91 } else if wl > textWidth {
92 left, right := splitWord(chunks[len(chunks)-1], textWidth)
93 line2 += left + "\n"
94 chunks[len(chunks)-1] = right
95 width = 0
96 } else {
97 line2 += "\n"
98 width = 0
99 }
100 }
101
102 line3 := applyTermEscapes(line2, termEscapes)
103 return line3
104}
105
106// EscapeItem: Storage of terminal escapes in a line. 'item' is the actural
107// escape command, and 'pos' is the index in the rune array where the 'item'
108// shall be inserted back. For example, the escape item in "F\x1b33mox" is
109// {"\x1b33m", 1}.
110type escapeItem struct {
111 item string
112 pos int
113}
114
115// Extract terminal escapes out of a line, returns a new line without terminal
116// escapes and a slice of escape items. The terminal escapes can be inserted
117// back into the new line at rune index 'item.pos' to recover the original line.
118//
119// Required: The line shall not contain "\n"
120//
121func extractTermEscapes(line string) (string, []escapeItem) {
122 var termEscapes []escapeItem
123 var line1 string
124
125 pos := 0
126 item := ""
127 occupiedRuneCount := 0
128 inEscape := false
129 for i, r := range []rune(line) {
130 if r == '\x1b' {
131 pos = i
132 item = string(r)
133 inEscape = true
134 continue
135 }
136 if inEscape {
137 item += string(r)
138 if r == 'm' {
139 termEscapes = append(termEscapes, escapeItem{item, pos - occupiedRuneCount})
140 occupiedRuneCount += utf8.RuneCountInString(item)
141 inEscape = false
142 }
143 continue
144 }
145 line1 += string(r)
146 }
147
148 return line1, termEscapes
149}
150
151// Apply the extracted terminal escapes to the edited line. The only edit
152// allowed is to insert "\n" like that in softwrapLine. Callers shall ensure
153// this since this function is not able to check it.
154func applyTermEscapes(line string, escapes []escapeItem) string {
155 if len(escapes) == 0 {
156 return line
157 }
158
159 var out string = ""
160
161 currPos := 0
162 currItem := 0
163 for _, r := range line {
164 if currItem < len(escapes) && currPos == escapes[currItem].pos {
165 // NOTE: We avoid terminal escapes at the end of a line by move them one
166 // pass the end of line, so that algorithms who trim right spaces are
167 // happy. But algorithms who trim left spaces are still unhappy.
168 if r == '\n' {
169 out += "\n" + escapes[currItem].item
170 } else {
171 out += escapes[currItem].item + string(r)
172 currPos++
173 }
174 currItem++
175 } else {
176 if r != '\n' {
177 currPos++
178 }
179 out += string(r)
180 }
181 }
182
183 return out
184}
185
186// Segment a line into chunks, where each chunk consists of chars with the same
187// type and is not breakable.
188func segmentLine(s string) []string {
189 var chunks []string
190
191 var word string
192 wordType := none
193 flushWord := func() {
194 chunks = append(chunks, word)
195 word = ""
196 wordType = none
197 }
198
199 for _, r := range s {
200 // A WIDE_CHAR itself constitutes a chunk.
201 thisType := runeType(r)
202 if thisType == wideChar {
203 if wordType != none {
204 flushWord()
205 }
206 chunks = append(chunks, string(r))
207 continue
208 }
209 // Other type of chunks starts with a char of that type, and ends with a
210 // char with different type or end of string.
211 if thisType != wordType {
212 if wordType != none {
213 flushWord()
214 }
215 word = string(r)
216 wordType = thisType
217 } else {
218 word += string(r)
219 }
220 }
221 if word != "" {
222 flushWord()
223 }
224
225 return chunks
226}
227
228// Rune categories
229//
230// These categories are so defined that each category forms a non-breakable
231// chunk. It IS NOT the same as unicode code point categories.
232//
233const (
234 none int = iota
235 wideChar
236 invisible
237 shortUnicode
238 space
239 visibleAscii
240)
241
242// Determine the category of a rune.
243func runeType(r rune) int {
244 rw := runewidth.RuneWidth(r)
245 if rw > 1 {
246 return wideChar
247 } else if rw == 0 {
248 return invisible
249 } else if r > 127 {
250 return shortUnicode
251 } else if r == ' ' {
252 return space
253 } else {
254 return visibleAscii
255 }
256}
257
258// wordLen return the length of a word, while ignoring the terminal escape
259// sequences
260func wordLen(word string) int {
261 length := 0
262 escape := false
263
264 for _, char := range word {
265 if char == '\x1b' {
266 escape = true
267 }
268 if !escape {
269 length += runewidth.RuneWidth(rune(char))
270 }
271 if char == 'm' {
272 escape = false
273 }
274 }
275
276 return length
277}
278
279// splitWord split a word at the given length, while ignoring the terminal escape sequences
280func splitWord(word string, length int) (string, string) {
281 runes := []rune(word)
282 var result []rune
283 added := 0
284 escape := false
285
286 if length == 0 {
287 return "", word
288 }
289
290 for _, r := range runes {
291 if r == '\x1b' {
292 escape = true
293 }
294
295 width := runewidth.RuneWidth(r)
296 if width+added > length {
297 // wide character made the length overflow
298 break
299 }
300
301 result = append(result, r)
302
303 if !escape {
304 added += width
305 if added >= length {
306 break
307 }
308 }
309
310 if r == 'm' {
311 escape = false
312 }
313 }
314
315 leftover := runes[len(result):]
316
317 return string(result), string(leftover)
318}
319
320func minInt(a, b int) int {
321 if a > b {
322 return b
323 }
324 return a
325}