xonecas.io
62159
Sy

symb / commit 777dafe

fix: editor and conversation pane wrap

xonecas2026-02-12 777dafeeae4968447ef55be90bba746d8837086a parent 55a98b3

4 files changed

internal/tui/editor/editor.go+64−25
@@ -207,6 +207,24 @@ func (m *Model) clampCursor() {
207207 }
208208 }
209209
210+// clampScrollBounds enforces scroll min/max without snapping to the cursor.
211+// Use for mouse wheel scrolling where the viewport moves independently.
212+func (m *Model) clampScrollBounds() {
213+ if m.height <= 0 {
214+ return
215+ }
216+ maxScroll := m.visualRowCount() - m.height
217+ if maxScroll < 0 {
218+ maxScroll = 0
219+ }
220+ if m.scroll > maxScroll {
221+ m.scroll = maxScroll
222+ }
223+ if m.scroll < 0 {
224+ m.scroll = 0
225+ }
226+}
227+
210228 // clampScroll ensures the cursor's visual row is visible and scroll doesn't
211229 // exceed content bounds. m.scroll is a visual row offset.
212230 func (m *Model) clampScroll() {
@@ -687,10 +705,10 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
687705 }
688706 case tea.MouseButtonWheelUp:
689707 m.scroll -= 3
690- m.clampScroll()
708+ m.clampScrollBounds()
691709 case tea.MouseButtonWheelDown:
692710 m.scroll += 3
693- m.clampScroll()
711+ m.clampScrollBounds()
694712 }
695713 }
696714
@@ -721,14 +739,17 @@ func (m Model) View() string {
721739 lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
722740
723741 // Build a flat list of visual rows from visible buffer lines.
724- // Each visual row knows its buffer line index and sub-row index.
725742 type visualRow struct {
726- bufRow int // buffer line index
727- subRow int // 0 = first wrap segment, 1 = second, etc.
728- text string // plain text (expanded tabs) for this segment
743+ bufRow int // buffer line index
744+ subRow int // 0 = first wrap segment, 1 = second, etc.
745+ text string // plain text (expanded tabs) for this segment
746+ fullHL string // full-line highlighted ANSI (shared across sub-rows)
747+ segStart int // rune offset of this segment in the full line
748+ segEnd int // rune end offset
729749 }
730750
731751 var rows []visualRow
752+ hasSyntax := m.Language != "" && m.SyntaxTheme != ""
732753
733754 // Find which buffer line the scroll offset lands in.
734755 startBuf, startRuneOff := m.visualToBuffer(m.scroll)
@@ -743,12 +764,29 @@ func (m Model) View() string {
743764 for bufIdx := startBuf; bufIdx < len(m.lines) && len(rows) < m.height; bufIdx++ {
744765 lineStr := expandTabs(string(m.lines[bufIdx]))
745766 segments := wrapPlain(lineStr, tw)
767+
768+ // Highlight the full line once for all its segments.
769+ var fullHL string
770+ if hasSyntax {
771+ fullHL = cachedHighlight(lineStr, m.Language, m.SyntaxTheme)
772+ }
773+
746774 firstSub := 0
747775 if bufIdx == startBuf {
748776 firstSub = startSubRow
749777 }
778+ runeOff := firstSub * tw
750779 for subIdx := firstSub; subIdx < len(segments) && len(rows) < m.height; subIdx++ {
751- rows = append(rows, visualRow{bufRow: bufIdx, subRow: subIdx, text: segments[subIdx]})
780+ segLen := len([]rune(segments[subIdx]))
781+ rows = append(rows, visualRow{
782+ bufRow: bufIdx,
783+ subRow: subIdx,
784+ text: segments[subIdx],
785+ fullHL: fullHL,
786+ segStart: runeOff,
787+ segEnd: runeOff + segLen,
788+ })
789+ runeOff += segLen
752790 }
753791 }
754792
@@ -808,9 +846,9 @@ func (m Model) View() string {
808846 var rendered string
809847 if isCursorHere {
810848 localCol := cursorExpandedCol - segRuneOff
811- rendered = m.renderCursorSegment(segText, localCol)
812- } else if m.Language != "" && m.SyntaxTheme != "" {
813- rendered = cachedHighlight(segText, m.Language, m.SyntaxTheme)
849+ rendered = m.renderCursorSegment(segText, vr.fullHL, vr.segStart, localCol)
850+ } else if hasSyntax && vr.fullHL != "" {
851+ rendered = ansi.Cut(vr.fullHL, vr.segStart, vr.segEnd)
814852 } else {
815853 rendered = bg.Render(segText)
816854 }
@@ -831,8 +869,11 @@ func (m Model) View() string {
831869 }
832870
833871 // renderCursorSegment renders a text segment with the cursor at localCol.
834-// localCol is a rune index within segText.
835-func (m Model) renderCursorSegment(segText string, localCol int) string {
872+// localCol is a rune index within the segment's plain text.
873+// fullHL is the full-line highlighted ANSI string; segStart is the rune offset
874+// of this segment within it. Uses ansi.Cut to extract correctly-highlighted
875+// before/after portions so syntax coloring is never broken.
876+func (m Model) renderCursorSegment(segText, fullHL string, segStart, localCol int) string {
836877 bg := m.bgForRender()
837878 runes := []rune(segText)
838879
@@ -841,26 +882,24 @@ func (m Model) renderCursorSegment(segText string, localCol int) string {
841882 col = len(runes)
842883 }
843884
844- before := string(runes[:col])
845- after := ""
885+ // Extract the cursor character from the plain text.
846886 cursorChar := " "
847887 if col < len(runes) {
848888 cursorChar = string(runes[col])
849- after = string(runes[col+1:])
850889 }
851890
852- // Highlight segments if syntax is enabled
853891 hasSyntax := m.Language != "" && m.SyntaxTheme != ""
854- if hasSyntax {
855- if before != "" {
856- before = cachedHighlight(before, m.Language, m.SyntaxTheme)
857- }
858- if after != "" {
859- after = cachedHighlight(after, m.Language, m.SyntaxTheme)
860- }
892+ var before, after string
893+
894+ if hasSyntax && fullHL != "" {
895+ // Cut from the full-line highlight at absolute positions.
896+ absCursorCol := segStart + col
897+ before = ansi.Cut(fullHL, segStart, absCursorCol)
898+ after = ansi.Cut(fullHL, absCursorCol+1, segStart+len(runes))
861899 } else {
862- before = bg.Render(before)
863- after = bg.Render(after)
900+ highlighted := bg.Render(segText)
901+ before = ansi.Truncate(highlighted, col, "")
902+ after = ansi.TruncateLeft(highlighted, col+1, "")
864903 }
865904
866905 // Render cursor character
internal/tui/tui.go+61−73
@@ -2,7 +2,6 @@ package tui
22
33 import (
44 "context"
5- "fmt"
65 "image"
76 "strings"
87 "time"
@@ -234,7 +233,9 @@ type Model struct {
234233 cancel context.CancelFunc
235234
236235 // Conversation
237- conversation []string // Pre-wrapped, pre-styled lines
236+ convEntries []string // Raw styled lines (not wrapped)
237+ convLines []string // Wrapped visual lines (cache, rebuilt on width change)
238+ convCachedW int // Width used for current convLines cache
238239 scrollOffset int // Lines from bottom (0 = pinned)
239240
240241 // Mouse state
@@ -242,9 +243,6 @@ type Model struct {
242243 selecting bool
243244 selectStart int
244245 selectEnd int
245-
246- // Cache
247- wrapCache map[string][]string
248246 }
249247
250248 // New creates a new TUI model.
@@ -284,15 +282,14 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
284282 styles: sty,
285283 focus: focusInput,
286284
287- provider: prov,
288- mcpProxy: proxy,
289- mcpTools: tools,
290- history: []provider.Message{{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}},
291- conversation: []string{},
292- updateChan: ch,
293- ctx: ctx,
294- cancel: cancel,
295- wrapCache: make(map[string][]string),
285+ provider: prov,
286+ mcpProxy: proxy,
287+ mcpTools: tools,
288+ history: []provider.Message{{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}},
289+ convEntries: []string{},
290+ updateChan: ch,
291+ ctx: ctx,
292+ cancel: cancel,
296293 }
297294 }
298295
@@ -308,46 +305,46 @@ func (m Model) Init() tea.Cmd {
308305 // convWidth returns the usable width of the conversation pane.
309306 func (m Model) convWidth() int { return m.layout.conv.Dx() }
310307
311-// wrapText word-wraps text to conversation width and applies style.
312-// Wrapping is cached (width+text); styling is applied after lookup.
313-func (m Model) wrapText(text string, style lipgloss.Style) ([]string, Model) {
314- w := m.convWidth()
315- if w <= 0 {
316- lines := strings.Split(text, "\n")
317- out := make([]string, len(lines))
318- for i, l := range lines {
319- out[i] = style.Render(l)
320- }
321- return out, m
322- }
323-
324- // Cache stores unstyled wrapped lines — safe to reuse across styles.
325- key := fmt.Sprintf("%d:%s", w, text)
326- lines, ok := m.wrapCache[key]
327- if !ok {
328- wrapped := ansi.Wordwrap(text, w, "")
329- lines = strings.Split(wrapped, "\n")
330- if len(m.wrapCache) > 1000 {
331- m.wrapCache = make(map[string][]string)
332- }
333- m.wrapCache[key] = lines
334- }
335-
336- // Apply style after cache lookup.
337- out := make([]string, len(lines))
338- for i, l := range lines {
308+// styledLines applies a lipgloss style to each line in a multi-line text.
309+// No wrapping — lines are stored raw for later wrapping at render time.
310+func styledLines(text string, style lipgloss.Style) []string {
311+ raw := strings.Split(text, "\n")
312+ out := make([]string, len(raw))
313+ for i, l := range raw {
339314 out[i] = style.Render(l)
340315 }
341- return out, m
316+ return out
342317 }
343318
344-// appendConv appends lines and returns whether we were at bottom (for sticky scroll).
345-func (m *Model) appendConv(lines ...string) bool {
319+// appendConv appends raw styled entries and returns whether we were at bottom
320+// (for sticky scroll). Invalidates the wrapped-lines cache.
321+func (m *Model) appendConv(entries ...string) bool {
346322 atBottom := m.scrollOffset == 0
347- m.conversation = append(m.conversation, lines...)
323+ m.convEntries = append(m.convEntries, entries...)
324+ m.convLines = nil // invalidate cache
348325 return atBottom
349326 }
350327
328+// wrappedConvLines returns the conversation wrapped to the current convWidth.
329+// Cached — only recomputed when entries change (nil) or width changes.
330+func (m *Model) wrappedConvLines() []string {
331+ w := m.convWidth()
332+ if m.convLines != nil && m.convCachedW == w {
333+ return m.convLines
334+ }
335+ m.convCachedW = w
336+ lines := make([]string, 0, len(m.convEntries))
337+ for _, entry := range m.convEntries {
338+ if entry == "" {
339+ lines = append(lines, "")
340+ } else {
341+ lines = append(lines, wrapANSI(entry, w)...)
342+ }
343+ }
344+ m.convLines = lines
345+ return m.convLines
346+}
347+
351348 // makeSeparator builds a timestamp separator line.
352349 func (m Model) makeSeparator(dur string, ts string) string {
353350 label := dur + " " + ts + " "
@@ -419,9 +416,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
419416 m.history = append(m.history, provider.Message{
420417 Role: "user", Content: msg.content, CreatedAt: now,
421418 })
422- lines, m2 := m.wrapText(msg.content, m.styles.Text)
423- m = m2
424- m.appendConv(lines...)
419+ m.appendConv(styledLines(msg.content, m.styles.Text)...)
425420 m.appendConv("")
426421 sep := m.makeSeparator("0s", now.Format("15:04:05"))
427422 wasBottom := m.appendConv(sep)
@@ -437,27 +432,22 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
437432
438433 case llmAssistantMsg:
439434 if msg.reasoning != "" {
440- lines, m2 := m.wrapText(msg.reasoning, m.styles.Muted)
441- m = m2
442- wasBottom := m.appendConv(lines...)
435+ wasBottom := m.appendConv(styledLines(msg.reasoning, m.styles.Muted)...)
443436 m.appendConv("")
444437 if wasBottom {
445438 m.scrollOffset = 0
446439 }
447440 }
448441 if msg.content != "" {
449- lines, m2 := m.wrapText(msg.content, m.styles.Text)
450- m = m2
451- wasBottom := m.appendConv(lines...)
442+ wasBottom := m.appendConv(styledLines(msg.content, m.styles.Text)...)
452443 m.appendConv("")
453444 if wasBottom {
454445 m.scrollOffset = 0
455446 }
456447 }
457448 for _, tc := range msg.toolCalls {
458- lines, m2 := m.wrapText(m.styles.ToolArrow.Render("→")+" "+m.styles.ToolCall.Render(tc.Name+"(...)"), lipgloss.NewStyle())
459- m = m2
460- wasBottom := m.appendConv(lines...)
449+ entry := m.styles.ToolArrow.Render("→") + " " + m.styles.ToolCall.Render(tc.Name+"(...)")
450+ wasBottom := m.appendConv(entry)
461451 if wasBottom {
462452 m.scrollOffset = 0
463453 }
@@ -465,9 +455,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
465455 return m, m.waitForLLMUpdate()
466456
467457 case llmToolResultMsg:
468- lines, m2 := m.wrapText(m.styles.ToolArrow.Render("←")+" "+m.styles.Dim.Render(msg.content), lipgloss.NewStyle())
469- m = m2
470- wasBottom := m.appendConv(lines...)
458+ entry := m.styles.ToolArrow.Render("←") + " " + m.styles.Dim.Render(msg.content)
459+ wasBottom := m.appendConv(entry)
471460 if wasBottom {
472461 m.scrollOffset = 0
473462 }
@@ -583,7 +572,8 @@ func (m Model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
583572 // --- Conversation: scroll + selection -----------------------------------
584573 if inRect(msg.X, msg.Y, m.layout.conv) {
585574 convH := m.layout.conv.Dy()
586- totalLines := len(m.conversation)
575+ lines := m.wrappedConvLines()
576+ totalLines := len(lines)
587577
588578 switch msg.Button {
589579 case tea.MouseButtonLeft:
@@ -612,7 +602,7 @@ func (m Model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
612602
613603 var sb strings.Builder
614604 for i := start; i <= end; i++ {
615- sb.WriteString(ansi.Strip(m.conversation[i]))
605+ sb.WriteString(ansi.Strip(lines[i]))
616606 if i < end {
617607 sb.WriteByte('\n')
618608 }
@@ -637,9 +627,10 @@ func (m Model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
637627 return m, tea.Batch(cmds...)
638628 }
639629
640-// visibleStartLine returns the index of the first visible conversation line.
641-func (m Model) visibleStartLine() int {
642- total := len(m.conversation)
630+// visibleStartLine returns the index of the first visible wrapped conversation line.
631+func (m *Model) visibleStartLine() int {
632+ lines := m.wrappedConvLines()
633+ total := len(lines)
643634 visible := m.layout.conv.Dy()
644635 if total <= visible {
645636 return 0
@@ -668,7 +659,8 @@ func (m Model) View() string {
668659 editorLines := strings.Split(m.editor.View(), "\n")
669660 inputLines := strings.Split(m.agentInput.View(), "\n")
670661
671- // Conversation visible window
662+ // Conversation visible window (wrapped to current width)
663+ convLines := m.wrappedConvLines()
672664 startLine := m.visibleStartLine()
673665
674666 bgFill := m.styles.BgFill
@@ -701,8 +693,8 @@ func (m Model) View() string {
701693 if relY < ly.conv.Dy() {
702694 // Conversation area
703695 lineIdx := startLine + relY
704- if lineIdx < len(m.conversation) {
705- line := m.conversation[lineIdx]
696+ if lineIdx < len(convLines) {
697+ line := convLines[lineIdx]
706698
707699 // Selection highlight
708700 isSelected := false
@@ -718,10 +710,6 @@ func (m Model) View() string {
718710 }
719711
720712 lw := lipgloss.Width(line)
721- if lw > rw {
722- line = ansi.Truncate(line, rw, "")
723- lw = lipgloss.Width(line)
724- }
725713 b.WriteString(line)
726714 if lw < rw {
727715 pad := strings.Repeat(" ", rw-lw)
internal/tui/wrap.go+99−0
@@ -0,0 +1,99 @@
1+package tui
2+
3+import (
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.
12+func 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.
25+func 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.
53+func 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.
82+func 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.
88+func 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+}
internal/tui/wrap_test.go+80−0
@@ -0,0 +1,80 @@
1+package tui
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+func TestWrapANSIPreservesStyles(t *testing.T) {
9+ red := "\x1b[31m"
10+ bgBlack := "\x1b[40m"
11+ reset := "\x1b[0m"
12+
13+ // A red-on-black string that will wrap across multiple lines.
14+ text := red + bgBlack + strings.Repeat("hello ", 20) + reset
15+
16+ lines := wrapANSI(text, 30)
17+
18+ if len(lines) < 2 {
19+ t.Fatalf("expected multiple lines, got %d", len(lines))
20+ }
21+
22+ // Every continuation line must start with the active style sequences.
23+ for i, line := range lines {
24+ if i == 0 {
25+ // First line should start with the original sequences.
26+ if !strings.HasPrefix(line, red+bgBlack) {
27+ t.Errorf("line 0: expected style prefix, got %q", line[:min(len(line), 30)])
28+ }
29+ continue
30+ }
31+ // Continuation lines must have the style re-opened.
32+ if !strings.Contains(line, "\x1b[31m") {
33+ t.Errorf("line %d: missing red foreground sequence: %q", i, line)
34+ }
35+ if !strings.Contains(line, "\x1b[40m") {
36+ t.Errorf("line %d: missing black background sequence: %q", i, line)
37+ }
38+ }
39+
40+ // All lines except the last should end with a reset.
41+ for i := 0; i < len(lines)-1; i++ {
42+ if !strings.HasSuffix(lines[i], "\x1b[m") {
43+ t.Errorf("line %d: should end with reset, got %q", i, lines[i][max(0, len(lines[i])-10):])
44+ }
45+ }
46+}
47+
48+func TestWrapANSIResetClearsState(t *testing.T) {
49+ red := "\x1b[31m"
50+ reset := "\x1b[0m"
51+
52+ // Style, some text, reset, more text — the continuation after reset
53+ // should NOT carry the red style.
54+ text := red + "aaaa" + reset + " " + strings.Repeat("b", 30)
55+
56+ lines := wrapANSI(text, 10)
57+
58+ if len(lines) < 2 {
59+ t.Fatalf("expected multiple lines, got %d", len(lines))
60+ }
61+
62+ // After the reset, continuation lines should NOT have red.
63+ for i := 1; i < len(lines); i++ {
64+ if strings.Contains(lines[i], "\x1b[31m") {
65+ t.Errorf("line %d: should not have red after reset: %q", i, lines[i])
66+ }
67+ }
68+}
69+
70+func TestWrapANSINoStylePassthrough(t *testing.T) {
71+ // Plain text should pass through unchanged (no spurious sequences added).
72+ text := "hello world this is a test of plain text wrapping"
73+ lines := wrapANSI(text, 15)
74+
75+ for i, line := range lines {
76+ if strings.Contains(line, "\x1b") {
77+ t.Errorf("line %d: unexpected ANSI sequence in plain text: %q", i, line)
78+ }
79+ }
80+}