Debian Codegraph @

textview.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // From https://github.com/rivo/tview/blob/master/textview.go
2
3 package mauview
4
5 import (
6 "bytes"
7 "fmt"
8 "regexp"
9 "sync"
10 "unicode/utf8"
11
12 "github.com/mattn/go-runewidth"
13
•14 "github.com/gdamore/tcell/v2"
15 )
16
17 // TabSize is the number of spaces with which a tab character will be replaced.
18 var TabSize = 4
19
20 // textViewIndex contains information about each line displayed in the text
21 // view.
22 type textViewIndex struct {
23 Line int // The index into the "buffer" variable.
24 Pos int // The index into the "buffer" string (byte position).
25 NextPos int // The (byte) index of the next character in this buffer line.
26 Width int // The screen width of this line.
27 ForegroundColor string // The starting foreground color ("" = don't change, "-" = reset).
28 BackgroundColor string // The starting background color ("" = don't change, "-" = reset).
29 Attributes string // The starting attributes ("" = don't change, "-" = reset).
30 Region string // The starting region ID.
31 }
32
33 // TextView is a box which displays text. It implements the io.Writer interface
34 // so you can stream text to it. This does not trigger a redraw automatically
35 // but if a handler is installed via SetChangedFunc(), you can cause it to be
36 // redrawn. (See SetChangedFunc() for more details.)
37 //
38 // # Navigation
39 //
40 // If the text view is scrollable (the default), text is kept in a buffer which
41 // may be larger than the screen and can be navigated similarly to Vim:
42 //
43 // - h, left arrow: Move left.
44 // - l, right arrow: Move right.
45 // - j, down arrow: Move down.
46 // - k, up arrow: Move up.
47 // - g, home: Move to the top.
48 // - G, end: Move to the bottom.
49 // - Ctrl-F, page down: Move down by one page.
50 // - Ctrl-B, page up: Move up by one page.
51 //
52 // If the text is not scrollable, any text above the top visible line is
53 // discarded.
54 //
55 // Use SetInputCapture() to override or modify keyboard input.
56 //
57 // # Colors
58 //
59 // If dynamic colors are enabled via SetDynamicColors(), text color can be
60 // changed dynamically by embedding color strings in square brackets. This works
61 // the same way as anywhere else. Please see the package documentation for more
62 // information.
63 //
64 // # Regions and Highlights
65 //
66 // If regions are enabled via SetRegions(), you can define text regions within
67 // the text and assign region IDs to them. Text regions start with region tags.
68 // Region tags are square brackets that contain a region ID in double quotes,
69 // for example:
70 //
71 // We define a ["rg"]region[""] here.
72 //
73 // A text region ends with the next region tag. Tags with no region ID ([""])
74 // don't start new regions. They can therefore be used to mark the end of a
75 // region. Region IDs must satisfy the following regular expression:
76 //
77 // [a-zA-Z0-9_,;: \-\.]+
78 //
79 // Regions can be highlighted by calling the Highlight() function with one or
80 // more region IDs. This can be used to display search results, for example.
81 //
82 // The ScrollToHighlight() function can be used to jump to the currently
83 // highlighted region once when the text view is drawn the next time.
84 //
85 // See https://github.com/rivo/tview/wiki/TextView for an example.
86 type TextView struct {
87 sync.Mutex
88
89 // The text buffer.
90 buffer []string
91
92 // The last bytes that have been received but are not part of the buffer yet.
93 recentBytes []byte
94
95 // The processed line index. This is nil if the buffer has changed and needs
96 // to be re-indexed.
97 index []*textViewIndex
98
99 // The text alignment, one of AlignLeft, AlignCenter, or AlignRight.
100 align int
101
102 // Indices into the "index" slice which correspond to the first line of the
103 // first highlight and the last line of the last highlight. This is calculated
104 // during re-indexing. Set to -1 if there is no current highlight.
105 fromHighlight, toHighlight int
106
107 // The screen space column of the highlight in its first line. Set to -1 if
108 // there is no current highlight.
109 posHighlight int
110
111 // A set of region IDs that are currently highlighted.
112 highlights map[string]struct{}
113
114 // The last width for which the current table is drawn.
115 lastWidth int
116
117 // The screen width of the longest line in the index (not the buffer).
118 longestLine int
119
120 // The index of the first line shown in the text view.
121 lineOffset int
122
123 // If set to true, the text view will always remain at the end of the content.
124 trackEnd bool
125
126 // The number of characters to be skipped on each line (not in wrap mode).
127 columnOffset int
128
129 // The height of the content the last time the text view was drawn.
130 pageSize int
131
132 // If set to true, the text view will keep a buffer of text which can be
133 // navigated when the text is longer than what fits into the box.
134 scrollable bool
135
136 // If set to true, lines that are longer than the available width are wrapped
137 // onto the next line. If set to false, any characters beyond the available
138 // width are discarded.
139 wrap bool
140
141 // If set to true and if wrap is also true, lines are split at spaces or
142 // after punctuation characters.
143 wordWrap bool
144
145 baseStyle tcell.Style
146
147 // If set to true, the text color can be changed dynamically by piping color
148 // strings in square brackets to the text view.
149 dynamicColors bool
150
151 // If set to true, region tags can be used to define regions.
152 regions bool
153
154 // A temporary flag which, when true, will automatically bring the current
155 // highlight(s) into the visible screen.
156 scrollToHighlights bool
157
158 // An optional function which is called when the content of the text view has
159 // changed.
160 changed func()
161
162 // An optional function which is called when the user presses one of the
163 // following keys: Escape, Enter, Tab, Backtab.
164 done func(tcell.Key)
165 }
166
167 // NewTextView returns a new text view.
168 func NewTextView() *TextView {
169 return &TextView{
170 highlights: make(map[string]struct{}),
171 lineOffset: -1,
172 scrollable: true,
173 align: AlignLeft,
174 wrap: true,
175 baseStyle: tcell.StyleDefault.Foreground(Styles.PrimaryTextColor),
176 regions: false,
177 dynamicColors: false,
178 }
179 }
180
181 // SetScrollable sets the flag that decides whether or not the text view is
182 // scrollable. If true, text is kept in a buffer and can be navigated.
183 func (t *TextView) SetScrollable(scrollable bool) *TextView {
184 t.scrollable = scrollable
185 if !scrollable {
186 t.trackEnd = true
187 }
188 return t
189 }
190
191 // SetWrap sets the flag that, if true, leads to lines that are longer than the
192 // available width being wrapped onto the next line. If false, any characters
193 // beyond the available width are not displayed.
194 func (t *TextView) SetWrap(wrap bool) *TextView {
195 if t.wrap != wrap {
196 t.index = nil
197 }
198 t.wrap = wrap
199 return t
200 }
201
202 // SetWordWrap sets the flag that, if true and if the "wrap" flag is also true
203 // (see SetWrap()), wraps the line at spaces or after punctuation marks. Note
204 // that trailing spaces will not be printed.
205 //
206 // This flag is ignored if the "wrap" flag is false.
207 func (t *TextView) SetWordWrap(wrapOnWords bool) *TextView {
208 if t.wordWrap != wrapOnWords {
209 t.index = nil
210 }
211 t.wordWrap = wrapOnWords
212 return t
213 }
214
215 // SetTextAlign sets the text alignment within the text view. This must be
216 // either AlignLeft, AlignCenter, or AlignRight.
217 func (t *TextView) SetTextAlign(align int) *TextView {
218 if t.align != align {
219 t.index = nil
220 }
221 t.align = align
222 return t
223 }
224
225 // SetTextColor sets the initial color of the text (which can be changed
226 // dynamically by sending color strings in square brackets to the text view if
227 // dynamic colors are enabled).
228 func (t *TextView) SetTextColor(color tcell.Color) *TextView {
229 t.baseStyle = t.baseStyle.Foreground(color)
230 return t
231 }
232
233 func (t *TextView) SetBackgroundColor(color tcell.Color) *TextView {
234 t.baseStyle = t.baseStyle.Background(color)
235 return t
236 }
237
238 // SetText sets the text of this text view to the provided string. Previously
239 // contained text will be removed.
240 func (t *TextView) SetText(text string) *TextView {
241 t.Clear()
242 fmt.Fprint(t, text)
243 return t
244 }
245
246 // SetDynamicColors sets the flag that allows the text color to be changed
247 // dynamically. See class description for details.
248 func (t *TextView) SetDynamicColors(dynamic bool) *TextView {
249 if t.dynamicColors != dynamic {
250 t.index = nil
251 }
252 t.dynamicColors = dynamic
253 return t
254 }
255
256 // SetRegions sets the flag that allows to define regions in the text. See class
257 // description for details.
258 func (t *TextView) SetRegions(regions bool) *TextView {
259 if t.regions != regions {
260 t.index = nil
261 }
262 t.regions = regions
263 return t
264 }
265
266 // SetChangedFunc sets a handler function which is called when the text of the
267 // text view has changed. This is useful when text is written to this io.Writer
268 // in a separate goroutine. This does not automatically cause the screen to be
269 // refreshed so you may want to use the "changed" handler to redraw the screen.
270 //
271 // Note that to avoid race conditions or deadlocks, there are a few rules you
272 // should follow:
273 //
274 // - You can call Application.Draw() from this handler.
275 // - You can call TextView.HasFocus() from this handler.
276 // - During the execution of this handler, access to any other variables from
277 // this primitive or any other primitive should be queued using
278 // Application.QueueUpdate().
279 //
280 // See package description for details on dealing with concurrency.
281 func (t *TextView) SetChangedFunc(handler func()) *TextView {
282 t.changed = handler
283 return t
284 }
285
286 // SetDoneFunc sets a handler which is called when the user presses on the
287 // following keys: Escape, Enter, Tab, Backtab. The key is passed to the
288 // handler.
289 func (t *TextView) SetDoneFunc(handler func(key tcell.Key)) *TextView {
290 t.done = handler
291 return t
292 }
293
294 // ScrollTo scrolls to the specified row and column (both starting with 0).
295 func (t *TextView) ScrollTo(row, column int) *TextView {
296 if !t.scrollable {
297 return t
298 }
299 t.lineOffset = row
300 t.columnOffset = column
301 return t
302 }
303
304 // ScrollToBeginning scrolls to the top left corner of the text if the text view
305 // is scrollable.
306 func (t *TextView) ScrollToBeginning() *TextView {
307 if !t.scrollable {
308 return t
309 }
310 t.trackEnd = false
311 t.lineOffset = 0
312 t.columnOffset = 0
313 return t
314 }
315
316 // ScrollToEnd scrolls to the bottom left corner of the text if the text view
317 // is scrollable. Adding new rows to the end of the text view will cause it to
318 // scroll with the new data.
319 func (t *TextView) ScrollToEnd() *TextView {
320 if !t.scrollable {
321 return t
322 }
323 t.trackEnd = true
324 t.columnOffset = 0
325 return t
326 }
327
328 // GetScrollOffset returns the number of rows and columns that are skipped at
329 // the top left corner when the text view has been scrolled.
330 func (t *TextView) GetScrollOffset() (row, column int) {
331 return t.lineOffset, t.columnOffset
332 }
333
334 // Clear removes all text from the buffer.
335 func (t *TextView) Clear() *TextView {
336 t.buffer = nil
337 t.recentBytes = nil
338 t.index = nil
339 return t
340 }
341
342 // Highlight specifies which regions should be highlighted. See class
343 // description for details on regions. Empty region strings are ignored.
344 //
345 // Text in highlighted regions will be drawn inverted, i.e. with their
346 // background and foreground colors swapped.
347 //
348 // Calling this function will remove any previous highlights. To remove all
349 // highlights, call this function without any arguments.
350 func (t *TextView) Highlight(regionIDs ...string) *TextView {
351 t.highlights = make(map[string]struct{})
352 for _, id := range regionIDs {
353 if id == "" {
354 continue
355 }
356 t.highlights[id] = struct{}{}
357 }
358 t.index = nil
359 return t
360 }
361
362 // GetHighlights returns the IDs of all currently highlighted regions.
363 func (t *TextView) GetHighlights() (regionIDs []string) {
364 for id := range t.highlights {
365 regionIDs = append(regionIDs, id)
366 }
367 return
368 }
369
370 // ScrollToHighlight will cause the visible area to be scrolled so that the
371 // highlighted regions appear in the visible area of the text view. This
372 // repositioning happens the next time the text view is drawn. It happens only
373 // once so you will need to call this function repeatedly to always keep
374 // highlighted regions in view.
375 //
376 // Nothing happens if there are no highlighted regions or if the text view is
377 // not scrollable.
378 func (t *TextView) ScrollToHighlight() *TextView {
379 if len(t.highlights) == 0 || !t.scrollable || !t.regions {
380 return t
381 }
382 t.index = nil
383 t.scrollToHighlights = true
384 t.trackEnd = false
385 return t
386 }
387
388 // GetRegionText returns the text of the region with the given ID. If dynamic
389 // colors are enabled, color tags are stripped from the text. Newlines are
390 // always returned as '\n' runes.
391 //
392 // If the region does not exist or if regions are turned off, an empty string
393 // is returned.
394 func (t *TextView) GetRegionText(regionID string) string {
395 if !t.regions || regionID == "" {
396 return ""
397 }
398
399 var (
400 buffer bytes.Buffer
401 currentRegionID string
402 )
403
404 for _, str := range t.buffer {
405 // Find all color tags in this line.
406 var colorTagIndices [][]int
407 if t.dynamicColors {
408 colorTagIndices = colorPattern.FindAllStringIndex(str, -1)
409 }
410
411 // Find all regions in this line.
412 var (
413 regionIndices [][]int
414 regions [][]string
415 )
416 if t.regions {
417 regionIndices = regionPattern.FindAllStringIndex(str, -1)
418 regions = regionPattern.FindAllStringSubmatch(str, -1)
419 }
420
421 // Analyze this line.
422 var currentTag, currentRegion int
423 for pos, ch := range str {
424 // Skip any color tags.
425 if currentTag < len(colorTagIndices) && pos >= colorTagIndices[currentTag][0] && pos < colorTagIndices[currentTag][1] {
426 if pos == colorTagIndices[currentTag][1]-1 {
427 currentTag++
428 }
429 continue
430 }
431
432 // Skip any regions.
433 if currentRegion < len(regionIndices) && pos >= regionIndices[currentRegion][0] && pos < regionIndices[currentRegion][1] {
434 if pos == regionIndices[currentRegion][1]-1 {
435 if currentRegionID == regionID {
436 // This is the end of the requested region. We're done.
437 return buffer.String()
438 }
439 currentRegionID = regions[currentRegion][1]
440 currentRegion++
441 }
442 continue
443 }
444
445 // Add this rune.
446 if currentRegionID == regionID {
447 buffer.WriteRune(ch)
448 }
449 }
450
451 // Add newline.
452 if currentRegionID == regionID {
453 buffer.WriteRune('\n')
454 }
455 }
456
457 return escapePattern.ReplaceAllString(buffer.String(), `[$1$2]`)
458 }
459
460 // Write lets us implement the io.Writer interface. Tab characters will be
461 // replaced with TabSize space characters. A "\n" or "\r\n" will be interpreted
462 // as a new line.
463 func (t *TextView) Write(p []byte) (n int, err error) {
464 // Notify at the end.
465 t.Lock()
466 changed := t.changed
467 t.Unlock()
468 if changed != nil {
469 defer changed() // Deadlocks may occur if we lock here.
470 }
471
472 t.Lock()
473 defer t.Unlock()
474
475 // Copy data over.
476 newBytes := append(t.recentBytes, p...)
477 t.recentBytes = nil
478
479 // If we have a trailing invalid UTF-8 byte, we'll wait.
480 if r, _ := utf8.DecodeLastRune(p); r == utf8.RuneError {
481 t.recentBytes = newBytes
482 return len(p), nil
483 }
484
485 // If we have a trailing open dynamic color, exclude it.
486 if t.dynamicColors {
487 openColor := regexp.MustCompile(`\[([a-zA-Z]*|#[0-9a-zA-Z]*)$`)
488 location := openColor.FindIndex(newBytes)
489 if location != nil {
490 t.recentBytes = newBytes[location[0]:]
491 newBytes = newBytes[:location[0]]
492 }
493 }
494
495 // If we have a trailing open region, exclude it.
496 if t.regions {
497 openRegion := regexp.MustCompile(`\["[a-zA-Z0-9_,;: \-\.]*"?$`)
498 location := openRegion.FindIndex(newBytes)
499 if location != nil {
500 t.recentBytes = newBytes[location[0]:]
501 newBytes = newBytes[:location[0]]
502 }
503 }
504
505 // Transform the new bytes into strings.
506 newLine := regexp.MustCompile(`\r?\n`)
507 newBytes = bytes.Replace(newBytes, []byte{'\t'}, bytes.Repeat([]byte{' '}, TabSize), -1)
508 for index, line := range newLine.Split(string(newBytes), -1) {
509 if index == 0 {
510 if len(t.buffer) == 0 {
511 t.buffer = []string{line}
512 } else {
513 t.buffer[len(t.buffer)-1] += line
514 }
515 } else {
516 t.buffer = append(t.buffer, line)
517 }
518 }
519
520 // Reset the index.
521 t.index = nil
522
523 return len(p), nil
524 }
525
526 // reindexBuffer re-indexes the buffer such that we can use it to easily draw
527 // the buffer onto the screen. Each line in the index will contain a pointer
528 // into the buffer from which on we will print text. It will also contain the
529 // color with which the line starts.
530 func (t *TextView) reindexBuffer(width int) {
531 if t.index != nil {
532 return // Nothing has changed. We can still use the current index.
533 }
534 t.index = nil
535 t.fromHighlight, t.toHighlight, t.posHighlight = -1, -1, -1
536
537 // If there's no space, there's no index.
538 if width < 1 {
539 return
540 }
541
542 // Initial states.
543 regionID := ""
544 var highlighted bool
545
546 // Go through each line in the buffer.
547 for bufferIndex, str := range t.buffer {
548 // Find all color tags in this line. Then remove them.
549 var (
550 colorTagIndices [][]int
551 colorTags [][]string
552 escapeIndices [][]int
553 )
554 strippedStr := str
555 if t.dynamicColors {
556 colorTagIndices, colorTags, _, _, escapeIndices, strippedStr, _ = decomposeString(str, true, false)
557 }
558
559 // Find all regions in this line. Then remove them.
560 var (
561 regionIndices [][]int
562 regions [][]string
563 )
564 if t.regions {
565 regionIndices = regionPattern.FindAllStringIndex(str, -1)
566 regions = regionPattern.FindAllStringSubmatch(str, -1)
567 strippedStr = regionPattern.ReplaceAllString(strippedStr, "")
568 }
569
570 // We don't need the original string anymore for now.
571 str = strippedStr
572
573 // Split the line if required.
574 var splitLines []string
575 if t.wrap && len(str) > 0 {
576 for len(str) > 0 {
577 extract := runewidth.Truncate(str, width, "")
578 if t.wordWrap && len(extract) < len(str) {
579 // Add any spaces from the next line.
580 if spaces := spacePattern.FindStringIndex(str[len(extract):]); spaces != nil && spaces[0] == 0 {
581 extract = str[:len(extract)+spaces[1]]
582 }
583
584 // Can we split before the mandatory end?
585 matches := boundaryPattern.FindAllStringIndex(extract, -1)
586 if len(matches) > 0 {
587 // Yes. Let's split there.
588 extract = extract[:matches[len(matches)-1][1]]
589 }
590 }
591 splitLines = append(splitLines, extract)
592 str = str[len(extract):]
593 }
594 } else {
595 // No need to split the line.
596 splitLines = []string{str}
597 }
598
599 // Create index from split lines.
600 var (
601 originalPos, colorPos, regionPos, escapePos int
602 foregroundColor, backgroundColor, attributes string
603 )
604 for _, splitLine := range splitLines {
605 line := &textViewIndex{
606 Line: bufferIndex,
607 Pos: originalPos,
608 ForegroundColor: foregroundColor,
609 BackgroundColor: backgroundColor,
610 Attributes: attributes,
611 Region: regionID,
612 }
613
614 // Shift original position with tags.
615 lineLength := len(splitLine)
616 remainingLength := lineLength
617 tagEnd := originalPos
618 totalTagLength := 0
619 for {
620 // Which tag comes next?
621 nextTag := make([][3]int, 0, 3)
622 if colorPos < len(colorTagIndices) {
623 nextTag = append(nextTag, [3]int{colorTagIndices[colorPos][0], colorTagIndices[colorPos][1], 0}) // 0 = color tag.
624 }
625 if regionPos < len(regionIndices) {
626 nextTag = append(nextTag, [3]int{regionIndices[regionPos][0], regionIndices[regionPos][1], 1}) // 1 = region tag.
627 }
628 if escapePos < len(escapeIndices) {
629 nextTag = append(nextTag, [3]int{escapeIndices[escapePos][0], escapeIndices[escapePos][1], 2}) // 2 = escape tag.
630 }
631 minPos := -1
632 tagIndex := -1
633 for index, pair := range nextTag {
634 if minPos < 0 || pair[0] < minPos {
635 minPos = pair[0]
636 tagIndex = index
637 }
638 }
639
640 // Is the next tag in range?
641 if tagIndex < 0 || minPos >= tagEnd+remainingLength {
642 break // No. We're done with this line.
643 }
644
645 // Advance.
646 strippedTagStart := nextTag[tagIndex][0] - originalPos - totalTagLength
647 tagEnd = nextTag[tagIndex][1]
648 tagLength := tagEnd - nextTag[tagIndex][0]
649 if nextTag[tagIndex][2] == 2 {
650 tagLength = 1
651 }
652 totalTagLength += tagLength
653 remainingLength = lineLength - (tagEnd - originalPos - totalTagLength)
654
655 // Process the tag.
656 switch nextTag[tagIndex][2] {
657 case 0:
658 // Process color tags.
659 foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colorTags[colorPos])
660 colorPos++
661 case 1:
662 // Process region tags.
663 regionID = regions[regionPos][1]
664 _, highlighted = t.highlights[regionID]
665
666 // Update highlight range.
667 if highlighted {
668 line := len(t.index)
669 if t.fromHighlight < 0 {
670 t.fromHighlight, t.toHighlight = line, line
671 t.posHighlight = runewidth.StringWidth(splitLine[:strippedTagStart])
672 } else if line > t.toHighlight {
673 t.toHighlight = line
674 }
675 }
676
677 regionPos++
678 case 2:
679 // Process escape tags.
680 escapePos++
681 }
682 }
683
684 // Advance to next line.
685 originalPos += lineLength + totalTagLength
686
687 // Append this line.
688 line.NextPos = originalPos
689 line.Width = runewidth.StringWidth(splitLine)
690 t.index = append(t.index, line)
691 }
692
693 // Word-wrapped lines may have trailing whitespace. Remove it.
694 if t.wrap && t.wordWrap {
695 for _, line := range t.index {
696 str := t.buffer[line.Line][line.Pos:line.NextPos]
697 spaces := spacePattern.FindAllStringIndex(str, -1)
698 if spaces != nil && spaces[len(spaces)-1][1] == len(str) {
699 oldNextPos := line.NextPos
700 line.NextPos -= spaces[len(spaces)-1][1] - spaces[len(spaces)-1][0]
701 line.Width -= runewidth.StringWidth(t.buffer[line.Line][line.NextPos:oldNextPos])
702 }
703 }
704 }
705 }
706
707 // Calculate longest line.
708 t.longestLine = 0
709 for _, line := range t.index {
710 if line.Width > t.longestLine {
711 t.longestLine = line.Width
712 }
713 }
714 }
715
716 // Draw draws this primitive onto the screen.
717 func (t *TextView) Draw(screen Screen) {
718 t.Lock()
719 defer t.Unlock()
720
721 screen.SetStyle(t.baseStyle)
722 screen.Clear()
723
724 // Get the available size.
725 width, height := screen.Size()
726 t.pageSize = height
727
728 // If the width has changed, we need to reindex.
729 if width != t.lastWidth && t.wrap {
730 t.index = nil
731 }
732 t.lastWidth = width
733
734 // Re-index.
735 t.reindexBuffer(width)
736
737 // If we don't have an index, there's nothing to draw.
738 if t.index == nil {
739 return
740 }
741
742 // Move to highlighted regions.
743 if t.regions && t.scrollToHighlights && t.fromHighlight >= 0 {
744 // Do we fit the entire height?
745 if t.toHighlight-t.fromHighlight+1 < height {
746 // Yes, let's center the highlights.
747 t.lineOffset = (t.fromHighlight + t.toHighlight - height) / 2
748 } else {
749 // No, let's move to the start of the highlights.
750 t.lineOffset = t.fromHighlight
751 }
752
753 // If the highlight is too far to the right, move it to the middle.
754 if t.posHighlight-t.columnOffset > 3*width/4 {
755 t.columnOffset = t.posHighlight - width/2
756 }
757
758 // If the highlight is off-screen on the left, move it on-screen.
759 if t.posHighlight-t.columnOffset < 0 {
760 t.columnOffset = t.posHighlight - width/4
761 }
762 }
763 t.scrollToHighlights = false
764
765 // Adjust line offset.
766 if t.lineOffset+height > len(t.index) {
767 t.trackEnd = true
768 }
769 if t.trackEnd {
770 t.lineOffset = len(t.index) - height
771 }
772 if t.lineOffset < 0 {
773 t.lineOffset = 0
774 }
775
776 // Adjust column offset.
777 if t.align == AlignLeft {
778 if t.columnOffset+width > t.longestLine {
779 t.columnOffset = t.longestLine - width
780 }
781 if t.columnOffset < 0 {
782 t.columnOffset = 0
783 }
784 } else if t.align == AlignRight {
785 if t.columnOffset-width < -t.longestLine {
786 t.columnOffset = width - t.longestLine
787 }
788 if t.columnOffset > 0 {
789 t.columnOffset = 0
790 }
791 } else { // AlignCenter.
792 half := (t.longestLine - width) / 2
793 if half > 0 {
794 if t.columnOffset > half {
795 t.columnOffset = half
796 }
797 if t.columnOffset < -half {
798 t.columnOffset = -half
799 }
800 } else {
801 t.columnOffset = 0
802 }
803 }
804
805 // Draw the buffer.
806 defaultStyle := t.baseStyle
807 for line := t.lineOffset; line < len(t.index); line++ {
808 // Are we done?
809 if line-t.lineOffset >= height {
810 break
811 }
812
813 // Get the text for this line.
814 index := t.index[line]
815 text := t.buffer[index.Line][index.Pos:index.NextPos]
816 foregroundColor := index.ForegroundColor
817 backgroundColor := index.BackgroundColor
818 attributes := index.Attributes
819 regionID := index.Region
820
821 // Get color tags.
822 var (
823 colorTagIndices [][]int
824 colorTags [][]string
825 escapeIndices [][]int
826 )
827 strippedText := text
828 if t.dynamicColors {
829 colorTagIndices, colorTags, _, _, escapeIndices, strippedText, _ = decomposeString(text, true, false)
830 }
831
832 // Get regions.
833 var (
834 regionIndices [][]int
835 regions [][]string
836 )
837 if t.regions {
838 regionIndices = regionPattern.FindAllStringIndex(text, -1)
839 regions = regionPattern.FindAllStringSubmatch(text, -1)
840 strippedText = regionPattern.ReplaceAllString(strippedText, "")
841 if !t.dynamicColors {
842 escapeIndices = escapePattern.FindAllStringIndex(text, -1)
843 strippedText = escapePattern.ReplaceAllString(strippedText, "[$1$2]")
844 }
845 }
846
847 // Calculate the position of the line.
848 var skip, posX int
849 if t.align == AlignLeft {
850 posX = -t.columnOffset
851 } else if t.align == AlignRight {
852 posX = width - index.Width - t.columnOffset
853 } else { // AlignCenter.
854 posX = (width-index.Width)/2 - t.columnOffset
855 }
856 if posX < 0 {
857 skip = -posX
858 posX = 0
859 }
860
861 // Print the line.
862 var colorPos, regionPos, escapePos, tagOffset, skipped int
863 iterateString(strippedText, func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
864 // Process tags.
865 for {
866 if colorPos < len(colorTags) && textPos+tagOffset >= colorTagIndices[colorPos][0] && textPos+tagOffset < colorTagIndices[colorPos][1] {
867 // Get the color.
868 foregroundColor, backgroundColor, attributes = styleFromTag(foregroundColor, backgroundColor, attributes, colorTags[colorPos])
869 tagOffset += colorTagIndices[colorPos][1] - colorTagIndices[colorPos][0]
870 colorPos++
871 } else if regionPos < len(regionIndices) && textPos+tagOffset >= regionIndices[regionPos][0] && textPos+tagOffset < regionIndices[regionPos][1] {
872 // Get the region.
873 regionID = regions[regionPos][1]
874 tagOffset += regionIndices[regionPos][1] - regionIndices[regionPos][0]
875 regionPos++
876 } else {
877 break
878 }
879 }
880
881 // Skip the second-to-last character of an escape tag.
882 if escapePos < len(escapeIndices) && textPos+tagOffset == escapeIndices[escapePos][1]-2 {
883 tagOffset++
884 escapePos++
885 }
886
887 // Mix the existing style with the new style.
888 _, _, existingStyle, _ := screen.GetContent(posX, line-t.lineOffset)
889 _, background, _ := existingStyle.Decompose()
890 style := overlayStyle(defaultStyle.Background(background), foregroundColor, backgroundColor, attributes)
891
892 // Do we highlight this character?
893 var highlighted bool
894 if len(regionID) > 0 {
895 if _, ok := t.highlights[regionID]; ok {
896 highlighted = true
897 }
898 }
899 if highlighted {
900 _, _, attrs := style.Decompose()
901 reversed := attrs&tcell.AttrReverse != 0
902 style = style.Reverse(!reversed)
903 }
904
905 // Skip to the right.
906 if !t.wrap && skipped < skip {
907 skipped += screenWidth
908 return false
909 }
910
911 // Stop at the right border.
912 if posX+screenWidth > width {
913 return true
914 }
915
916 // Draw the character.
917 for offset := screenWidth - 1; offset >= 0; offset-- {
918 if offset == 0 {
919 screen.SetContent(posX+offset, line-t.lineOffset, main, comb, style)
920 } else {
921 screen.SetContent(posX+offset, line-t.lineOffset, ' ', nil, style)
922 }
923 }
924
925 // Advance.
926 posX += screenWidth
927 return false
928 })
929 }
930
931 // If this view is not scrollable, we'll purge the buffer of lines that have
932 // scrolled out of view.
933 if !t.scrollable && t.lineOffset > 0 {
934 t.buffer = t.buffer[t.index[t.lineOffset].Line:]
935 t.index = nil
936 }
937 }
938
939 func (t *TextView) Submit(event KeyEvent) bool {
940 return true
941 }
942
943 func (t *TextView) OnKeyEvent(event KeyEvent) bool {
944 key := event.Key()
945
946 if !t.scrollable {
947 return false
948 }
949
950 switch key {
951 case tcell.KeyRune:
952 switch event.Rune() {
953 case 'g': // Home.
954 t.trackEnd = false
955 t.lineOffset = 0
956 t.columnOffset = 0
957 case 'G': // End.
958 t.trackEnd = true
959 t.columnOffset = 0
960 case 'j': // Down.
961 t.lineOffset++
962 case 'k': // Up.
963 t.trackEnd = false
964 t.lineOffset--
965 case 'h': // Left.
966 t.columnOffset--
967 case 'l': // Right.
968 t.columnOffset++
969 }
970 case tcell.KeyHome:
971 t.trackEnd = false
972 t.lineOffset = 0
973 t.columnOffset = 0
974 case tcell.KeyEnd:
975 t.trackEnd = true
976 t.columnOffset = 0
977 case tcell.KeyUp:
978 t.trackEnd = false
979 t.lineOffset--
980 case tcell.KeyDown:
981 t.lineOffset++
982 case tcell.KeyLeft:
983 t.columnOffset--
984 case tcell.KeyRight:
985 t.columnOffset++
986 case tcell.KeyPgDn, tcell.KeyCtrlF:
987 t.lineOffset += t.pageSize
988 case tcell.KeyPgUp, tcell.KeyCtrlB:
989 t.trackEnd = false
990 t.lineOffset -= t.pageSize
991 default:
992 return false
993 }
994 return true
995 }
996
997 func (t *TextView) OnMouseEvent(event MouseEvent) bool {
998 if !t.scrollable {
999 return false
1000 }
1001
1002 switch event.Buttons() {
1003 case tcell.WheelDown:
1004 t.lineOffset += 3
1005 case tcell.WheelUp:
1006 t.lineOffset -= 3
1007 default:
1008 return false
1009 }
1010 return true
1011 }
1012
1013 func (t *TextView) OnPasteEvent(event PasteEvent) bool {
1014 return false
1015 }