xonecas.io
62159
Sy

symb / files

symb / internal / tui / wrap.go

2.6 KB
1package tui
2
3import (
4	"strings"
5
6	"github.com/charmbracelet/x/ansi"
7)
8
9// wrapANSI word-wraps an ANSI-styled string to the given width, returning
10// the resulting visual lines. Styles are propagated across line breaks so
11// each line is independently renderable.
12func wrapANSI(s string, width int) []string {
13	if width <= 0 || s == "" {
14		return []string{s}
15	}
16	wrapped := ansi.Wordwrap(s, width, "")
17	wrapped = ansi.Hardwrap(wrapped, width, true)
18	lines := splitLines(wrapped)
19	return propagateStyles(lines)
20}
21
22// propagateStyles ensures each line carries the ANSI style state from
23// previous lines. After this, every line can be rendered independently
24// with correct colors/attributes.
25func propagateStyles(lines []string) []string {
26	if len(lines) <= 1 {
27		return lines
28	}
29
30	var activeSeqs []string // non-reset SGR sequences currently active
31
32	for i, line := range lines {
33		// Prepend active style to continuation lines.
34		if i > 0 && len(activeSeqs) > 0 {
35			lines[i] = strings.Join(activeSeqs, "") + line
36		}
37
38		// Scan this line for SGR sequences to update active state.
39		activeSeqs = scanSGR(line, activeSeqs)
40
41		// Append reset at end of each line (except last) so padding
42		// after the line doesn't inherit the style.
43		if i < len(lines)-1 && len(activeSeqs) > 0 {
44			lines[i] = lines[i] + ansi.ResetStyle
45		}
46	}
47
48	return lines
49}
50
51// scanSGR scans a line for SGR escape sequences and updates the active
52// sequence list. Resets clear the list; other SGRs are appended.
53func scanSGR(line string, active []string) []string {
54	const esc = '\x1b'
55	for j := 0; j < len(line); j++ {
56		if line[j] != byte(esc) || j+1 >= len(line) || line[j+1] != '[' {
57			continue
58		}
59		// Found ESC[, scan to find the 'm' terminator (SGR).
60		k := j + 2
61		for k < len(line) && line[k] != 'm' && line[k] != esc {
62			k++
63		}
64		if k >= len(line) || line[k] != 'm' {
65			continue
66		}
67		seq := line[j : k+1] // e.g. "\x1b[31m" or "\x1b[0m"
68		params := line[j+2 : k]
69
70		if isResetSGR(params) {
71			active = active[:0]
72		} else {
73			active = append(active, seq)
74		}
75		j = k // skip past the sequence
76	}
77	return active
78}
79
80// isResetSGR returns true if the SGR parameter string represents a reset.
81// A reset is "0", "" or standalone zero.
82func isResetSGR(params string) bool {
83	return params == "" || params == "0"
84}
85
86// splitLines splits on newline without the trailing empty element that
87// strings.Split produces for a trailing newline.
88func splitLines(s string) []string {
89	lines := make([]string, 0, 8)
90	start := 0
91	for i := 0; i < len(s); i++ {
92		if s[i] == '\n' {
93			lines = append(lines, s[start:i])
94			start = i + 1
95		}
96	}
97	lines = append(lines, s[start:])
98	return lines
99}