xonecas.io
62159
Sy

symb / commit aec43cf

feat: break editor into smaller files

xonecas2026-02-13 aec43cf0c0779cdb4ed00ab3b0fd0f100e8cf452 parent e3247e8

5 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

internal/tui/editor/editing.go+111−0
@@ -0,0 +1,111 @@
1+package editor
2+
3+// ---------------------------------------------------------------------------
4+// Editing operations
5+// ---------------------------------------------------------------------------
6+
7+// InsertText inserts a multi-line string at the current cursor position.
8+// Newlines are handled via insertNewline. No-op if ReadOnly.
9+func (m *Model) InsertText(text string) {
10+ if m.ReadOnly {
11+ return
12+ }
13+ for _, r := range text {
14+ switch r {
15+ case '\n':
16+ m.insertNewline()
17+ case '\r':
18+ // Skip carriage returns (normalize \r\n to \n)
19+ default:
20+ m.insertRune(r)
21+ }
22+ }
23+}
24+
25+func (m *Model) insertRune(r rune) {
26+ if m.ReadOnly {
27+ return
28+ }
29+ line := m.currentLine()
30+ newLine := make([]rune, 0, len(line)+1)
31+ newLine = append(newLine, line[:m.col]...)
32+ newLine = append(newLine, r)
33+ newLine = append(newLine, line[m.col:]...)
34+ m.lines[m.row] = newLine
35+ m.col++
36+}
37+
38+func (m *Model) insertNewline() {
39+ if m.ReadOnly {
40+ return
41+ }
42+ line := m.currentLine()
43+ after := make([]rune, len(line[m.col:]))
44+ copy(after, line[m.col:])
45+ m.lines[m.row] = line[:m.col]
46+ // Insert new line after current
47+ newLines := make([][]rune, 0, len(m.lines)+1)
48+ newLines = append(newLines, m.lines[:m.row+1]...)
49+ newLines = append(newLines, after)
50+ newLines = append(newLines, m.lines[m.row+1:]...)
51+ m.lines = newLines
52+ m.row++
53+ m.col = 0
54+}
55+
56+func (m *Model) deleteBack() {
57+ if m.ReadOnly {
58+ return
59+ }
60+ if m.col > 0 {
61+ line := m.currentLine()
62+ m.lines[m.row] = append(line[:m.col-1], line[m.col:]...)
63+ m.col--
64+ } else if m.row > 0 {
65+ // Merge with previous line
66+ prev := m.lines[m.row-1]
67+ m.col = len(prev)
68+ m.lines[m.row-1] = append(prev, m.currentLine()...)
69+ m.lines = append(m.lines[:m.row], m.lines[m.row+1:]...)
70+ m.row--
71+ }
72+}
73+
74+func (m *Model) deleteForward() {
75+ if m.ReadOnly {
76+ return
77+ }
78+ line := m.currentLine()
79+ if m.col < len(line) {
80+ m.lines[m.row] = append(line[:m.col], line[m.col+1:]...)
81+ } else if m.row < len(m.lines)-1 {
82+ // Merge with next line
83+ m.lines[m.row] = append(line, m.lines[m.row+1]...)
84+ m.lines = append(m.lines[:m.row+1], m.lines[m.row+2:]...)
85+ }
86+}
87+
88+func (m *Model) tabIndent() {
89+ if m.ReadOnly {
90+ return
91+ }
92+ // Indent to match the leading whitespace of the line above.
93+ indent := "\t"
94+ if m.row > 0 {
95+ above := m.lines[m.row-1]
96+ indent = ""
97+ for _, r := range above {
98+ if r == ' ' || r == '\t' {
99+ indent += string(r)
100+ } else {
101+ break
102+ }
103+ }
104+ if indent == "" {
105+ indent = "\t"
106+ }
107+ }
108+ for _, r := range indent {
109+ m.insertRune(r)
110+ }
111+}
internal/tui/editor/editor.go+0−836
@@ -7,121 +7,12 @@ import (
77 "fmt"
88 "image/color"
99 "strings"
10- "sync"
1110
1211 "charm.land/bubbles/v2/cursor"
1312 tea "charm.land/bubbletea/v2"
1413 "charm.land/lipgloss/v2"
15- "github.com/alecthomas/chroma/v2"
16- "github.com/alecthomas/chroma/v2/formatters"
17- "github.com/alecthomas/chroma/v2/lexers"
18- "github.com/alecthomas/chroma/v2/styles"
19- "github.com/charmbracelet/x/ansi"
2014 )
2115
22-// ---------------------------------------------------------------------------
23-// Highlight cache (global, shared across instances)
24-// ---------------------------------------------------------------------------
25-
26-var (
27- hlCache = make(map[string]string)
28- hlCacheMu sync.RWMutex
29-)
30-
31-func cachedHighlight(text, language, theme, bgHex string) string {
32- cacheKey := language + ":" + theme + ":" + bgHex + ":" + text
33- hlCacheMu.RLock()
34- if v, ok := hlCache[cacheKey]; ok {
35- hlCacheMu.RUnlock()
36- return v
37- }
38- hlCacheMu.RUnlock()
39-
40- lex := lexers.Get(language)
41- if lex == nil {
42- return text
43- }
44- lex = chroma.Coalesce(lex)
45- sty := styles.Get(theme)
46- fmtr := formatters.Get("terminal16m")
47- if fmtr == nil {
48- fmtr = formatters.Fallback
49- }
50- it, err := lex.Tokenise(nil, text)
51- if err != nil {
52- return text
53- }
54- var buf strings.Builder
55- if err := fmtr.Format(&buf, sty, it); err != nil {
56- return text
57- }
58- raw := strings.TrimRight(buf.String(), "\n")
59-
60- // Chroma's terminal16m formatter skips bg on tokens that inherit from
61- // the Background entry, and every \x1b[0m reset clears bg. Fix by
62- // replacing resets with reset+bg so the background is always active.
63- bgSeq := hexToBgSeq(bgHex)
64- result := bgSeq + strings.ReplaceAll(raw, "\x1b[0m", "\x1b[0m"+bgSeq)
65-
66- hlCacheMu.Lock()
67- if len(hlCache) > 2000 {
68- hlCache = make(map[string]string)
69- }
70- hlCache[cacheKey] = result
71- hlCacheMu.Unlock()
72- return result
73-}
74-
75-// hexToBgSeq converts "#rrggbb" to an ANSI 24-bit background escape sequence.
76-func hexToBgSeq(hex string) string {
77- if len(hex) != 7 || hex[0] != '#' {
78- return ""
79- }
80- r := hexByte(hex[1], hex[2])
81- g := hexByte(hex[3], hex[4])
82- b := hexByte(hex[5], hex[6])
83- return fmt.Sprintf("\x1b[48;2;%d;%d;%dm", r, g, b)
84-}
85-
86-func hexByte(hi, lo byte) int {
87- return hexNibble(hi)<<4 | hexNibble(lo)
88-}
89-
90-func hexNibble(c byte) int {
91- switch {
92- case c >= '0' && c <= '9':
93- return int(c - '0')
94- case c >= 'a' && c <= 'f':
95- return int(c-'a') + 10
96- case c >= 'A' && c <= 'F':
97- return int(c-'A') + 10
98- }
99- return 0
100-}
101-
102-// colorToBgSeq converts a color.Color to an ANSI 24-bit background escape.
103-func colorToBgSeq(c color.Color) string {
104- if c == nil {
105- return ""
106- }
107- r, g, b, _ := c.RGBA()
108- return fmt.Sprintf("\x1b[48;2;%d;%d;%dm", r>>8, g>>8, b>>8)
109-}
110-
111-// themeBg extracts the background hex color from a Chroma style.
112-// Returns "" if no background is set.
113-func themeBg(theme string) string {
114- sty := styles.Get(theme)
115- if sty == nil {
116- return ""
117- }
118- bg := sty.Get(chroma.Background).Background
119- if !bg.IsSet() {
120- return ""
121- }
122- return bg.String() // "#rrggbb"
123-}
124-
12516 // ---------------------------------------------------------------------------
12617 // Model
12718 // ---------------------------------------------------------------------------
@@ -673,730 +564,3 @@ func (m *Model) bgHexForHighlight() string {
673564 }
674565 return "#000000"
675566 }
676-
677-// ---------------------------------------------------------------------------
678-// Editing operations
679-// ---------------------------------------------------------------------------
680-
681-// InsertText inserts a multi-line string at the current cursor position.
682-// Newlines are handled via insertNewline. No-op if ReadOnly.
683-func (m *Model) InsertText(text string) {
684- if m.ReadOnly {
685- return
686- }
687- for _, r := range text {
688- switch r {
689- case '\n':
690- m.insertNewline()
691- case '\r':
692- // Skip carriage returns (normalize \r\n to \n)
693- default:
694- m.insertRune(r)
695- }
696- }
697-}
698-
699-func (m *Model) insertRune(r rune) {
700- if m.ReadOnly {
701- return
702- }
703- line := m.currentLine()
704- newLine := make([]rune, 0, len(line)+1)
705- newLine = append(newLine, line[:m.col]...)
706- newLine = append(newLine, r)
707- newLine = append(newLine, line[m.col:]...)
708- m.lines[m.row] = newLine
709- m.col++
710-}
711-
712-func (m *Model) insertNewline() {
713- if m.ReadOnly {
714- return
715- }
716- line := m.currentLine()
717- after := make([]rune, len(line[m.col:]))
718- copy(after, line[m.col:])
719- m.lines[m.row] = line[:m.col]
720- // Insert new line after current
721- newLines := make([][]rune, 0, len(m.lines)+1)
722- newLines = append(newLines, m.lines[:m.row+1]...)
723- newLines = append(newLines, after)
724- newLines = append(newLines, m.lines[m.row+1:]...)
725- m.lines = newLines
726- m.row++
727- m.col = 0
728-}
729-
730-func (m *Model) deleteBack() {
731- if m.ReadOnly {
732- return
733- }
734- if m.col > 0 {
735- line := m.currentLine()
736- m.lines[m.row] = append(line[:m.col-1], line[m.col:]...)
737- m.col--
738- } else if m.row > 0 {
739- // Merge with previous line
740- prev := m.lines[m.row-1]
741- m.col = len(prev)
742- m.lines[m.row-1] = append(prev, m.currentLine()...)
743- m.lines = append(m.lines[:m.row], m.lines[m.row+1:]...)
744- m.row--
745- }
746-}
747-
748-func (m *Model) deleteForward() {
749- if m.ReadOnly {
750- return
751- }
752- line := m.currentLine()
753- if m.col < len(line) {
754- m.lines[m.row] = append(line[:m.col], line[m.col+1:]...)
755- } else if m.row < len(m.lines)-1 {
756- // Merge with next line
757- m.lines[m.row] = append(line, m.lines[m.row+1]...)
758- m.lines = append(m.lines[:m.row+1], m.lines[m.row+2:]...)
759- }
760-}
761-
762-func (m *Model) tabIndent() {
763- if m.ReadOnly {
764- return
765- }
766- // Indent to match the leading whitespace of the line above.
767- indent := "\t"
768- if m.row > 0 {
769- above := m.lines[m.row-1]
770- indent = ""
771- for _, r := range above {
772- if r == ' ' || r == '\t' {
773- indent += string(r)
774- } else {
775- break
776- }
777- }
778- if indent == "" {
779- indent = "\t"
780- }
781- }
782- for _, r := range indent {
783- m.insertRune(r)
784- }
785-}
786-
787-// screenToPos converts screen-relative x,y to a buffer row,col.
788-// x,y are relative to the editor component origin.
789-func (m *Model) screenToPos(x, y int) pos {
790- visRow := m.scroll + y
791- if visRow < 0 {
792- visRow = 0
793- }
794- bufRow, runeOffset := m.visualToBuffer(visRow)
795-
796- col := x - m.gutterWidth
797- if col < 0 {
798- col = 0
799- }
800- // runeOffset is in expanded-tab space; convert back to buffer col.
801- // We need to find which buffer rune corresponds to runeOffset + col
802- // in the expanded string.
803- bufCol := m.expandedColToBufferCol(bufRow, runeOffset+col)
804- return pos{row: bufRow, col: bufCol}
805-}
806-
807-// ---------------------------------------------------------------------------
808-// Update
809-// ---------------------------------------------------------------------------
810-
811-func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
812- var cmds []tea.Cmd
813-
814- switch msg := msg.(type) {
815- case tea.KeyPressMsg:
816- if !m.focus {
817- break
818- }
819- moved := true
820- key := msg.Keystroke()
821-
822- switch key {
823- // --- Shift+navigation: extend selection ---
824- case "shift+up":
825- m.startOrExtendSelection()
826- m.row--
827- m.clampCursor()
828- m.updateSelectionActive()
829- case "shift+down":
830- m.startOrExtendSelection()
831- m.row++
832- m.clampCursor()
833- m.updateSelectionActive()
834- case "shift+left":
835- m.startOrExtendSelection()
836- if m.col > 0 {
837- m.col--
838- } else if m.row > 0 {
839- m.row--
840- m.col = len(m.currentLine())
841- }
842- m.updateSelectionActive()
843- case "shift+right":
844- m.startOrExtendSelection()
845- if m.col < len(m.currentLine()) {
846- m.col++
847- } else if m.row < len(m.lines)-1 {
848- m.row++
849- m.col = 0
850- }
851- m.updateSelectionActive()
852- case "shift+home":
853- m.startOrExtendSelection()
854- m.col = 0
855- m.updateSelectionActive()
856- case "shift+end":
857- m.startOrExtendSelection()
858- m.col = len(m.currentLine())
859- m.updateSelectionActive()
860- case "shift+pgup":
861- m.startOrExtendSelection()
862- m.row -= m.height
863- m.clampCursor()
864- m.updateSelectionActive()
865- case "shift+pgdown":
866- m.startOrExtendSelection()
867- m.row += m.height
868- m.clampCursor()
869- m.updateSelectionActive()
870-
871- // --- Plain navigation: clear selection ---
872- case "up":
873- m.ClearSelection()
874- m.row--
875- m.clampCursor()
876- case "down":
877- m.ClearSelection()
878- m.row++
879- m.clampCursor()
880- case "left":
881- m.ClearSelection()
882- if m.col > 0 {
883- m.col--
884- } else if m.row > 0 {
885- m.row--
886- m.col = len(m.currentLine())
887- }
888- case "right":
889- m.ClearSelection()
890- if m.col < len(m.currentLine()) {
891- m.col++
892- } else if m.row < len(m.lines)-1 {
893- m.row++
894- m.col = 0
895- }
896- case "home", "ctrl+a":
897- m.ClearSelection()
898- m.col = 0
899- case "end", "ctrl+e":
900- m.ClearSelection()
901- m.col = len(m.currentLine())
902- case "pgup":
903- m.ClearSelection()
904- m.row -= m.height
905- m.clampCursor()
906- case "pgdown":
907- m.ClearSelection()
908- m.row += m.height
909- m.clampCursor()
910- case "ctrl+home":
911- m.ClearSelection()
912- m.row = 0
913- m.col = 0
914- case "ctrl+end":
915- m.ClearSelection()
916- m.row = len(m.lines) - 1
917- m.col = len(m.currentLine())
918-
919- // --- Editing: delete selection first ---
920- case "backspace", "ctrl+h":
921- if m.HasSelection() {
922- m.DeleteSelection()
923- } else {
924- m.deleteBack()
925- }
926- case "delete", "ctrl+d":
927- if m.HasSelection() {
928- m.DeleteSelection()
929- } else {
930- m.deleteForward()
931- }
932- case "enter":
933- m.DeleteSelection()
934- m.insertNewline()
935- case "tab":
936- m.DeleteSelection()
937- m.tabIndent()
938-
939- default:
940- moved = false
941- if !m.ReadOnly && msg.Text != "" {
942- m.DeleteSelection()
943- for _, r := range msg.Text {
944- m.insertRune(r)
945- }
946- moved = true
947- }
948- }
949-
950- if moved {
951- m.clampCursor()
952- m.clampScroll()
953- cmds = append(cmds, m.cursor.Blink())
954- }
955-
956- case tea.MouseClickMsg:
957- if !m.focus {
958- break
959- }
960- if msg.Button == tea.MouseLeft {
961- p := m.screenToPos(msg.X, msg.Y)
962- m.dragging = true
963- m.sel = &selection{anchor: p, active: p}
964- m.row = p.row
965- m.col = p.col
966- m.clampCursor()
967- }
968-
969- case tea.MouseMotionMsg:
970- if !m.focus {
971- break
972- }
973- if m.dragging {
974- p := m.screenToPos(msg.X, msg.Y)
975- m.sel.active = p
976- m.row = p.row
977- m.col = p.col
978- m.clampCursor()
979- }
980-
981- case tea.MouseReleaseMsg:
982- if !m.focus {
983- break
984- }
985- m.dragging = false
986- if m.sel != nil && m.sel.empty() {
987- m.ClearSelection()
988- }
989-
990- case tea.MouseWheelMsg:
991- if !m.focus {
992- break
993- }
994- if msg.Button == tea.MouseWheelUp {
995- m.scroll -= 3
996- m.clampScrollBounds()
997- } else if msg.Button == tea.MouseWheelDown {
998- m.scroll += 3
999- m.clampScrollBounds()
1000- }
1001- }
1002-
1003- // Forward to cursor for blink handling
1004- var cmd tea.Cmd
1005- m.cursor, cmd = m.cursor.Update(msg)
1006- cmds = append(cmds, cmd)
1007-
1008- return m, tea.Batch(cmds...)
1009-}
1010-
1011-// ---------------------------------------------------------------------------
1012-// View
1013-// ---------------------------------------------------------------------------
1014-
1015-func (m Model) View() string {
1016- if m.width == 0 || m.height == 0 {
1017- return ""
1018- }
1019-
1020- // Show placeholder when empty
1021- if len(m.lines) == 1 && len(m.lines[0]) == 0 && m.Placeholder != "" {
1022- return m.placeholderView()
1023- }
1024-
1025- tw := m.textWidth()
1026- bg := m.bgForRender()
1027- lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
1028- themeBgSeq := hexToBgSeq(m.bgHexForHighlight()) // for LineBg replacement
1029-
1030- // Build a flat list of visual rows from visible buffer lines.
1031- type visualRow struct {
1032- bufRow int // buffer line index
1033- subRow int // 0 = first wrap segment, 1 = second, etc.
1034- text string // plain text (expanded tabs) for this segment
1035- fullHL string // full-line highlighted ANSI (shared across sub-rows)
1036- segStart int // rune offset of this segment in the full line
1037- segEnd int // rune end offset
1038- }
1039-
1040- var rows []visualRow
1041- hasSyntax := m.Language != "" && m.SyntaxTheme != ""
1042-
1043- // Find which buffer line the scroll offset lands in.
1044- startBuf, startRuneOff := m.visualToBuffer(m.scroll)
1045-
1046- // Pre-compute the sub-row index for the starting buffer line.
1047- startSubRow := 0
1048- if startRuneOff > 0 && tw > 0 {
1049- startSubRow = startRuneOff / tw
1050- }
1051-
1052- // Generate visual rows starting from the scroll position.
1053- for bufIdx := startBuf; bufIdx < len(m.lines) && len(rows) < m.height; bufIdx++ {
1054- lineStr := expandTabs(string(m.lines[bufIdx]))
1055- segments := wrapPlain(lineStr, tw)
1056-
1057- // Highlight the full line once for all its segments.
1058- var fullHL string
1059- if hasSyntax {
1060- fullHL = cachedHighlight(lineStr, m.Language, m.SyntaxTheme, m.bgHexForHighlight())
1061- }
1062-
1063- firstSub := 0
1064- if bufIdx == startBuf {
1065- firstSub = startSubRow
1066- }
1067- runeOff := firstSub * tw
1068- for subIdx := firstSub; subIdx < len(segments) && len(rows) < m.height; subIdx++ {
1069- segLen := len([]rune(segments[subIdx]))
1070- rows = append(rows, visualRow{
1071- bufRow: bufIdx,
1072- subRow: subIdx,
1073- text: segments[subIdx],
1074- fullHL: fullHL,
1075- segStart: runeOff,
1076- segEnd: runeOff + segLen,
1077- })
1078- runeOff += segLen
1079- }
1080- }
1081-
1082- // Determine cursor position in expanded-tab space for the cursor line.
1083- cursorExpandedCol := -1
1084- if m.focus && m.row >= 0 && m.row < len(m.lines) {
1085- prefix := expandTabs(string(m.lines[m.row][:m.col]))
1086- cursorExpandedCol = len([]rune(prefix))
1087- }
1088-
1089- // Pre-compute selection range in expanded-tab space (once, not per row).
1090- hasSel := m.HasSelection()
1091- var selStartRow, selStartExp, selEndRow, selEndExp int
1092- if hasSel {
1093- ss, se := m.sel.ordered()
1094- selStartRow = ss.row
1095- selStartExp = m.bufferColToExpandedCol(ss.row, ss.col)
1096- selEndRow = se.row
1097- selEndExp = m.bufferColToExpandedCol(se.row, se.col)
1098- }
1099-
1100- selSty := m.SelectionStyle
1101-
1102- var b strings.Builder
1103-
1104- for vi := 0; vi < m.height; vi++ {
1105- if vi > 0 {
1106- b.WriteByte('\n')
1107- }
1108-
1109- if vi >= len(rows) {
1110- // End-of-buffer: fill entire row with bg
1111- b.WriteString(bg.Render(strings.Repeat(" ", m.width)))
1112- continue
1113- }
1114-
1115- vr := rows[vi]
1116-
1117- // Resolve per-line background override.
1118- rowBg := bg
1119- hasLineBg := false
1120- if lbg, ok := m.LineBg[vr.bufRow]; ok {
1121- rowBg = lbg
1122- hasLineBg = true
1123- }
1124-
1125- // -- Gutter (line numbers + marker column) ---------------------------
1126- if m.ShowLineNumbers {
1127- gutSty := lineNumSty
1128- if hasLineBg {
1129- gutSty = gutSty.Background(rowBg.GetBackground())
1130- }
1131- digits := m.gutterWidth - 2 // gutter = digits + space + marker
1132- if vr.subRow == 0 {
1133- num := fmt.Sprintf("%*d ", digits, vr.bufRow+1)
1134- b.WriteString(gutSty.Render(num))
1135- b.WriteString(m.renderGutterMark(vr.bufRow, gutSty))
1136- } else {
1137- // Continuation row — blank gutter
1138- b.WriteString(gutSty.Render(strings.Repeat(" ", m.gutterWidth)))
1139- }
1140- }
1141-
1142- // -- Text content ----------------------------------------------------
1143- segText := vr.text
1144- segRuneOff := vr.subRow * tw // rune offset within the full expanded line
1145- segLen := len([]rune(segText))
1146-
1147- // Compute selection intersection for this visual row.
1148- // selColStart/selColEnd are in segment-local expanded rune space.
1149- rowHasSel := false
1150- selColStart, selColEnd := 0, 0
1151- if hasSel && vr.bufRow >= selStartRow && vr.bufRow <= selEndRow {
1152- // Compute absolute expanded range that is selected on this buffer row.
1153- absSelStart := 0
1154- if vr.bufRow == selStartRow {
1155- absSelStart = selStartExp
1156- }
1157- absSelEnd := segRuneOff + segLen // default: rest of line
1158- if vr.bufRow == selEndRow {
1159- absSelEnd = selEndExp
1160- }
1161- // Intersect with this segment's range [segRuneOff, segRuneOff+segLen)
1162- localStart := absSelStart - segRuneOff
1163- localEnd := absSelEnd - segRuneOff
1164- if localStart < 0 {
1165- localStart = 0
1166- }
1167- if localEnd > segLen {
1168- localEnd = segLen
1169- }
1170- if localStart < localEnd {
1171- rowHasSel = true
1172- selColStart = localStart
1173- selColEnd = localEnd
1174- }
1175- }
1176-
1177- // Is the cursor on this visual row?
1178- isCursorHere := false
1179- if m.focus && vr.bufRow == m.row {
1180- if cursorExpandedCol >= segRuneOff && cursorExpandedCol < segRuneOff+tw {
1181- isCursorHere = true
1182- } else if cursorExpandedCol == segRuneOff+segLen && segLen < tw {
1183- isCursorHere = true
1184- }
1185- }
1186-
1187- var rendered string
1188- if rowHasSel {
1189- rendered = m.renderSelectedSegment(segText, vr.fullHL, vr.segStart, segLen,
1190- selColStart, selColEnd, selSty, rowBg, isCursorHere, cursorExpandedCol-segRuneOff)
1191- } else if isCursorHere {
1192- localCol := cursorExpandedCol - segRuneOff
1193- rendered = m.renderCursorSegment(segText, vr.fullHL, vr.segStart, localCol)
1194- } else if hasSyntax && vr.fullHL != "" {
1195- rendered = ansi.Cut(vr.fullHL, vr.segStart, vr.segEnd)
1196- if hasLineBg && themeBgSeq != "" {
1197- overrideBgSeq := colorToBgSeq(rowBg.GetBackground())
1198- rendered = strings.ReplaceAll(rendered, themeBgSeq, overrideBgSeq)
1199- }
1200- } else {
1201- rendered = rowBg.Render(segText)
1202- }
1203-
1204- // Pad to text width
1205- rw := lipgloss.Width(rendered)
1206- if rw > tw {
1207- rendered = ansi.Truncate(rendered, tw, "")
1208- rw = lipgloss.Width(rendered)
1209- }
1210- b.WriteString(rendered)
1211- if rw < tw {
1212- b.WriteString(rowBg.Render(strings.Repeat(" ", tw-rw)))
1213- }
1214- }
1215-
1216- return b.String()
1217-}
1218-
1219-// renderCursorSegment renders a text segment with the cursor at localCol.
1220-// localCol is a rune index within the segment's plain text.
1221-// fullHL is the full-line highlighted ANSI string; segStart is the rune offset
1222-// of this segment within it. Uses ansi.Cut to extract correctly-highlighted
1223-// before/after portions so syntax coloring is never broken.
1224-func (m Model) renderCursorSegment(segText, fullHL string, segStart, localCol int) string {
1225- bg := m.bgForRender()
1226- runes := []rune(segText)
1227-
1228- col := localCol
1229- if col > len(runes) {
1230- col = len(runes)
1231- }
1232-
1233- // Extract the cursor character from the plain text.
1234- cursorChar := " "
1235- if col < len(runes) {
1236- cursorChar = string(runes[col])
1237- }
1238-
1239- hasSyntax := m.Language != "" && m.SyntaxTheme != ""
1240- var before, after string
1241-
1242- if hasSyntax && fullHL != "" {
1243- // Cut from the full-line highlight at absolute positions.
1244- absCursorCol := segStart + col
1245- before = ansi.Cut(fullHL, segStart, absCursorCol)
1246- after = ansi.Cut(fullHL, absCursorCol+1, segStart+len(runes))
1247- } else {
1248- highlighted := bg.Render(segText)
1249- before = ansi.Truncate(highlighted, col, "")
1250- after = ansi.TruncateLeft(highlighted, col+1, "")
1251- }
1252-
1253- // Render cursor character
1254- m.cursor.SetChar(cursorChar)
1255- m.cursor.TextStyle = bg
1256- cursorView := m.cursor.View()
1257-
1258- return before + cursorView + after
1259-}
1260-
1261-// renderSelectedSegment renders a text segment with a selection highlight
1262-// (and optionally a cursor). selStart/selEnd are segment-local rune offsets.
1263-func (m Model) renderSelectedSegment(
1264- segText, fullHL string, segStart, segLen, selStart, selEnd int,
1265- selSty, bg lipgloss.Style, hasCursor bool, cursorLocalCol int,
1266-) string {
1267- hasSyntax := m.Language != "" && m.SyntaxTheme != ""
1268- runes := []rune(segText)
1269-
1270- // Helper: render a rune range with a given style (selection or bg).
1271- renderRange := func(from, to int, sty lipgloss.Style) string {
1272- if from >= to {
1273- return ""
1274- }
1275- if hasSyntax && fullHL != "" {
1276- cut := ansi.Cut(fullHL, segStart+from, segStart+to)
1277- // Wrap in selection bg — this overrides the syntax bg
1278- return sty.Render(ansi.Strip(cut))
1279- }
1280- return sty.Render(string(runes[from:to]))
1281- }
1282-
1283- // Helper: render a rune range with the normal style (bg or syntax HL).
1284- renderNormal := func(from, to int) string {
1285- if from >= to {
1286- return ""
1287- }
1288- if hasSyntax && fullHL != "" {
1289- return ansi.Cut(fullHL, segStart+from, segStart+to)
1290- }
1291- return bg.Render(string(runes[from:to]))
1292- }
1293-
1294- // If cursor is in this segment, we need to handle it specially.
1295- if hasCursor && cursorLocalCol >= 0 && cursorLocalCol <= len(runes) {
1296- cc := cursorLocalCol
1297- cursorChar := " "
1298- if cc < len(runes) {
1299- cursorChar = string(runes[cc])
1300- }
1301- m.cursor.SetChar(cursorChar)
1302- cursorInSel := cc >= selStart && cc < selEnd
1303- if cursorInSel {
1304- m.cursor.TextStyle = selSty
1305- } else {
1306- m.cursor.TextStyle = bg
1307- }
1308- cv := m.cursor.View()
1309-
1310- var sb strings.Builder
1311- switch {
1312- case cc < selStart:
1313- // [normal 0..cc] [cursor] [normal cc+1..selStart] [sel] [normal selEnd..end]
1314- sb.WriteString(renderNormal(0, cc))
1315- sb.WriteString(cv)
1316- sb.WriteString(renderNormal(cc+1, selStart))
1317- sb.WriteString(renderRange(selStart, selEnd, selSty))
1318- sb.WriteString(renderNormal(selEnd, len(runes)))
1319- case cc >= selEnd:
1320- // [normal 0..selStart] [sel] [normal selEnd..cc] [cursor] [normal cc+1..end]
1321- sb.WriteString(renderNormal(0, selStart))
1322- sb.WriteString(renderRange(selStart, selEnd, selSty))
1323- sb.WriteString(renderNormal(selEnd, cc))
1324- sb.WriteString(cv)
1325- if cc+1 <= len(runes) {
1326- sb.WriteString(renderNormal(cc+1, len(runes)))
1327- }
1328- default:
1329- // Cursor inside selection
1330- // [normal 0..selStart] [sel selStart..cc] [cursor] [sel cc+1..selEnd] [normal selEnd..end]
1331- sb.WriteString(renderNormal(0, selStart))
1332- if cc > selStart {
1333- sb.WriteString(renderRange(selStart, cc, selSty))
1334- }
1335- sb.WriteString(cv)
1336- if cc+1 < selEnd {
1337- sb.WriteString(renderRange(cc+1, selEnd, selSty))
1338- }
1339- sb.WriteString(renderNormal(selEnd, len(runes)))
1340- }
1341- return sb.String()
1342- }
1343-
1344- // No cursor: simple before/selected/after
1345- var sb strings.Builder
1346- sb.WriteString(renderNormal(0, selStart))
1347- sb.WriteString(renderRange(selStart, selEnd, selSty))
1348- sb.WriteString(renderNormal(selEnd, segLen))
1349- return sb.String()
1350-}
1351-
1352-// ---------------------------------------------------------------------------
1353-// Placeholder view (shown when empty + unfocused)
1354-// ---------------------------------------------------------------------------
1355-
1356-func (m Model) placeholderView() string {
1357- if m.Placeholder == "" {
1358- return ""
1359- }
1360- bg := m.bgForRender()
1361- tw := m.textWidth()
1362-
1363- var b strings.Builder
1364- // Gutter
1365- if m.ShowLineNumbers {
1366- lineNumSty := m.LineNumStyle.Background(bg.GetBackground())
1367- digits := m.gutterWidth - 2 // gutter = digits + space + marker
1368- num := fmt.Sprintf("%*d ", digits, 1)
1369- b.WriteString(lineNumSty.Render(num))
1370- b.WriteString(m.renderGutterMark(0, lineNumSty))
1371- }
1372-
1373- // First line: cursor (if focused) then placeholder text
1374- if m.focus {
1375- // Render cursor on first character of placeholder
1376- phRunes := []rune(m.Placeholder)
1377- m.cursor.SetChar(string(phRunes[0]))
1378- m.cursor.TextStyle = m.PlaceholderSty
1379- b.WriteString(m.cursor.View())
1380- rest := m.PlaceholderSty.Render(string(phRunes[1:]))
1381- rw := lipgloss.Width(m.cursor.View()) + lipgloss.Width(rest)
1382- b.WriteString(rest)
1383- if rw < tw {
1384- b.WriteString(bg.Render(strings.Repeat(" ", tw-rw)))
1385- }
1386- } else {
1387- ph := m.PlaceholderSty.Render(m.Placeholder)
1388- pw := lipgloss.Width(ph)
1389- b.WriteString(ph)
1390- if pw < tw {
1391- b.WriteString(bg.Render(strings.Repeat(" ", tw-pw)))
1392- }
1393- }
1394-
1395- // Remaining rows: empty with bg
1396- for vi := 1; vi < m.height; vi++ {
1397- b.WriteByte('\n')
1398- b.WriteString(bg.Render(strings.Repeat(" ", m.width)))
1399- }
1400-
1401- return b.String()
1402-}
internal/tui/editor/highlight.go+116−0
@@ -0,0 +1,116 @@
1+package editor
2+
3+import (
4+ "fmt"
5+ "image/color"
6+ "strings"
7+ "sync"
8+
9+ "github.com/alecthomas/chroma/v2"
10+ "github.com/alecthomas/chroma/v2/formatters"
11+ "github.com/alecthomas/chroma/v2/lexers"
12+ "github.com/alecthomas/chroma/v2/styles"
13+)
14+
15+// ---------------------------------------------------------------------------
16+// Highlight cache (global, shared across instances)
17+// ---------------------------------------------------------------------------
18+
19+var (
20+ hlCache = make(map[string]string)
21+ hlCacheMu sync.RWMutex
22+)
23+
24+func cachedHighlight(text, language, theme, bgHex string) string {
25+ cacheKey := language + ":" + theme + ":" + bgHex + ":" + text
26+ hlCacheMu.RLock()
27+ if v, ok := hlCache[cacheKey]; ok {
28+ hlCacheMu.RUnlock()
29+ return v
30+ }
31+ hlCacheMu.RUnlock()
32+
33+ lex := lexers.Get(language)
34+ if lex == nil {
Cut short: this commit's diff is over 1000 lines.
internal/tui/editor/update.go+227−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/editor/view.go+402−0
Cut short: this commit's diff is over 1000 lines.