xonecas.io
62159
Sy

symb / files

symb / internal / tui / editor / editor.go

14.8 KB
1// Package editor provides a minimal text editor component for bubbletea.
2// Supports optional line numbers, Chroma syntax highlighting, mouse cursor
3// placement, drag-to-select, and consistent background colors.
4package editor
5
6import (
7	"fmt"
8	"image/color"
9	"strings"
10
11	"charm.land/bubbles/v2/cursor"
12	"charm.land/lipgloss/v2"
13	"github.com/xonecas/symb/internal/highlight"
14)
15
16// ---------------------------------------------------------------------------
17// Model
18// ---------------------------------------------------------------------------
19
20// GutterMark identifies the type of change marker shown in the gutter.
21type GutterMark int
22
23const (
24	GutterAdd    GutterMark = iota // Line was added
25	GutterChange                   // Line was modified
26	GutterDelete                   // Line(s) deleted after this line
27)
28
29// Model is a minimal text editor / viewer component.
30type Model struct {
31	// Public configuration — set before first Update/View.
32	ReadOnly        bool
33	ShowLineNumbers bool
34	SubmitOnEnter   bool   // Enter is a no-op (parent handles submit); shift+enter inserts newline
35	Language        string // Chroma lexer name (empty = no highlighting)
36	SyntaxTheme     string // Chroma style name (empty = no highlighting)
37	Placeholder     string // Shown when empty and blurred
38
39	// Styles — set by parent.
40	CursorStyle    lipgloss.Style // Foreground for the cursor character
41	SelectionStyle lipgloss.Style // Background for selected text
42	LineNumStyle   lipgloss.Style // Line number gutter
43	PlaceholderSty lipgloss.Style // Placeholder text
44	BgColor        color.Color    // Fallback bg when no syntax theme
45
46	// Gutter markers (git diff indicators in line number column).
47	GutterMarkers map[int]GutterMark // bufRow (0-indexed) -> mark type
48	MarkAddStyle  lipgloss.Style     // Style for added-line marker
49	MarkChgStyle  lipgloss.Style     // Style for changed-line marker
50	MarkDelStyle  lipgloss.Style     // Style for deleted-line marker
51
52	// Per-line diagnostic severity (LSP). bufRow (0-indexed) -> severity (1=error, 2=warning).
53	DiagnosticLines map[int]int
54	DiagErrStyle    lipgloss.Style // Line number fg when line has error
55	DiagWarnStyle   lipgloss.Style // Line number fg when line has warning
56
57	// Internal state
58	lines  [][]rune // Backing store, one entry per line
59	row    int      // Cursor row (0-indexed into lines)
60	col    int      // Cursor column (0-indexed into line runes)
61	scroll int      // First visible row
62
63	width  int // Viewport width (cells)
64	height int // Viewport height (rows)
65
66	focus  bool
67	cursor cursor.Model
68
69	// Selection state (anchor + active pattern).
70	// Anchor is where selection started; active moves with cursor/drag.
71	sel      *selection
72	dragging bool // Mouse drag in progress
73
74	// Cached computed values
75	gutterWidth int // Width of line number gutter (0 if disabled)
76}
77
78type pos struct{ row, col int }
79
80// selection tracks a text selection via anchor+active points.
81// Anchor is fixed (where selection started); active moves with cursor/drag.
82type selection struct {
83	anchor pos
84	active pos
85}
86
87// ordered returns the selection endpoints in document order.
88func (s selection) ordered() (start, end pos) {
89	if s.anchor.row > s.active.row ||
90		(s.anchor.row == s.active.row && s.anchor.col > s.active.col) {
91		return s.active, s.anchor
92	}
93	return s.anchor, s.active
94}
95
96// empty returns true when anchor == active (no actual selection).
97func (s selection) empty() bool {
98	return s.anchor == s.active
99}
100
101// New creates a new editor with sensible defaults.
102func New() Model {
103	c := cursor.New()
104	c.SetMode(cursor.CursorStatic)
105	return Model{
106		lines:  [][]rune{{}},
107		cursor: c,
108	}
109}
110
111// ---------------------------------------------------------------------------
112// Public methods called by parent
113// ---------------------------------------------------------------------------
114
115func (m *Model) SetWidth(w int)  { m.width = w; m.clampScroll() }
116func (m *Model) SetHeight(h int) { m.height = h; m.clampScroll() }
117
118func (m *Model) Focus() {
119	m.focus = true
120	m.cursor.Focus()
121}
122
123func (m *Model) Blur() {
124	m.focus = false
125	m.cursor.Blur()
126}
127
128func (m Model) Focused() bool { return m.focus }
129
130func (m *Model) SetValue(s string) {
131	raw := strings.Split(s, "\n")
132	m.lines = make([][]rune, len(raw))
133	for i, l := range raw {
134		m.lines[i] = []rune(l)
135	}
136	if len(m.lines) == 0 {
137		m.lines = [][]rune{{}}
138	}
139	m.row = 0
140	m.col = 0
141	m.scroll = 0
142}
143
144func (m Model) Value() string {
145	var sb strings.Builder
146	for i, line := range m.lines {
147		sb.WriteString(string(line))
148		if i < len(m.lines)-1 {
149			sb.WriteByte('\n')
150		}
151	}
152	return sb.String()
153}
154
155func (m *Model) Reset() {
156	m.lines = [][]rune{{}}
157	m.row = 0
158	m.col = 0
159	m.scroll = 0
160}
161
162// GotoLine moves the cursor to the given 1-indexed line number and scrolls
163// it into view.
164func (m *Model) GotoLine(line int) {
165	line-- // convert to 0-indexed
166	if line < 0 {
167		line = 0
168	}
169	if line >= len(m.lines) {
170		line = len(m.lines) - 1
171	}
172	m.row = line
173	m.col = 0
174	m.clampScroll()
175}
176
177// ---------------------------------------------------------------------------
178// Selection API (called by parent)
179// ---------------------------------------------------------------------------
180
181// HasSelection returns true if there is a non-empty text selection.
182func (m Model) HasSelection() bool {
183	return m.sel != nil && !m.sel.empty()
184}
185
186// SelectedText returns the currently selected text, or "" if none.
187func (m Model) SelectedText() string {
188	if !m.HasSelection() {
189		return ""
190	}
191	s, e := m.sel.ordered()
192	return m.textInRange(s, e)
193}
194
195// ClearSelection removes any active selection.
196func (m *Model) ClearSelection() {
197	m.sel = nil
198	m.dragging = false
199}
200
201// textInRange extracts text between two buffer positions.
202func (m *Model) textInRange(start, end pos) string {
203	if start.row == end.row {
204		line := m.lines[start.row]
205		sc := clampMax(start.col, len(line))
206		ec := clampMax(end.col, len(line))
207		return string(line[sc:ec])
208	}
209	var sb strings.Builder
210	first := m.lines[start.row]
211	sb.WriteString(string(first[clampMax(start.col, len(first)):]))
212	for r := start.row + 1; r < end.row; r++ {
213		sb.WriteByte('\n')
214		sb.WriteString(string(m.lines[r]))
215	}
216	sb.WriteByte('\n')
217	last := m.lines[end.row]
218	sb.WriteString(string(last[:clampMax(end.col, len(last))]))
219	return sb.String()
220}
221
222// CursorOffset returns the rune offset of the cursor from the beginning of the document.
223func (m Model) CursorOffset() int {
224	offset := 0
225	for i := 0; i < m.row && i < len(m.lines); i++ {
226		offset += len(m.lines[i]) + 1 // +1 for newline
227	}
228	offset += m.col
229	return offset
230}
231
232// DeleteSelection removes the selected text and positions the cursor at the
233// start of the deleted range. Returns true if a selection was deleted.
234func (m *Model) DeleteSelection() bool {
235	if m.ReadOnly || !m.HasSelection() {
236		return false
237	}
238	s, e := m.sel.ordered()
239	m.ClearSelection()
240
241	// Clamp to valid range
242	s.row = clampMax(s.row, len(m.lines)-1)
243	s.col = clampMax(s.col, len(m.lines[s.row]))
244	e.row = clampMax(e.row, len(m.lines)-1)
245	e.col = clampMax(e.col, len(m.lines[e.row]))
246
247	if s.row == e.row {
248		line := m.lines[s.row]
249		m.lines[s.row] = append(line[:s.col], line[e.col:]...)
250	} else {
251		// Keep text before selection start + text after selection end
252		before := m.lines[s.row][:s.col]
253		after := m.lines[e.row][e.col:]
254		merged := make([]rune, 0, len(before)+len(after))
255		merged = append(merged, before...)
256		merged = append(merged, after...)
257		// Replace the range of lines
258		newLines := make([][]rune, 0, len(m.lines)-(e.row-s.row))
259		newLines = append(newLines, m.lines[:s.row]...)
260		newLines = append(newLines, merged)
261		newLines = append(newLines, m.lines[e.row+1:]...)
262		m.lines = newLines
263	}
264	if len(m.lines) == 0 {
265		m.lines = [][]rune{{}}
266	}
267	m.row = s.row
268	m.col = s.col
269	return true
270}
271
272func clampMax(v, hi int) int {
273	if v < 0 {
274		return 0
275	}
276	if v > hi {
277		return hi
278	}
279	return v
280}
281
282// startOrExtendSelection sets anchor to current cursor pos if no selection
283// exists, then after the caller moves the cursor, active is updated.
284func (m *Model) startOrExtendSelection() {
285	if m.sel == nil {
286		m.sel = &selection{
287			anchor: pos{row: m.row, col: m.col},
288			active: pos{row: m.row, col: m.col},
289		}
290	}
291}
292
293// updateSelectionActive sets the active end to the current cursor position.
294func (m *Model) updateSelectionActive() {
295	if m.sel != nil {
296		m.sel.active = pos{row: m.row, col: m.col}
297	}
298}
299
300// ---------------------------------------------------------------------------
301// Internal helpers
302// ---------------------------------------------------------------------------
303
304func (m *Model) currentLine() []rune { return m.lines[m.row] }
305
306func (m *Model) clampCursor() {
307	if m.row < 0 {
308		m.row = 0
309	}
310	if m.row >= len(m.lines) {
311		m.row = len(m.lines) - 1
312	}
313	if m.col < 0 {
314		m.col = 0
315	}
316	if m.col > len(m.currentLine()) {
317		m.col = len(m.currentLine())
318	}
319}
320
321// clampScrollBounds enforces scroll min/max without snapping to the cursor.
322// Use for mouse wheel scrolling where the viewport moves independently.
323func (m *Model) clampScrollBounds() {
324	if m.height <= 0 {
325		return
326	}
327	maxScroll := m.visualRowCount() - m.height
328	if maxScroll < 0 {
329		maxScroll = 0
330	}
331	if m.scroll > maxScroll {
332		m.scroll = maxScroll
333	}
334	if m.scroll < 0 {
335		m.scroll = 0
336	}
337}
338
339// clampScroll ensures the cursor's visual row is visible and scroll doesn't
340// exceed content bounds. m.scroll is a visual row offset.
341func (m *Model) clampScroll() {
342	if m.height <= 0 {
343		return
344	}
345	cvr := m.cursorVisualRow()
346	// Ensure cursor is visible
347	if cvr < m.scroll {
348		m.scroll = cvr
349	}
350	if cvr >= m.scroll+m.height {
351		m.scroll = cvr - m.height + 1
352	}
353	// Don't scroll past content
354	maxScroll := m.visualRowCount() - m.height
355	if maxScroll < 0 {
356		maxScroll = 0
357	}
358	if m.scroll > maxScroll {
359		m.scroll = maxScroll
360	}
361	if m.scroll < 0 {
362		m.scroll = 0
363	}
364}
365
366const tabWidth = 4
367
368// expandTabs replaces tabs with spaces (tabWidth-aligned).
369func expandTabs(s string) string {
370	var b strings.Builder
371	col := 0
372	for _, r := range s {
373		if r == '\t' {
374			spaces := tabWidth - (col % tabWidth)
375			b.WriteString(strings.Repeat(" ", spaces))
376			col += spaces
377		} else {
378			b.WriteRune(r)
379			col++
380		}
381	}
382	return b.String()
383}
384
385// textWidth returns the width available for text content.
386func (m *Model) textWidth() int {
387	m.gutterWidth = 0
388	if m.ShowLineNumbers {
389		digits := len(fmt.Sprintf("%d", len(m.lines)))
390		if digits < 2 {
391			digits = 2
392		}
393		m.gutterWidth = digits + 2 // digits + marker column + 1 space
394	}
395	w := m.width - m.gutterWidth
396	if w < 1 {
397		w = 1
398	}
399	return w
400}
401
402// SetGutterMarkers replaces the current gutter markers.
403// Keys are 0-indexed buffer row numbers.
404func (m *Model) SetGutterMarkers(markers map[int]GutterMark) {
405	m.GutterMarkers = markers
406}
407
408// renderGutterMark returns the styled single-character marker for a buffer row.
409// Falls back to a space (in lineNumSty) if no marker exists.
410func (m Model) renderGutterMark(bufRow int, lineNumSty lipgloss.Style) string {
411	mark, ok := m.GutterMarkers[bufRow]
412	if !ok {
413		return lineNumSty.Render(" ")
414	}
415	switch mark {
416	case GutterAdd:
417		return m.MarkAddStyle.Render("+")
418	case GutterChange:
419		return m.MarkChgStyle.Render("~")
420	case GutterDelete:
421		return m.MarkDelStyle.Render("-")
422	default:
423		return lineNumSty.Render(" ")
424	}
425}
426
427// ---------------------------------------------------------------------------
428// Soft line wrapping helpers
429// ---------------------------------------------------------------------------
430
431// wrapPlain splits a plain-text string into visual rows of at most `width`
432// runes. No ANSI awareness needed — call this on the raw expanded-tab text.
433func wrapPlain(s string, width int) []string {
434	if width <= 0 {
435		return []string{s}
436	}
437	runes := []rune(s)
438	if len(runes) <= width {
439		return []string{s}
440	}
441	var rows []string
442	for len(runes) > 0 {
443		end := width
444		if end > len(runes) {
445			end = len(runes)
446		}
447		rows = append(rows, string(runes[:end]))
448		runes = runes[end:]
449	}
450	return rows
451}
452
453// visualRowCount returns the total number of visual rows across all buffer
454// lines, given the text width for wrapping.
455func (m *Model) visualRowCount() int {
456	tw := m.textWidth()
457	total := 0
458	for _, line := range m.lines {
459		expanded := expandTabs(string(line))
460		n := len([]rune(expanded))
461		if n <= tw {
462			total++
463		} else {
464			total += (n + tw - 1) / tw
465		}
466	}
467	return total
468}
469
470// cursorVisualRow returns the visual row index of the current cursor position.
471func (m *Model) cursorVisualRow() int {
472	tw := m.textWidth()
473	vr := 0
474	for i := 0; i < m.row && i < len(m.lines); i++ {
475		expanded := expandTabs(string(m.lines[i]))
476		n := len([]rune(expanded))
477		if n <= tw {
478			vr++
479		} else {
480			vr += (n + tw - 1) / tw
481		}
482	}
483	// Add the sub-row within the cursor's line
484	if m.row < len(m.lines) {
485		// The cursor col in the expanded string
486		prefix := expandTabs(string(m.lines[m.row][:m.col]))
487		runeCol := len([]rune(prefix))
488		vr += runeCol / tw
489	}
490	return vr
491}
492
493// visualToBuffer converts a visual row index to a buffer row and the rune
494// offset (in the expanded line) at the start of that visual sub-row.
495func (m *Model) visualToBuffer(visRow int) (bufRow, runeOffset int) {
496	tw := m.textWidth()
497	vr := 0
498	for i, line := range m.lines {
499		expanded := expandTabs(string(line))
500		n := len([]rune(expanded))
501		rows := 1
502		if n > tw {
503			rows = (n + tw - 1) / tw
504		}
505		if vr+rows > visRow {
506			return i, (visRow - vr) * tw
507		}
508		vr += rows
509	}
510	// Past end — return last line
511	return len(m.lines) - 1, 0
512}
513
514// expandedColToBufferCol maps a column in the expanded-tab string back to the
515// corresponding rune index in the original buffer line.
516func (m *Model) expandedColToBufferCol(bufRow, expandedCol int) int {
517	if bufRow < 0 || bufRow >= len(m.lines) {
518		return 0
519	}
520	line := m.lines[bufRow]
521	col := 0 // visual column in expanded space
522	for i, r := range line {
523		if col >= expandedCol {
524			return i
525		}
526		if r == '\t' {
527			col += tabWidth - (col % tabWidth)
528		} else {
529			col++
530		}
531	}
532	return len(line)
533}
534
535// bufferColToExpandedCol converts a buffer column (rune index) to expanded-tab
536// column (visual column) for a given buffer row.
537func (m *Model) bufferColToExpandedCol(bufRow, bufCol int) int {
538	if bufRow < 0 || bufRow >= len(m.lines) {
539		return 0
540	}
541	line := m.lines[bufRow]
542	c := clampMax(bufCol, len(line))
543	prefix := expandTabs(string(line[:c]))
544	return len([]rune(prefix))
545}
546
547// bgForRender returns the background as a lipgloss style. Prefers the syntax
548// theme background, falls back to BgColor.
549func (m *Model) bgForRender() lipgloss.Style {
550	if m.Language != "" && m.SyntaxTheme != "" {
551		if hex := highlight.ThemeBg(m.SyntaxTheme); hex != "" {
552			return lipgloss.NewStyle().Background(lipgloss.Color(hex))
553		}
554	}
555	return lipgloss.NewStyle().Background(m.BgColor)
556}
557
558// bgHexForHighlight returns the bg hex string for syntax highlighting.
559func (m *Model) bgHexForHighlight() string {
560	if m.Language != "" && m.SyntaxTheme != "" {
561		if hex := highlight.ThemeBg(m.SyntaxTheme); hex != "" {
562			return hex
563		}
564	}
565	if m.BgColor != nil {
566		r, g, b, _ := m.BgColor.RGBA()
567		return fmt.Sprintf("#%02x%02x%02x", r>>8, g>>8, b>>8)
568	}
569	return "#000000"
570}