Debian Codegraph @

util.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // From https://github.com/rivo/tview/blob/master/util.go
2 // Copyright (c) 2018 Oliver Kuederle
3 // MIT license
4
5 package mauview
6
7 import (
8 "math"
9 "regexp"
10 "sort"
11 "strconv"
12
13 "github.com/mattn/go-runewidth"
14 "github.com/rivo/uniseg"
15
•16 "github.com/gdamore/tcell/v2"
17 )
18
19 // Text alignment within a box.
20 const (
21 AlignLeft = iota
22 AlignCenter
23 AlignRight
24 )
25
26 // Common regular expressions.
27 var (
28 colorPattern = regexp.MustCompile(`\[([a-zA-Z]+|#[0-9a-zA-Z]{6}|\-)?(:([a-zA-Z]+|#[0-9a-zA-Z]{6}|\-)?(:([lbidrus]+|\-)?)?)?\]`)
29 regionPattern = regexp.MustCompile(`\["([a-zA-Z0-9_,;: \-\.]*)"\]`)
30 escapePattern = regexp.MustCompile(`\[([a-zA-Z0-9_,;: \-\."#]+)\[(\[*)\]`)
31 nonEscapePattern = regexp.MustCompile(`(\[[a-zA-Z0-9_,;: \-\."#]+\[*)\]`)
32 boundaryPattern = regexp.MustCompile(`(([,\.\-:;!\?&#+]|\n)[ \t\f\r]*|([ \t\f\r]+))`)
33 spacePattern = regexp.MustCompile(`\s+`)
34 )
35
36 // Positions of substrings in regular expressions.
37 const (
38 colorForegroundPos = 1
39 colorBackgroundPos = 3
40 colorFlagPos = 5
41 )
42
43 // Predefined InputField acceptance functions.
44 var (
45 // InputFieldInteger accepts integers.
46 InputFieldInteger func(text string, ch rune) bool
47
48 // InputFieldFloat accepts floating-point numbers.
49 InputFieldFloat func(text string, ch rune) bool
50
51 // InputFieldMaxLength returns an input field accept handler which accepts
52 // input strings up to a given length. Use it like this:
53 //
54 // inputField.SetAcceptanceFunc(InputFieldMaxLength(10)) // Accept up to 10 characters.
55 InputFieldMaxLength func(maxLength int) func(text string, ch rune) bool
56 )
57
58 // Package initialization.
59 func init() {
60 // Initialize the predefined input field handlers.
61 InputFieldInteger = func(text string, ch rune) bool {
62 if text == "-" {
63 return true
64 }
65 _, err := strconv.Atoi(text)
66 return err == nil
67 }
68 InputFieldFloat = func(text string, ch rune) bool {
69 if text == "-" || text == "." || text == "-." {
70 return true
71 }
72 _, err := strconv.ParseFloat(text, 64)
73 return err == nil
74 }
75 InputFieldMaxLength = func(maxLength int) func(text string, ch rune) bool {
76 return func(text string, ch rune) bool {
77 return len([]rune(text)) <= maxLength
78 }
79 }
80 }
81
82 // styleFromTag takes the given style, defined by a foreground color (fgColor),
83 // a background color (bgColor), and style attributes, and modifies it based on
84 // the substrings (tagSubstrings) extracted by the regular expression for color
85 // tags. The new colors and attributes are returned where empty strings mean
86 // "don't modify" and a dash ("-") means "reset to default".
87 func styleFromTag(fgColor, bgColor, attributes string, tagSubstrings []string) (newFgColor, newBgColor, newAttributes string) {
88 if tagSubstrings[colorForegroundPos] != "" {
89 color := tagSubstrings[colorForegroundPos]
90 if color == "-" {
91 fgColor = "-"
92 } else if color != "" {
93 fgColor = color
94 }
95 }
96
97 if tagSubstrings[colorBackgroundPos-1] != "" {
98 color := tagSubstrings[colorBackgroundPos]
99 if color == "-" {
100 bgColor = "-"
101 } else if color != "" {
102 bgColor = color
103 }
104 }
105
106 if tagSubstrings[colorFlagPos-1] != "" {
107 flags := tagSubstrings[colorFlagPos]
108 if flags == "-" {
109 attributes = "-"
110 } else if flags != "" {
111 attributes = flags
112 }
113 }
114
115 return fgColor, bgColor, attributes
116 }
117
118 // overlayStyle calculates a new style based on "style" and applying tag-based
119 // colors/attributes to it (see also styleFromTag()).
120 func overlayStyle(style tcell.Style, fgColor, bgColor, attributes string) tcell.Style {
121 _, _, defAttr := style.Decompose()
122
123 if fgColor != "" && fgColor != "-" {
124 style = style.Foreground(tcell.GetColor(fgColor))
125 }
126
127 if bgColor != "" && bgColor != "-" {
128 style = style.Background(tcell.GetColor(bgColor))
129 }
130
131 if attributes == "-" {
132 style = style.Bold(defAttr&tcell.AttrBold > 0).
133 Italic(defAttr&tcell.AttrItalic > 0).
134 Blink(defAttr&tcell.AttrBlink > 0).
135 Reverse(defAttr&tcell.AttrReverse > 0).
136 Underline(defAttr&tcell.AttrUnderline > 0).
137 Dim(defAttr&tcell.AttrDim > 0)
138 } else if attributes != "" {
139 style = style.Normal()
140 for _, flag := range attributes {
141 switch flag {
142 case 'l':
143 style = style.Blink(true)
144 case 'b':
145 style = style.Bold(true)
146 case 'i':
147 style = style.Italic(true)
148 case 'd':
149 style = style.Dim(true)
150 case 'r':
151 style = style.Reverse(true)
152 case 'u':
153 style = style.Underline(true)
154 case 's':
155 style = style.StrikeThrough(true)
156 }
157 }
158 }
159
160 return style
161 }
162
163 // decomposeString returns information about a string which may contain color
164 // tags or region tags, depending on which ones are requested to be found. It
165 // returns the indices of the color tags (as returned by
166 // re.FindAllStringIndex()), the color tags themselves (as returned by
167 // re.FindAllStringSubmatch()), the indices of region tags and the region tags
168 // themselves, the indices of an escaped tags (only if at least color tags or
169 // region tags are requested), the string stripped by any tags and escaped, and
170 // the screen width of the stripped string.
171 func decomposeString(text string, findColors, findRegions bool) (colorIndices [][]int, colors [][]string, regionIndices [][]int, regions [][]string, escapeIndices [][]int, stripped string, width int) {
172 // Shortcut for the trivial case.
173 if !findColors && !findRegions {
174 return nil, nil, nil, nil, nil, text, stringWidth(text)
175 }
176
177 // Get positions of any tags.
178 if findColors {
179 colorIndices = colorPattern.FindAllStringIndex(text, -1)
180 colors = colorPattern.FindAllStringSubmatch(text, -1)
181 }
182 if findRegions {
183 regionIndices = regionPattern.FindAllStringIndex(text, -1)
184 regions = regionPattern.FindAllStringSubmatch(text, -1)
185 }
186 escapeIndices = escapePattern.FindAllStringIndex(text, -1)
187
188 // Because the color pattern detects empty tags, we need to filter them out.
189 for i := len(colorIndices) - 1; i >= 0; i-- {
190 if colorIndices[i][1]-colorIndices[i][0] == 2 {
191 colorIndices = append(colorIndices[:i], colorIndices[i+1:]...)
192 colors = append(colors[:i], colors[i+1:]...)
193 }
194 }
195
196 // Make a (sorted) list of all tags.
197 allIndices := make([][3]int, 0, len(colorIndices)+len(regionIndices)+len(escapeIndices))
198 for indexType, index := range [][][]int{colorIndices, regionIndices, escapeIndices} {
199 for _, tag := range index {
200 allIndices = append(allIndices, [3]int{tag[0], tag[1], indexType})
201 }
202 }
203 sort.Slice(allIndices, func(i int, j int) bool {
204 return allIndices[i][0] < allIndices[j][0]
205 })
206
207 // Remove the tags from the original string.
208 var from int
209 buf := make([]byte, 0, len(text))
210 for _, indices := range allIndices {
211 if indices[2] == 2 { // Escape sequences are not simply removed.
212 buf = append(buf, []byte(text[from:indices[1]-2])...)
213 buf = append(buf, ']')
214 from = indices[1]
215 } else {
216 buf = append(buf, []byte(text[from:indices[0]])...)
217 from = indices[1]
218 }
219 }
220 buf = append(buf, text[from:]...)
221 stripped = string(buf)
222
223 // Get the width of the stripped string.
224 width = stringWidth(stripped)
225
226 return
227 }
228
229 // Print prints text onto the screen into the given box at (x,y,maxWidth,1),
230 // not exceeding that box. "align" is one of AlignLeft, AlignCenter, or
231 // AlignRight. The screen's background color will not be changed.
232 //
233 // You can change the colors and text styles mid-text by inserting a color tag.
234 // See the package description for details.
235 //
236 // Returns the number of actual bytes of the text printed (including color tags)
237 // and the actual width used for the printed runes.
238 func Print(screen Screen, text string, x, y, maxWidth, align int, color tcell.Color) (int, int) {
239 bytes, width, _, _ := printWithStyle(screen, text, x, y, 0, maxWidth, align, tcell.StyleDefault.Foreground(color), true)
240 return bytes, width
241 }
242
243 func PrintWithStyle(screen Screen, text string, x, y, maxWidth, align int, style tcell.Style) (int, int) {
244 bytes, width, _, _ := printWithStyle(screen, text, x, y, 0, maxWidth, align, style, true)
245 return bytes, width
246 }
247
248 // printWithStyle works like Print() but it takes a style instead of just a
249 // foreground color. The skipWidth parameter specifies the number of cells
250 // skipped at the beginning of the text. It also returns the start and end index
251 // (exclusively) of the text actually printed. If maintainBackground is "true",
252 // The existing screen background is not changed (i.e. the style's background
253 // color is ignored).
254 func printWithStyle(screen Screen, text string, x, y, skipWidth, maxWidth, align int, style tcell.Style, maintainBackground bool) (int, int, int, int) {
255 totalWidth, totalHeight := screen.Size()
256 if maxWidth <= 0 || len(text) == 0 || y < 0 || y >= totalHeight {
257 return 0, 0, 0, 0
258 }
259
260 // Decompose the text.
261 colorIndices, colors, _, _, escapeIndices, strippedText, strippedWidth := decomposeString(text, true, false)
262
263 // We want to reduce all alignments to AlignLeft.
264 if align == AlignRight {
265 if strippedWidth-skipWidth <= maxWidth {
266 // There's enough space for the entire text.
267 return printWithStyle(screen, text, x+maxWidth-strippedWidth+skipWidth, y, skipWidth, maxWidth, AlignLeft, style, maintainBackground)
268 }
269 // Trim characters off the beginning.
270 var (
271 bytes, width, colorPos, escapePos, tagOffset, from, to int
272 foregroundColor, backgroundColor, attributes string
273 )
274 originalStyle := style
275 iterateString(strippedText, func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
276 // Update color/escape tag offset and style.
277 if colorPos < len(colorIndices) && textPos+tagOffset >= colorIndices[colorPos][0] && textPos+tagOffset < colorIndices[colorPos][1] {
278 foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colors[colorPos])
279 style = overlayStyle(originalStyle, foregroundColor, backgroundColor, attributes)
280 tagOffset += colorIndices[colorPos][1] - colorIndices[colorPos][0]
281 colorPos++
282 }
283 if escapePos < len(escapeIndices) && textPos+tagOffset >= escapeIndices[escapePos][0] && textPos+tagOffset < escapeIndices[escapePos][1] {
284 tagOffset++
285 escapePos++
286 }
287 if strippedWidth-screenPos <= maxWidth {
288 // We chopped off enough.
289 if escapePos > 0 && textPos+tagOffset-1 >= escapeIndices[escapePos-1][0] && textPos+tagOffset-1 < escapeIndices[escapePos-1][1] {
290 // Unescape open escape sequences.
291 escapeCharPos := escapeIndices[escapePos-1][1] - 2
292 text = text[:escapeCharPos] + text[escapeCharPos+1:]
293 }
294 // Print and return.
295 bytes, width, from, to = printWithStyle(screen, text[textPos+tagOffset:], x, y, 0, maxWidth, AlignLeft, style, maintainBackground)
296 from += textPos + tagOffset
297 to += textPos + tagOffset
298 return true
299 }
300 return false
301 })
302 return bytes, width, from, to
303 } else if align == AlignCenter {
304 if strippedWidth-skipWidth == maxWidth {
305 // Use the exact space.
306 return printWithStyle(screen, text, x, y, skipWidth, maxWidth, AlignLeft, style, maintainBackground)
307 } else if strippedWidth-skipWidth < maxWidth {
308 // We have more space than we need.
309 half := (maxWidth - strippedWidth + skipWidth) / 2
310 return printWithStyle(screen, text, x+half, y, skipWidth, maxWidth-half, AlignLeft, style, maintainBackground)
311 } else {
312 // Chop off runes until we have a perfect fit.
313 var choppedLeft, choppedRight, leftIndex, rightIndex int
314 rightIndex = len(strippedText)
315 for rightIndex-1 > leftIndex && strippedWidth-skipWidth-choppedLeft-choppedRight > maxWidth {
316 if skipWidth > 0 || choppedLeft < choppedRight {
317 // Iterate on the left by one character.
318 iterateString(strippedText[leftIndex:], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
319 if skipWidth > 0 {
320 skipWidth -= screenWidth
321 strippedWidth -= screenWidth
322 } else {
323 choppedLeft += screenWidth
324 }
325 leftIndex += textWidth
326 return true
327 })
328 } else {
329 // Iterate on the right by one character.
330 iterateStringReverse(strippedText[leftIndex:rightIndex], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
331 choppedRight += screenWidth
332 rightIndex -= textWidth
333 return true
334 })
335 }
336 }
337
338 // Add tag offsets and determine start style.
339 var (
340 colorPos, escapePos, tagOffset int
341 foregroundColor, backgroundColor, attributes string
342 )
343 originalStyle := style
344 for index := range strippedText {
345 // We only need the offset of the left index.
346 if index > leftIndex {
347 // We're done.
348 if escapePos > 0 && leftIndex+tagOffset-1 >= escapeIndices[escapePos-1][0] && leftIndex+tagOffset-1 < escapeIndices[escapePos-1][1] {
349 // Unescape open escape sequences.
350 escapeCharPos := escapeIndices[escapePos-1][1] - 2
351 text = text[:escapeCharPos] + text[escapeCharPos+1:]
352 }
353 break
354 }
355
356 // Update color/escape tag offset.
357 if colorPos < len(colorIndices) && index+tagOffset >= colorIndices[colorPos][0] && index+tagOffset < colorIndices[colorPos][1] {
358 if index <= leftIndex {
359 foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colors[colorPos])
360 style = overlayStyle(originalStyle, foregroundColor, backgroundColor, attributes)
361 }
362 tagOffset += colorIndices[colorPos][1] - colorIndices[colorPos][0]
363 colorPos++
364 }
365 if escapePos < len(escapeIndices) && index+tagOffset >= escapeIndices[escapePos][0] && index+tagOffset < escapeIndices[escapePos][1] {
366 tagOffset++
367 escapePos++
368 }
369 }
370 bytes, width, from, to := printWithStyle(screen, text[leftIndex+tagOffset:], x, y, 0, maxWidth, AlignLeft, style, maintainBackground)
371 from += leftIndex + tagOffset
372 to += leftIndex + tagOffset
373 return bytes, width, from, to
374 }
375 }
376
377 // Draw text.
378 var (
379 drawn, drawnWidth, colorPos, escapePos, tagOffset, from, to int
380 foregroundColor, backgroundColor, attributes string
381 )
382 iterateString(strippedText, func(main rune, comb []rune, textPos, length, screenPos, screenWidth int) bool {
383 // Skip character if necessary.
384 if skipWidth > 0 {
385 skipWidth -= screenWidth
386 from = textPos + length
387 to = from
388 return false
389 }
390
391 // Only continue if there is still space.
392 if drawnWidth+screenWidth > maxWidth || x+drawnWidth >= totalWidth {
393 return true
394 }
395
396 // Handle color tags.
397 for colorPos < len(colorIndices) && textPos+tagOffset >= colorIndices[colorPos][0] && textPos+tagOffset < colorIndices[colorPos][1] {
398 foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colors[colorPos])
399 tagOffset += colorIndices[colorPos][1] - colorIndices[colorPos][0]
400 colorPos++
401 }
402
403 // Handle escape tags.
404 if escapePos < len(escapeIndices) && textPos+tagOffset >= escapeIndices[escapePos][0] && textPos+tagOffset < escapeIndices[escapePos][1] {
405 if textPos+tagOffset == escapeIndices[escapePos][1]-2 {
406 tagOffset++
407 escapePos++
408 }
409 }
410
411 // Memorize positions.
412 to = textPos + length
413
414 // Print the rune sequence.
415 finalX := x + drawnWidth
416 finalStyle := style
417 if maintainBackground {
418 _, _, existingStyle, _ := screen.GetContent(finalX, y)
419 _, background, _ := existingStyle.Decompose()
420 finalStyle = finalStyle.Background(background)
421 }
422 finalStyle = overlayStyle(finalStyle, foregroundColor, backgroundColor, attributes)
423 for offset := screenWidth - 1; offset >= 0; offset-- {
424 // To avoid undesired effects, we populate all cells.
425 if offset == 0 {
426 screen.SetContent(finalX+offset, y, main, comb, finalStyle)
427 } else {
428 screen.SetContent(finalX+offset, y, ' ', nil, finalStyle)
429 }
430 }
431
432 // Advance.
433 drawn += length
434 drawnWidth += screenWidth
435
436 return false
437 })
438
439 return drawn + tagOffset + len(escapeIndices), drawnWidth, from, to
440 }
441
442 // PrintSimple prints white text to the screen at the given position.
443 func PrintSimple(screen Screen, text string, x, y int) {
444 Print(screen, text, x, y, math.MaxInt32, AlignLeft, Styles.PrimaryTextColor)
445 }
446
447 // TaggedStringWidth returns the width of the given string needed to print it on
448 // screen. The text may contain color tags which are not counted.
449 func TaggedStringWidth(text string) int {
450 _, _, _, _, _, _, width := decomposeString(text, true, false)
451 return width
452 }
453
454 // stringWidth returns the number of horizontal cells needed to print the given
455 // text. It splits the text into its grapheme clusters, calculates each
456 // cluster's width, and adds them up to a total.
457 func stringWidth(text string) (width int) {
458 g := uniseg.NewGraphemes(text)
459 for g.Next() {
460 var chWidth int
461 for _, r := range g.Runes() {
462 chWidth = runewidth.RuneWidth(r)
463 if chWidth > 0 {
464 break // Our best guess at this point is to use the width of the first non-zero-width rune.
465 }
466 }
467 width += chWidth
468 }
469 return
470 }
471
472 // WordWrap splits a text such that each resulting line does not exceed the
473 // given screen width. Possible split points are after any punctuation or
474 // whitespace. Whitespace after split points will be dropped.
475 //
476 // This function considers color tags to have no width.
477 //
478 // Text is always split at newline characters ('\n').
479 func WordWrap(text string, width int) (lines []string) {
480 colorTagIndices, _, _, _, escapeIndices, strippedText, _ := decomposeString(text, true, false)
481
482 // Find candidate breakpoints.
483 breakpoints := boundaryPattern.FindAllStringSubmatchIndex(strippedText, -1)
484 // Results in one entry for each candidate. Each entry is an array a of
485 // indices into strippedText where a[6] < 0 for newline/punctuation matches
486 // and a[4] < 0 for whitespace matches.
487
488 // Process stripped text one character at a time.
489 var (
490 colorPos, escapePos, breakpointPos, tagOffset int
491 lastBreakpoint, lastContinuation, currentLineStart int
492 lineWidth, overflow int
493 forceBreak bool
494 )
495 unescape := func(substr string, startIndex int) string {
496 // A helper function to unescape escaped tags.
497 for index := escapePos; index >= 0; index-- {
498 if index < len(escapeIndices) && startIndex > escapeIndices[index][0] && startIndex < escapeIndices[index][1]-1 {
499 pos := escapeIndices[index][1] - 2 - startIndex
500 return substr[:pos] + substr[pos+1:]
501 }
502 }
503 return substr
504 }
505 iterateString(strippedText, func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
506 // Handle tags.
507 for {
508 if colorPos < len(colorTagIndices) && textPos+tagOffset >= colorTagIndices[colorPos][0] && textPos+tagOffset < colorTagIndices[colorPos][1] {
509 // Colour tags.
510 tagOffset += colorTagIndices[colorPos][1] - colorTagIndices[colorPos][0]
511 colorPos++
512 } else if escapePos < len(escapeIndices) && textPos+tagOffset == escapeIndices[escapePos][1]-2 {
513 // Escape tags.
514 tagOffset++
515 escapePos++
516 } else {
517 break
518 }
519 }
520
521 // Is this a breakpoint?
522 if breakpointPos < len(breakpoints) && textPos+tagOffset == breakpoints[breakpointPos][0] {
523 // Yes, it is. Set up breakpoint infos depending on its type.
524 lastBreakpoint = breakpoints[breakpointPos][0] + tagOffset
525 lastContinuation = breakpoints[breakpointPos][1] + tagOffset
526 overflow = 0
527 forceBreak = main == '\n'
528 if breakpoints[breakpointPos][6] < 0 && !forceBreak {
529 lastBreakpoint++ // Don't skip punctuation.
530 }
531 breakpointPos++
532 }
533
534 // Check if a break is warranted.
535 if forceBreak || lineWidth > 0 && lineWidth+screenWidth > width {
536 breakpoint := lastBreakpoint
537 continuation := lastContinuation
538 if forceBreak {
539 breakpoint = textPos + tagOffset
540 continuation = textPos + tagOffset + 1
541 lastBreakpoint = 0
542 overflow = 0
543 } else if lastBreakpoint <= currentLineStart {
544 breakpoint = textPos + tagOffset
545 continuation = textPos + tagOffset
546 overflow = 0
547 }
548 lines = append(lines, unescape(text[currentLineStart:breakpoint], currentLineStart))
549 currentLineStart, lineWidth, forceBreak = continuation, overflow, false
550 }
551
552 // Remember the characters since the last breakpoint.
553 if lastBreakpoint > 0 && lastContinuation <= textPos+tagOffset {
554 overflow += screenWidth
555 }
556
557 // Advance.
558 lineWidth += screenWidth
559
560 // But if we're still inside a breakpoint, skip next character (whitespace).
561 if textPos+tagOffset < currentLineStart {
562 lineWidth -= screenWidth
563 }
564
565 return false
566 })
567
568 // Flush the rest.
569 if currentLineStart < len(text) {
570 lines = append(lines, unescape(text[currentLineStart:], currentLineStart))
571 }
572
573 return
574 }
575
576 // Escape escapes the given text such that color and/or region tags are not
577 // recognized and substituted by the print functions of this package. For
578 // example, to include a tag-like string in a box title or in a TextView:
579 //
580 // box.SetTitle(tview.Escape("[squarebrackets]"))
581 // fmt.Fprint(textView, tview.Escape(`["quoted"]`))
582 func Escape(text string) string {
583 return nonEscapePattern.ReplaceAllString(text, "$1[]")
584 }
585
586 // iterateString iterates through the given string one printed character at a
587 // time. For each such character, the callback function is called with the
588 // Unicode code points of the character (the first rune and any combining runes
589 // which may be nil if there aren't any), the starting position (in bytes)
590 // within the original string, its length in bytes, the screen position of the
591 // character, and the screen width of it. The iteration stops if the callback
592 // returns true. This function returns true if the iteration was stopped before
593 // the last character.
594 func iterateString(text string, callback func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool) bool {
595 var screenPos int
596
597 gr := uniseg.NewGraphemes(text)
598 for gr.Next() {
599 r := gr.Runes()
600 from, to := gr.Positions()
601 width := stringWidth(gr.Str())
602 var comb []rune
603 if len(r) > 1 {
604 comb = r[1:]
605 }
606
607 if callback(r[0], comb, from, to-from, screenPos, width) {
608 return true
609 }
610
611 screenPos += width
612 }
613
614 return false
615 }
616
617 // iterateStringReverse iterates through the given string in reverse, starting
618 // from the end of the string, one printed character at a time. For each such
619 // character, the callback function is called with the Unicode code points of
620 // the character (the first rune and any combining runes which may be nil if
621 // there aren't any), the starting position (in bytes) within the original
622 // string, its length in bytes, the screen position of the character, and the
623 // screen width of it. The iteration stops if the callback returns true. This
624 // function returns true if the iteration was stopped before the last character.
625 func iterateStringReverse(text string, callback func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool) bool {
626 type cluster struct {
627 main rune
628 comb []rune
629 textPos, textWidth, screenPos, screenWidth int
630 }
631
632 // Create the grapheme clusters.
633 var clusters []cluster
634 iterateString(text, func(main rune, comb []rune, textPos int, textWidth int, screenPos int, screenWidth int) bool {
635 clusters = append(clusters, cluster{
636 main: main,
637 comb: comb,
638 textPos: textPos,
639 textWidth: textWidth,
640 screenPos: screenPos,
641 screenWidth: screenWidth,
642 })
643 return false
644 })
645
646 // Iterate in reverse.
647 for index := len(clusters) - 1; index >= 0; index-- {
648 if callback(
649 clusters[index].main,
650 clusters[index].comb,
651 clusters[index].textPos,
652 clusters[index].textWidth,
653 clusters[index].screenPos,
654 clusters[index].screenWidth,
655 ) {
656 return true
657 }
658 }
659
660 return false
661 }
662
663 // stripTags strips colour tags from the given string. (Region tags are not
664 // stripped.)
665 func stripTags(text string) string {
666 stripped := colorPattern.ReplaceAllStringFunc(text, func(match string) string {
667 if len(match) > 2 {
668 return ""
669 }
670 return match
671 })
672 return escapePattern.ReplaceAllString(stripped, `[$1$2]`)
673 }