xonecas.io
62159
Sy

symb / commit 55a98b3

fix: add soft line wrapping to editor component

Long lines now wrap to continuation rows instead of being truncated.
Scroll, cursor, and mouse click all work in visual-row space.

xonecas2026-02-12 55a98b3a594dd8b4705159e6dbf105185bba51e0 parent 9a96378

2 files changed

internal/tui/editor/editor.go+204−32
@@ -207,19 +207,22 @@ func (m *Model) clampCursor() {
207207 }
208208 }
209209
210+// clampScroll ensures the cursor's visual row is visible and scroll doesn't
211+// exceed content bounds. m.scroll is a visual row offset.
210212 func (m *Model) clampScroll() {
211213 if m.height <= 0 {
212214 return
213215 }
216+ cvr := m.cursorVisualRow()
214217 // Ensure cursor is visible
215- if m.row < m.scroll {
216- m.scroll = m.row
218+ if cvr < m.scroll {
219+ m.scroll = cvr
217220 }
218- if m.row >= m.scroll+m.height {
219- m.scroll = m.row - m.height + 1
221+ if cvr >= m.scroll+m.height {
222+ m.scroll = cvr - m.height + 1
220223 }
221224 // Don't scroll past content
222- maxScroll := len(m.lines) - m.height
225+ maxScroll := m.visualRowCount() - m.height
223226 if maxScroll < 0 {
224227 maxScroll = 0
225228 }
@@ -267,6 +270,114 @@ func (m *Model) textWidth() int {
267270 return w
268271 }
269272
273+// ---------------------------------------------------------------------------
274+// Soft line wrapping helpers
275+// ---------------------------------------------------------------------------
276+
277+// wrapPlain splits a plain-text string into visual rows of at most `width`
278+// runes. No ANSI awareness needed — call this on the raw expanded-tab text.
279+func wrapPlain(s string, width int) []string {
280+ if width <= 0 {
281+ return []string{s}
282+ }
283+ runes := []rune(s)
284+ if len(runes) <= width {
285+ return []string{s}
286+ }
287+ var rows []string
288+ for len(runes) > 0 {
289+ end := width
290+ if end > len(runes) {
291+ end = len(runes)
292+ }
293+ rows = append(rows, string(runes[:end]))
294+ runes = runes[end:]
295+ }
296+ return rows
297+}
298+
299+// visualRowCount returns the total number of visual rows across all buffer
300+// lines, given the text width for wrapping.
301+func (m *Model) visualRowCount() int {
302+ tw := m.textWidth()
303+ total := 0
304+ for _, line := range m.lines {
305+ expanded := expandTabs(string(line))
306+ n := len([]rune(expanded))
307+ if n <= tw {
308+ total++
309+ } else {
310+ total += (n + tw - 1) / tw
311+ }
312+ }
313+ return total
314+}
315+
316+// cursorVisualRow returns the visual row index of the current cursor position.
317+func (m *Model) cursorVisualRow() int {
318+ tw := m.textWidth()
319+ vr := 0
320+ for i := 0; i < m.row && i < len(m.lines); i++ {
321+ expanded := expandTabs(string(m.lines[i]))
322+ n := len([]rune(expanded))
323+ if n <= tw {
324+ vr++
325+ } else {
326+ vr += (n + tw - 1) / tw
327+ }
328+ }
329+ // Add the sub-row within the cursor's line
330+ if m.row < len(m.lines) {
331+ // The cursor col in the expanded string
332+ prefix := expandTabs(string(m.lines[m.row][:m.col]))
333+ runeCol := len([]rune(prefix))
334+ vr += runeCol / tw
335+ }
336+ return vr
337+}
338+
339+// visualToBuffer converts a visual row index to a buffer row and the rune
340+// offset (in the expanded line) at the start of that visual sub-row.
341+func (m *Model) visualToBuffer(visRow int) (bufRow, runeOffset int) {
342+ tw := m.textWidth()
343+ vr := 0
344+ for i, line := range m.lines {
345+ expanded := expandTabs(string(line))
346+ n := len([]rune(expanded))
347+ rows := 1
348+ if n > tw {
349+ rows = (n + tw - 1) / tw
350+ }
351+ if vr+rows > visRow {
352+ return i, (visRow - vr) * tw
353+ }
354+ vr += rows
355+ }
356+ // Past end — return last line
357+ return len(m.lines) - 1, 0
358+}
359+
360+// expandedColToBufferCol maps a column in the expanded-tab string back to the
361+// corresponding rune index in the original buffer line.
362+func (m *Model) expandedColToBufferCol(bufRow, expandedCol int) int {
363+ if bufRow < 0 || bufRow >= len(m.lines) {
364+ return 0
365+ }
366+ line := m.lines[bufRow]
367+ col := 0 // visual column in expanded space
368+ for i, r := range line {
369+ if col >= expandedCol {
370+ return i
371+ }
372+ if r == '\t' {
373+ col += tabWidth - (col % tabWidth)
374+ } else {
375+ col++
376+ }
377+ }
378+ return len(line)
379+}
380+
270381 // bgForRender returns the background style. Extracts from syntax theme if
271382 // available, falls back to BgColor.
272383 func (m *Model) bgForRender() lipgloss.Style {
@@ -420,23 +531,23 @@ func (m *Model) selectedText() string {
420531 }
421532
422533 // screenToPos converts screen-relative x,y to a buffer row,col.
534+// x,y are relative to the editor component origin.
423535 func (m *Model) screenToPos(x, y int) pos {
424- row := m.scroll + y
425- if row < 0 {
426- row = 0
427- }
428- if row >= len(m.lines) {
429- row = len(m.lines) - 1
536+ visRow := m.scroll + y
537+ if visRow < 0 {
538+ visRow = 0
430539 }
540+ bufRow, runeOffset := m.visualToBuffer(visRow)
541+
431542 col := x - m.gutterWidth
432543 if col < 0 {
433544 col = 0
434545 }
435- lineLen := len(m.lines[row])
436- if col > lineLen {
437- col = lineLen
438- }
439- return pos{row: row, col: col}
546+ // runeOffset is in expanded-tab space; convert back to buffer col.
547+ // We need to find which buffer rune corresponds to runeOffset + col
548+ // in the expanded string.
549+ bufCol := m.expandedColToBufferCol(bufRow, runeOffset+col)
550+ return pos{row: bufRow, col: bufCol}
440551 }
441552
442553 func clampMax(v, hi int) int {
@@ -609,42 +720,102 @@ func (m Model) View() string {
609720 bg := m.bgForRender()
610721 lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
611722
723+ // Build a flat list of visual rows from visible buffer lines.
724+ // Each visual row knows its buffer line index and sub-row index.
725+ 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
729+ }
730+
731+ var rows []visualRow
732+
733+ // Find which buffer line the scroll offset lands in.
734+ startBuf, startRuneOff := m.visualToBuffer(m.scroll)
735+
736+ // Pre-compute the sub-row index for the starting buffer line.
737+ startSubRow := 0
738+ if startRuneOff > 0 && tw > 0 {
739+ startSubRow = startRuneOff / tw
740+ }
741+
742+ // Generate visual rows starting from the scroll position.
743+ for bufIdx := startBuf; bufIdx < len(m.lines) && len(rows) < m.height; bufIdx++ {
744+ lineStr := expandTabs(string(m.lines[bufIdx]))
745+ segments := wrapPlain(lineStr, tw)
746+ firstSub := 0
747+ if bufIdx == startBuf {
748+ firstSub = startSubRow
749+ }
750+ for subIdx := firstSub; subIdx < len(segments) && len(rows) < m.height; subIdx++ {
751+ rows = append(rows, visualRow{bufRow: bufIdx, subRow: subIdx, text: segments[subIdx]})
752+ }
753+ }
754+
755+ // Determine cursor position in expanded-tab space for the cursor line.
756+ cursorExpandedCol := -1
757+ if m.focus && m.row >= 0 && m.row < len(m.lines) {
758+ prefix := expandTabs(string(m.lines[m.row][:m.col]))
759+ cursorExpandedCol = len([]rune(prefix))
760+ }
761+
612762 var b strings.Builder
613763
614764 for vi := 0; vi < m.height; vi++ {
615- row := m.scroll + vi
616765 if vi > 0 {
617766 b.WriteByte('\n')
618767 }
619768
620- if row >= len(m.lines) {
769+ if vi >= len(rows) {
621770 // End-of-buffer: fill entire row with bg
622771 b.WriteString(bg.Render(strings.Repeat(" ", m.width)))
623772 continue
624773 }
625774
775+ vr := rows[vi]
776+
626777 // -- Gutter (line numbers) -------------------------------------------
627778 if m.ShowLineNumbers {
628779 digits := m.gutterWidth - 1
629- num := fmt.Sprintf("%*d ", digits, row+1)
630- b.WriteString(lineNumSty.Render(num))
780+ if vr.subRow == 0 {
781+ num := fmt.Sprintf("%*d ", digits, vr.bufRow+1)
782+ b.WriteString(lineNumSty.Render(num))
783+ } else {
784+ // Continuation row — blank gutter
785+ b.WriteString(lineNumSty.Render(strings.Repeat(" ", m.gutterWidth)))
786+ }
631787 }
632788
633789 // -- Text content ----------------------------------------------------
634- line := m.lines[row]
635- lineStr := expandTabs(string(line))
636- isCursorRow := m.focus && row == m.row
790+ segText := vr.text
791+ segRuneOff := vr.subRow * tw // rune offset within the full expanded line
792+ segLen := len([]rune(segText))
793+
794+ // Is the cursor on this visual row?
795+ // Cursor is here if it falls within this segment's rune range,
796+ // OR if it's at end-of-segment and this is the last sub-row
797+ // (cursor past last char sits on the last segment).
798+ isCursorHere := false
799+ if m.focus && vr.bufRow == m.row {
800+ if cursorExpandedCol >= segRuneOff && cursorExpandedCol < segRuneOff+tw {
801+ isCursorHere = true
802+ } else if cursorExpandedCol == segRuneOff+segLen && segLen < tw {
803+ // End-of-line cursor on a short (last) segment
804+ isCursorHere = true
805+ }
806+ }
637807
638808 var rendered string
639- if isCursorRow {
640- rendered = m.renderCursorLine(lineStr)
809+ if isCursorHere {
810+ localCol := cursorExpandedCol - segRuneOff
811+ rendered = m.renderCursorSegment(segText, localCol)
641812 } else if m.Language != "" && m.SyntaxTheme != "" {
642- rendered = cachedHighlight(lineStr, m.Language, m.SyntaxTheme)
813+ rendered = cachedHighlight(segText, m.Language, m.SyntaxTheme)
643814 } else {
644- rendered = bg.Render(lineStr)
815+ rendered = bg.Render(segText)
645816 }
646817
647- // Truncate to text width and pad
818+ // Pad to text width
648819 rw := lipgloss.Width(rendered)
649820 if rw > tw {
650821 rendered = ansi.Truncate(rendered, tw, "")
@@ -659,12 +830,13 @@ func (m Model) View() string {
659830 return b.String()
660831 }
661832
662-// renderCursorLine renders the cursor row with the cursor character visible.
663-func (m Model) renderCursorLine(lineStr string) string {
833+// 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 {
664836 bg := m.bgForRender()
665- runes := []rune(lineStr)
837+ runes := []rune(segText)
666838
667- col := m.col
839+ col := localCol
668840 if col > len(runes) {
669841 col = len(runes)
670842 }
internal/tui/editor/editor_test.go+76−2
@@ -36,14 +36,88 @@ func TestLineWidthWithTabs(t *testing.T) {
3636 }
3737 }
3838
39+func TestSoftLineWrap(t *testing.T) {
40+ ed := New()
41+ ed.ShowLineNumbers = true
42+ ed.ReadOnly = true
43+ ed.BgColor = lipgloss.Color("#000000")
44+ ed.LineNumStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#666666"))
45+
46+ // Width 30, gutter ~3 chars ("_1 "), so text width = 27.
47+ // Line "abcdefghij..." (40 chars) should wrap into 2 visual rows.
48+ ed.SetWidth(30)
49+ ed.SetHeight(10)
50+ ed.SetValue("short\n" + strings.Repeat("a", 40) + "\nend")
51+
52+ view := ed.View()
53+ lines := strings.Split(view, "\n")
54+
55+ // Should have: line 1 (short), line 2 wrap-1, line 2 wrap-2, line 3 (end), + 6 empty = 10
56+ if len(lines) != 10 {
57+ t.Errorf("expected 10 visual rows, got %d", len(lines))
58+ }
59+ // Every visual row must be exactly 30 wide.
60+ for i, line := range lines {
61+ w := lipgloss.Width(line)
62+ if w != 30 {
63+ t.Errorf("visual row %d: width=%d (want 30)", i, w)
64+ }
65+ }
66+
67+ // The long line should produce a continuation row with blank gutter.
68+ // First visual row of long line should have "2" in gutter, second should not.
69+ if len(lines) >= 3 {
70+ // Row index 1 = first segment of buffer line 2 → should have "2" in gutter
71+ if !strings.Contains(lines[1], "2") {
72+ t.Errorf("visual row 1 should show line number 2, got: %q", lines[1])
73+ }
74+ }
75+}
76+
77+func TestWrapPlain(t *testing.T) {
78+ cases := []struct {
79+ in string
80+ width int
81+ want int // number of segments
82+ }{
83+ {"hello", 10, 1},
84+ {"hello world!!!", 5, 3}, // "hello", " worl", "d!!!"
85+ {"", 5, 1},
86+ {strings.Repeat("x", 20), 7, 3}, // 7+7+6
87+ }
88+ for _, tc := range cases {
89+ got := wrapPlain(tc.in, tc.width)
90+ if len(got) != tc.want {
91+ t.Errorf("wrapPlain(%q, %d) = %d segments, want %d: %v",
92+ tc.in, tc.width, len(got), tc.want, got)
93+ }
94+ }
95+}
96+
97+func TestVisualRowCount(t *testing.T) {
98+ ed := New()
99+ ed.SetWidth(10) // no line numbers, so textWidth = 10
100+ ed.SetHeight(20)
101+ ed.SetValue("short\n" + strings.Repeat("a", 25) + "\nend")
102+
103+ // Line 0: "short" (5 chars) → 1 visual row
104+ // Line 1: 25 chars → ceil(25/10) = 3 visual rows
105+ // Line 2: "end" (3 chars) → 1 visual row
106+ // Total: 5
107+ got := ed.visualRowCount()
108+ if got != 5 {
109+ t.Errorf("visualRowCount() = %d, want 5", got)
110+ }
111+}
112+
39113 func TestExpandTabs(t *testing.T) {
40114 cases := []struct {
41115 in string
42116 want int // visual width (all chars are ASCII, so rune count = display width)
43117 }{
44- {"\thello", 4 + 5}, // 1 tab (4 spaces) + "hello"
118+ {"\thello", 4 + 5}, // 1 tab (4 spaces) + "hello"
45119 {"\t\thello", 4 + 4 + 5}, // 2 tabs + "hello"
46- {"ab\tc", 2 + 2 + 1}, // "ab" then tab to col 4, then "c"
120+ {"ab\tc", 2 + 2 + 1}, // "ab" then tab to col 4, then "c"
47121 {"no tabs", 7},
48122 }
49123 for _, tc := range cases {