xonecas.io
62159
Sy

symb / commit 91fe4cb

fix: selection consistency

xonecas2026-02-13 91fe4cb0ec93a872a365c821669c3935794539d3 parent 1973fc2

4 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.

docs/mouse-selection-tui.md+363−0
@@ -0,0 +1,363 @@
1+# Mouse & Selection in Bubbletea TUIs
2+
3+Reference document based on patterns from Charm's Crush (production TUI using
4+Bubbletea v2 + Lipgloss v2). Applies directly to our stack.
5+
6+---
7+
8+## 1. Mouse Modes
9+
10+Bubbletea supports two mouse tracking modes:
11+
12+- **CellMotion** (`tea.WithMouseCellMotion()` / `MouseModeCellMotion`): reports
13+ presses, releases, and motion *while a button is held* (i.e. drags). This is
14+ what you want for selection. Does NOT report hover.
15+- **AllMotion** (`tea.WithMouseAllMotion()` / `MouseModeAllMotion`): also
16+ reports motion with no button held. Expensive — avoid unless hover is needed.
17+
18+Crush uses CellMotion. So do we.
19+
20+## 2. Mouse Message Types (Bubbletea v2)
21+
22+Bubbletea v2 splits the old `tea.MouseMsg` into distinct types:
23+
24+| Type | When fired |
25+|---------------------|----------------------------------|
26+| `tea.MouseClickMsg` | Button pressed |
27+| `tea.MouseMotionMsg`| Motion while button held (drag) |
28+| `tea.MouseReleaseMsg`| Button released |
29+| `tea.MouseWheelMsg` | Scroll wheel |
30+
31+Bubbletea v1 (what we use) has a single `tea.MouseMsg` with `.Action` field:
32+
33+| `msg.Action` | Equivalent v2 type |
34+|---------------------------|-----------------------|
35+| `tea.MouseActionPress` | `tea.MouseClickMsg` |
36+| `tea.MouseActionMotion` | `tea.MouseMotionMsg` |
37+| `tea.MouseActionRelease` | `tea.MouseReleaseMsg` |
38+
39+And `msg.Button` for wheel: `tea.MouseButtonWheelUp`, `tea.MouseButtonWheelDown`.
40+
41+## 3. Event Throttling
42+
43+Trackpads and high-refresh mice flood the event queue. Use `tea.WithFilter` to
44+throttle motion and wheel events at the program level:
45+
46+```go
47+var lastMouseEvent time.Time
48+
49+func MouseEventFilter(_ tea.Model, msg tea.Msg) tea.Msg {
50+ switch msg.(type) {
51+ case tea.MouseWheelMsg, tea.MouseMotionMsg:
52+ now := time.Now()
53+ if now.Sub(lastMouseEvent) < 15*time.Millisecond {
54+ return nil // drop event
55+ }
56+ lastMouseEvent = now
57+ }
58+ return msg
59+}
60+```
61+
62+For v1 (our code), switch on `tea.MouseMsg` and check `msg.Action`/`msg.Button`
63+instead. **Never drop click or release events** — only motion and wheel.
64+
65+Register at program creation:
66+
67+```go
68+p := tea.NewProgram(model, tea.WithMouseCellMotion(), tea.WithFilter(filter))
69+```
70+
71+## 4. Mouse Event Routing
72+
73+### 4.1 Layout Rects (Not Zones)
74+
75+Both Crush and our codebase use `image.Rectangle` structs for layout regions.
76+Hit testing is `image.Pt(msg.X, msg.Y).In(rect)`. This is simpler and more
77+predictable than lipgloss zone-based routing.
78+
79+### 4.2 Coordinate Translation
80+
81+Mouse coordinates are screen-absolute. Child components expect local
82+coordinates. Subtract the layout rect origin before forwarding:
83+
84+```go
85+localX := msg.X - layout.pane.Min.X
86+localY := msg.Y - layout.pane.Min.Y
87+```
88+
89+### 4.3 Routing Priority
90+
91+Process mouse events in this order:
92+
93+1. **Dialogs/overlays** — if open, they consume all mouse events
94+2. **Divider drag** — if resizing, motion goes to resize logic
95+3. **Focus switching** — click sets focus to the clicked region
96+4. **Component dispatch** — forward (with coord translation) to the hit region
97+
98+This matches both Crush and our current approach.
99+
100+## 5. Selection Data Model
101+
102+### 5.1 Anchor + Active Pattern
103+
104+Selection is defined by two points:
105+
106+- **Anchor**: where the selection started (mouse down, or cursor position when
107+ shift was first held)
108+- **Active**: where the selection currently extends to (mouse drag position, or
109+ current cursor position while shift is held)
110+
111+The anchor is fixed; the active point moves. This lets backward selection
112+(dragging up/left) work naturally.
113+
114+```go
115+type selPos struct{ row, col int }
116+
117+type selection struct {
118+ anchor selPos
119+ active selPos
120+}
121+```
122+
123+To get the ordered range:
124+
125+```go
126+func (s selection) ordered() (start, end selPos) {
127+ if s.anchor.row > s.active.row ||
128+ (s.anchor.row == s.active.row && s.anchor.col > s.active.col) {
129+ return s.active, s.anchor
130+ }
131+ return s.anchor, s.active
132+}
133+```
134+
135+### 5.2 Valid Selection Check
136+
137+A selection is "empty" when anchor == active. Only render highlight and allow
138+copy when they differ.
139+
140+### 5.3 Clearing Selection
141+
142+Clear on:
143+- Any non-shift cursor movement (arrows, home, end, pgup, pgdown)
144+- Click (press) without drag
145+- Edit operations (typing, backspace, delete, paste)
146+- Explicit copy (Ctrl+Shift+C) — optional, some editors keep it
147+
148+Do NOT clear on:
149+- Mouse motion during drag
150+- Shift+movement keys
151+- Scroll (wheel)
152+
153+## 6. Mouse Selection Flow
154+
155+### 6.1 Press → Drag → Release
156+
157+```
158+Press: Set anchor = active = screenToPos(x, y). Set mouseDown = true.
159+Motion: If mouseDown, update active = screenToPos(x, y).
160+Release: Set mouseDown = false. Keep selection visible.
161+```
162+
163+Crush does NOT auto-copy on release. It waits for an explicit copy action
164+(keyboard shortcut or delayed auto-copy after double-click timeout). This
165+prevents accidental clipboard overwrites during casual clicking.
166+
167+### 6.2 Click Detection (No Drag)
168+
169+If press and release happen at the same position (anchor == active after
170+release), treat it as a click, not a selection. Clear any existing selection
171+and handle the click action (e.g., position cursor, open file link).
172+
173+### 6.3 Double-Click / Triple-Click
174+
175+Crush implements multi-click via timing + spatial tolerance:
176+
177+```go
178+const (
179+ doubleClickThreshold = 400 * time.Millisecond
180+ clickTolerance = 2 // pixels
181+)
182+```
183+
184+On click, check if the previous click was within threshold and tolerance:
185+- **Double-click**: select word at cursor (using Unicode word boundaries)
186+- **Triple-click**: select entire line
187+
188+Track `lastClickTime`, `lastClickX`, `lastClickY`, `clickCount`.
189+
190+### 6.4 Delayed Single-Click
191+
192+Problem: a single click should position the cursor, but the first click of a
193+double-click should NOT trigger single-click behavior.
194+
195+Solution: on single click, schedule a delayed action after `doubleClickThreshold`.
196+Increment a `pendingClickID`. If a double-click arrives before the delay fires,
197+the ID won't match and the pending action is discarded.
198+
199+### 6.5 Auto-Scroll During Drag
200+
201+When dragging near viewport edges, scroll the content:
202+
203+```go
204+case tea.MouseActionMotion:
205+ if msg.Y <= 0 {
206+ scrollUp(1)
207+ } else if msg.Y >= viewportHeight-1 {
208+ scrollDown(1)
209+ }
210+```
211+
212+This lets the user drag-select beyond the visible area.
213+
214+## 7. Keyboard Selection (Editors)
215+
216+Keyboard selection uses the same anchor+active model:
217+
218+- **Start selection**: On any shift+movement key, if no selection exists, set
219+ anchor = current cursor position. Then move cursor. Set active = new cursor.
220+- **Extend selection**: On shift+movement with existing selection, just move
221+ cursor and update active. Anchor stays put.
222+- **Clear selection**: On any non-shift movement or edit, clear the selection.
223+
224+Supported shift+key combinations:
225+
226+| Key | Action |
227+|-----------------|---------------------------|
228+| `shift+left` | Extend selection left 1 |
229+| `shift+right` | Extend selection right 1 |
230+| `shift+up` | Extend selection up 1 row |
231+| `shift+down` | Extend selection down 1 |
232+| `shift+home` | Extend to line start |
233+| `shift+end` | Extend to line end |
234+| `shift+pgup` | Extend up by page |
235+| `shift+pgdown` | Extend down by page |
236+
237+## 8. Clipboard
238+
239+### 8.1 Dual Write for Compatibility
240+
241+Use both OSC 52 and native clipboard for writes:
242+
243+```go
244+func CopyToClipboard(text string) tea.Cmd {
245+ return tea.Sequence(
246+ tea.SetClipboard(text), // OSC 52 (works through SSH/tmux)
247+ func() tea.Msg {
248+ _ = clipboard.WriteAll(text) // Native OS clipboard
249+ return nil
250+ },
251+ )
252+}
253+```
254+
255+`tea.SetClipboard()` sends an OSC 52 escape sequence. Many terminals support
256+it, and it works through SSH tunnels and tmux (if configured). The native
257+clipboard call (`github.com/atotto/clipboard`) covers local-only terminals.
258+
259+### 8.2 Copy Trigger
260+
261+Ctrl+Shift+C (not Ctrl+C, which should remain quit/cancel). The top-level
262+handler checks which component has a selection and copies from it.
263+
264+### 8.3 Paste Trigger
265+
266+Ctrl+Shift+V. Read from native clipboard and insert at cursor.
267+
268+## 9. Highlight Rendering
269+
270+### 9.1 Cell-Level Approach (Crush)
271+
272+Crush uses `ultraviolet.ScreenBuffer` — a cell grid where each cell has content,
273+foreground, background, and attributes. Highlighting replaces cell styles in the
274+selected range. This gives perfect per-character accuracy but requires the UV
275+library.
276+
277+### 9.2 ANSI String Approach (Our Stack)
278+
279+Without UV, we work with ANSI-styled strings. To highlight a region within a
280+rendered line:
281+
282+1. Determine which characters fall within the selection range
283+2. Split the line into before / selected / after segments
284+3. Strip existing background from the selected segment
285+4. Apply the selection background style
286+5. Reassemble
287+
288+For syntax-highlighted content, use `ansi.Cut(hlString, start, end)` to extract
289+ANSI substrings at character boundaries, then wrap the selected portion in the
290+highlight style.
291+
292+### 9.3 Selection Style
293+
294+Define a visible but not jarring selection background:
295+
296+```go
297+Selection: lipgloss.NewStyle().Background(lipgloss.Color("#264f78"))
298+```
299+
300+Dark blue (#264f78) is the VS Code default and works well on dark backgrounds.
301+The current `#111111` is too subtle — almost invisible.
302+
303+### 9.4 Per-Row Intersection
304+
305+For each visual row during render, compute the intersection with the selection
306+range:
307+
308+```go
309+// selStart, selEnd are in buffer coordinates (row, col)
310+// vr.bufRow is this visual row's buffer line
311+// vr.segStart, vr.segEnd are the rune range of this segment
312+
313+if vr.bufRow < selStart.row || vr.bufRow > selEnd.row {
314+ // No selection on this row
315+} else {
316+ colStart := 0
317+ if vr.bufRow == selStart.row { colStart = selStart.col - vr.segStart }
318+ colEnd := segLen
319+ if vr.bufRow == selEnd.row { colEnd = selEnd.col - vr.segStart }
320+ // Clamp to segment bounds, then render highlight
321+}
322+```
323+
324+## 10. Cross-Component Selection
325+
326+Our app has 3 selectable regions: editor, conversation, input. Only one can
327+have an active selection at a time. When a mouse press or shift+key starts a
328+selection in one region, clear any selection in the others.
329+
330+The top-level model owns this coordination:
331+
332+```go
333+func (m *Model) clearAllSelections() {
334+ m.editor.ClearSelection()
335+ m.agentInput.ClearSelection()
336+ m.convSelection = nil
337+}
338+```
339+
340+On Ctrl+Shift+C, check each component in priority order and copy from the
341+first one with an active selection.
342+
343+## 11. Common Pitfalls
344+
345+1. **Auto-copy on mouse release**: Don't. It overwrites the clipboard on every
346+ casual click-drag. Copy should be explicit (Ctrl+Shift+C) or delayed.
347+
348+2. **Clearing selection on release**: Don't. The user expects to see what they
349+ selected, then press a key to copy. Only clear on next click or edit.
350+
351+3. **Not translating coordinates**: Mouse events use screen-absolute positions.
352+ Always subtract the component's layout origin before forwarding.
353+
354+4. **Selection during scroll**: Mouse wheel should NOT affect selection state.
355+ The selection anchors are in buffer coordinates, not screen coordinates, so
356+ they survive scrolling.
357+
358+5. **Forgetting to clamp**: Selection endpoints must be clamped to valid buffer
359+ ranges. Off-by-one errors here cause panics or garbled rendering.
360+
361+6. **Highlight on trailing whitespace**: Crush explicitly avoids highlighting
362+ trailing whitespace on each line. Track `lastContentX` and only highlight
363+ up to that point. This looks much cleaner.
internal/tui/editor/editor.go+402−12
@@ -127,6 +127,7 @@ type Model struct {
127127
128128 // Styles — set by parent.
129129 CursorStyle lipgloss.Style // Foreground for the cursor character
130+ SelectionStyle lipgloss.Style // Background for selected text
130131 LineNumStyle lipgloss.Style // Line number gutter
131132 PlaceholderSty lipgloss.Style // Placeholder text
132133 BgColor lipgloss.Color // Fallback bg when no syntax theme
@@ -143,12 +144,38 @@ type Model struct {
143144 focus bool
144145 cursor cursor.Model
145146
147+ // Selection state (anchor + active pattern).
148+ // Anchor is where selection started; active moves with cursor/drag.
149+ sel *selection
150+ dragging bool // Mouse drag in progress
151+
146152 // Cached computed values
147153 gutterWidth int // Width of line number gutter (0 if disabled)
148154 }
149155
150156 type pos struct{ row, col int }
151157
158+// selection tracks a text selection via anchor+active points.
159+// Anchor is fixed (where selection started); active moves with cursor/drag.
160+type selection struct {
161+ anchor pos
162+ active pos
163+}
164+
165+// ordered returns the selection endpoints in document order.
166+func (s selection) ordered() (start, end pos) {
167+ if s.anchor.row > s.active.row ||
168+ (s.anchor.row == s.active.row && s.anchor.col > s.active.col) {
169+ return s.active, s.anchor
170+ }
171+ return s.anchor, s.active
172+}
173+
174+// empty returns true when anchor == active (no actual selection).
175+func (s selection) empty() bool {
176+ return s.anchor == s.active
177+}
178+
152179 // New creates a new editor with sensible defaults.
153180 func New() Model {
154181 c := cursor.New()
@@ -228,6 +255,119 @@ func (m *Model) GotoLine(line int) {
228255 // Blink returns the initial cursor blink message. Call from Init().
229256 func Blink() tea.Msg { return cursor.Blink() }
230257
258+// ---------------------------------------------------------------------------
259+// Selection API (called by parent)
260+// ---------------------------------------------------------------------------
261+
262+// HasSelection returns true if there is a non-empty text selection.
263+func (m Model) HasSelection() bool {
264+ return m.sel != nil && !m.sel.empty()
265+}
266+
267+// SelectedText returns the currently selected text, or "" if none.
268+func (m Model) SelectedText() string {
269+ if !m.HasSelection() {
270+ return ""
271+ }
272+ s, e := m.sel.ordered()
273+ return m.textInRange(s, e)
274+}
275+
276+// ClearSelection removes any active selection.
277+func (m *Model) ClearSelection() {
278+ m.sel = nil
279+ m.dragging = false
280+}
281+
282+// textInRange extracts text between two buffer positions.
283+func (m *Model) textInRange(start, end pos) string {
284+ if start.row == end.row {
285+ line := m.lines[start.row]
286+ sc := clampMax(start.col, len(line))
287+ ec := clampMax(end.col, len(line))
288+ return string(line[sc:ec])
289+ }
290+ var sb strings.Builder
291+ first := m.lines[start.row]
292+ sb.WriteString(string(first[clampMax(start.col, len(first)):]))
293+ for r := start.row + 1; r < end.row; r++ {
294+ sb.WriteByte('\n')
295+ sb.WriteString(string(m.lines[r]))
296+ }
297+ sb.WriteByte('\n')
298+ last := m.lines[end.row]
299+ sb.WriteString(string(last[:clampMax(end.col, len(last))]))
300+ return sb.String()
301+}
302+
303+// DeleteSelection removes the selected text and positions the cursor at the
304+// start of the deleted range. Returns true if a selection was deleted.
305+func (m *Model) DeleteSelection() bool {
306+ if m.ReadOnly || !m.HasSelection() {
307+ return false
308+ }
309+ s, e := m.sel.ordered()
310+ m.ClearSelection()
311+
312+ // Clamp to valid range
313+ s.row = clampMax(s.row, len(m.lines)-1)
314+ s.col = clampMax(s.col, len(m.lines[s.row]))
315+ e.row = clampMax(e.row, len(m.lines)-1)
316+ e.col = clampMax(e.col, len(m.lines[e.row]))
317+
318+ if s.row == e.row {
319+ line := m.lines[s.row]
320+ m.lines[s.row] = append(line[:s.col], line[e.col:]...)
321+ } else {
322+ // Keep text before selection start + text after selection end
323+ before := m.lines[s.row][:s.col]
324+ after := m.lines[e.row][e.col:]
325+ merged := make([]rune, 0, len(before)+len(after))
326+ merged = append(merged, before...)
327+ merged = append(merged, after...)
328+ // Replace the range of lines
329+ newLines := make([][]rune, 0, len(m.lines)-(e.row-s.row))
330+ newLines = append(newLines, m.lines[:s.row]...)
331+ newLines = append(newLines, merged)
332+ newLines = append(newLines, m.lines[e.row+1:]...)
333+ m.lines = newLines
334+ }
335+ if len(m.lines) == 0 {
336+ m.lines = [][]rune{{}}
337+ }
338+ m.row = s.row
339+ m.col = s.col
340+ return true
341+}
342+
343+func clampMax(v, hi int) int {
344+ if v < 0 {
345+ return 0
346+ }
347+ if v > hi {
348+ return hi
349+ }
350+ return v
351+}
352+
353+// startOrExtendSelection sets anchor to current cursor pos if no selection
354+// exists, then after the caller moves the cursor, active is updated.
355+func (m *Model) startOrExtendSelection() {
356+ if m.sel == nil {
357+ m.sel = &selection{
358+ anchor: pos{row: m.row, col: m.col},
359+ active: pos{row: m.row, col: m.col},
360+ }
361+ }
362+}
363+
364+// updateSelectionActive sets the active end to the current cursor position.
365+func (m *Model) updateSelectionActive() {
366+ if m.sel != nil {
367+ m.sel.active = pos{row: m.row, col: m.col}
368+ }
369+}
370+
231371 // ---------------------------------------------------------------------------
232372 // Internal helpers
233373 // ---------------------------------------------------------------------------
@@ -438,6 +578,18 @@ func (m *Model) expandedColToBufferCol(bufRow, expandedCol int) int {
438578 return len(line)
439579 }
440580
581+// bufferColToExpandedCol converts a buffer column (rune index) to expanded-tab
582+// column (visual column) for a given buffer row.
583+func (m *Model) bufferColToExpandedCol(bufRow, bufCol int) int {
584+ if bufRow < 0 || bufRow >= len(m.lines) {
585+ return 0
586+ }
587+ line := m.lines[bufRow]
588+ c := clampMax(bufCol, len(line))
589+ prefix := expandTabs(string(line[:c]))
590+ return len([]rune(prefix))
591+}
592+
441593 // bgHexForRender returns the background hex color. Prefers the syntax theme
442594 // background, falls back to BgColor.
443595 func (m *Model) bgHexForRender() string {
@@ -458,6 +610,24 @@ func (m *Model) bgForRender() lipgloss.Style {
458610 // Editing operations
459611 // ---------------------------------------------------------------------------
460612
613+// InsertText inserts a multi-line string at the current cursor position.
614+// Newlines are handled via insertNewline. No-op if ReadOnly.
615+func (m *Model) InsertText(text string) {
616+ if m.ReadOnly {
617+ return
618+ }
619+ for _, r := range text {
620+ switch r {
621+ case '\n':
622+ m.insertNewline()
623+ case '\r':
624+ // Skip carriage returns (normalize \r\n to \n)
625+ default:
626+ m.insertRune(r)
627+ }
628+ }
629+}
630+
461631 func (m *Model) insertRune(r rune) {
462632 if m.ReadOnly {
463633 return
@@ -579,15 +749,68 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
579749 break
580750 }
581751 moved := true
582- switch msg.String() {
583- // Navigation
752+ key := msg.String()
753+
754+ switch key {
755+ // --- Shift+navigation: extend selection ---
756+ case "shift+up":
757+ m.startOrExtendSelection()
758+ m.row--
759+ m.clampCursor()
760+ m.updateSelectionActive()
761+ case "shift+down":
762+ m.startOrExtendSelection()
763+ m.row++
764+ m.clampCursor()
765+ m.updateSelectionActive()
766+ case "shift+left":
767+ m.startOrExtendSelection()
768+ if m.col > 0 {
769+ m.col--
770+ } else if m.row > 0 {
771+ m.row--
772+ m.col = len(m.currentLine())
773+ }
774+ m.updateSelectionActive()
775+ case "shift+right":
776+ m.startOrExtendSelection()
777+ if m.col < len(m.currentLine()) {
778+ m.col++
779+ } else if m.row < len(m.lines)-1 {
780+ m.row++
781+ m.col = 0
782+ }
783+ m.updateSelectionActive()
784+ case "shift+home":
785+ m.startOrExtendSelection()
786+ m.col = 0
787+ m.updateSelectionActive()
788+ case "shift+end":
789+ m.startOrExtendSelection()
790+ m.col = len(m.currentLine())
791+ m.updateSelectionActive()
792+ case "shift+pgup":
793+ m.startOrExtendSelection()
794+ m.row -= m.height
795+ m.clampCursor()
796+ m.updateSelectionActive()
797+ case "shift+pgdown":
798+ m.startOrExtendSelection()
799+ m.row += m.height
800+ m.clampCursor()
801+ m.updateSelectionActive()
802+
803+ // --- Plain navigation: clear selection ---
584804 case "up":
805+ m.ClearSelection()
585806 m.row--
586807 m.clampCursor()
587808 case "down":
809+ m.ClearSelection()
588810 m.row++
589811 m.clampCursor()
590812 case "left":
813+ m.ClearSelection()
591814 if m.col > 0 {
592815 m.col--
593816 } else if m.row > 0 {
@@ -595,6 +818,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
595818 m.col = len(m.currentLine())
596819 }
597820 case "right":
821+ m.ClearSelection()
598822 if m.col < len(m.currentLine()) {
599823 m.col++
600824 } else if m.row < len(m.lines)-1 {
@@ -602,36 +826,52 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
602826 m.col = 0
603827 }
604828 case "home", "ctrl+a":
829+ m.ClearSelection()
605830 m.col = 0
606831 case "end", "ctrl+e":
832+ m.ClearSelection()
607833 m.col = len(m.currentLine())
608834 case "pgup":
835+ m.ClearSelection()
609836 m.row -= m.height
610837 m.clampCursor()
611838 case "pgdown":
839+ m.ClearSelection()
612840 m.row += m.height
613841 m.clampCursor()
614842 case "ctrl+home":
843+ m.ClearSelection()
615844 m.row = 0
616845 m.col = 0
617846 case "ctrl+end":
847+ m.ClearSelection()
618848 m.row = len(m.lines) - 1
619849 m.col = len(m.currentLine())
620850
621- // Editing
851+ // --- Editing: delete selection first ---
622852 case "backspace", "ctrl+h":
623- m.deleteBack()
853+ if m.HasSelection() {
854+ m.DeleteSelection()
855+ } else {
856+ m.deleteBack()
857+ }
624858 case "delete", "ctrl+d":
625- m.deleteForward()
859+ if m.HasSelection() {
860+ m.DeleteSelection()
861+ } else {
862+ m.deleteForward()
863+ }
626864 case "enter":
865+ m.DeleteSelection()
627866 m.insertNewline()
628867 case "tab":
868+ m.DeleteSelection()
629869 m.tabIndent()
630870
631871 default:
632872 moved = false
633- // Insert printable runes
634873 if !m.ReadOnly && len(msg.Runes) > 0 {
874+ m.DeleteSelection()
635875 for _, r := range msg.Runes {
636876 m.insertRune(r)
637877 }
@@ -652,11 +892,28 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
652892 }
653893 switch msg.Button {
654894 case tea.MouseButtonLeft:
655- if msg.Action == tea.MouseActionPress {
895+ switch msg.Action {
896+ case tea.MouseActionPress:
656897 p := m.screenToPos(msg.X, msg.Y)
898+ m.dragging = true
899+ m.sel = &selection{anchor: p, active: p}
657900 m.row = p.row
658901 m.col = p.col
659902 m.clampCursor()
903+ case tea.MouseActionMotion:
904+ if m.dragging {
905+ p := m.screenToPos(msg.X, msg.Y)
906+ m.sel.active = p
907+ m.row = p.row
908+ m.col = p.col
909+ m.clampCursor()
910+ }
911+ case tea.MouseActionRelease:
912+ m.dragging = false
913+ // If no actual drag distance, treat as click: clear selection
914+ if m.sel != nil && m.sel.empty() {
915+ m.ClearSelection()
916+ }
660917 }
661918 case tea.MouseButtonWheelUp:
662919 m.scroll -= 3
@@ -753,6 +1010,19 @@ func (m Model) View() string {
7531010 cursorExpandedCol = len([]rune(prefix))
7541011 }
7551012
1013+ // Pre-compute selection range in expanded-tab space (once, not per row).
1014+ hasSel := m.HasSelection()
1015+ var selStartRow, selStartExp, selEndRow, selEndExp int
1016+ if hasSel {
1017+ ss, se := m.sel.ordered()
1018+ selStartRow = ss.row
1019+ selStartExp = m.bufferColToExpandedCol(ss.row, ss.col)
1020+ selEndRow = se.row
1021+ selEndExp = m.bufferColToExpandedCol(se.row, se.col)
1022+ }
1023+
1024+ selSty := m.SelectionStyle
1025+
7561026 var b strings.Builder
7571027
7581028 for vi := 0; vi < m.height; vi++ {
@@ -785,22 +1055,51 @@ func (m Model) View() string {
7851055 segRuneOff := vr.subRow * tw // rune offset within the full expanded line
7861056 segLen := len([]rune(segText))
7871057
1058+ // Compute selection intersection for this visual row.
1059+ // selColStart/selColEnd are in segment-local expanded rune space.
1060+ rowHasSel := false
1061+ selColStart, selColEnd := 0, 0
1062+ if hasSel && vr.bufRow >= selStartRow && vr.bufRow <= selEndRow {
1063+ // Compute absolute expanded range that is selected on this buffer row.
1064+ absSelStart := 0
1065+ if vr.bufRow == selStartRow {
1066+ absSelStart = selStartExp
1067+ }
1068+ absSelEnd := segRuneOff + segLen // default: rest of line
1069+ if vr.bufRow == selEndRow {
1070+ absSelEnd = selEndExp
1071+ }
1072+ // Intersect with this segment's range [segRuneOff, segRuneOff+segLen)
1073+ localStart := absSelStart - segRuneOff
1074+ localEnd := absSelEnd - segRuneOff
1075+ if localStart < 0 {
1076+ localStart = 0
1077+ }
1078+ if localEnd > segLen {
1079+ localEnd = segLen
1080+ }
1081+ if localStart < localEnd {
1082+ rowHasSel = true
1083+ selColStart = localStart
1084+ selColEnd = localEnd
1085+ }
1086+ }
1087+
7881088 // Is the cursor on this visual row?
789- // Cursor is here if it falls within this segment's rune range,
790- // OR if it's at end-of-segment and this is the last sub-row
791- // (cursor past last char sits on the last segment).
7921089 isCursorHere := false
7931090 if m.focus && vr.bufRow == m.row {
7941091 if cursorExpandedCol >= segRuneOff && cursorExpandedCol < segRuneOff+tw {
7951092 isCursorHere = true
7961093 } else if cursorExpandedCol == segRuneOff+segLen && segLen < tw {
797- // End-of-line cursor on a short (last) segment
7981094 isCursorHere = true
7991095 }
8001096 }
8011097
8021098 var rendered string
803- if isCursorHere {
1099+ if rowHasSel {
1100+ rendered = m.renderSelectedSegment(segText, vr.fullHL, vr.segStart, segLen,
1101+ selColStart, selColEnd, selSty, bg, isCursorHere, cursorExpandedCol-segRuneOff)
1102+ } else if isCursorHere {
8041103 localCol := cursorExpandedCol - segRuneOff
8051104 rendered = m.renderCursorSegment(segText, vr.fullHL, vr.segStart, localCol)
8061105 } else if hasSyntax && vr.fullHL != "" {
@@ -866,6 +1165,97 @@ func (m Model) renderCursorSegment(segText, fullHL string, segStart, localCol in
8661165 return before + cursorView + after
8671166 }
8681167
1168+// renderSelectedSegment renders a text segment with a selection highlight
1169+// (and optionally a cursor). selStart/selEnd are segment-local rune offsets.
1170+func (m Model) renderSelectedSegment(
1171+ segText, fullHL string, segStart, segLen, selStart, selEnd int,
1172+ selSty, bg lipgloss.Style, hasCursor bool, cursorLocalCol int,
1173+) string {
1174+ hasSyntax := m.Language != "" && m.SyntaxTheme != ""
1175+ runes := []rune(segText)
1176+
1177+ // Helper: render a rune range with a given style (selection or bg).
1178+ renderRange := func(from, to int, sty lipgloss.Style) string {
1179+ if from >= to {
1180+ return ""
1181+ }
1182+ if hasSyntax && fullHL != "" {
1183+ cut := ansi.Cut(fullHL, segStart+from, segStart+to)
1184+ // Wrap in selection bg — this overrides the syntax bg
1185+ return sty.Render(ansi.Strip(cut))
1186+ }
1187+ return sty.Render(string(runes[from:to]))
1188+ }
1189+
1190+ // Helper: render a rune range with the normal style (bg or syntax HL).
1191+ renderNormal := func(from, to int) string {
1192+ if from >= to {
1193+ return ""
1194+ }
1195+ if hasSyntax && fullHL != "" {
1196+ return ansi.Cut(fullHL, segStart+from, segStart+to)
1197+ }
1198+ return bg.Render(string(runes[from:to]))
1199+ }
1200+
1201+ // If cursor is in this segment, we need to handle it specially.
1202+ if hasCursor && cursorLocalCol >= 0 && cursorLocalCol <= len(runes) {
1203+ cc := cursorLocalCol
1204+ cursorChar := " "
1205+ if cc < len(runes) {
1206+ cursorChar = string(runes[cc])
1207+ }
1208+ m.cursor.SetChar(cursorChar)
1209+ cursorInSel := cc >= selStart && cc < selEnd
1210+ if cursorInSel {
1211+ m.cursor.TextStyle = selSty
1212+ } else {
1213+ m.cursor.TextStyle = bg
1214+ }
1215+ cv := m.cursor.View()
1216+
1217+ var sb strings.Builder
1218+ switch {
1219+ case cc < selStart:
1220+ // [normal 0..cc] [cursor] [normal cc+1..selStart] [sel] [normal selEnd..end]
1221+ sb.WriteString(renderNormal(0, cc))
1222+ sb.WriteString(cv)
1223+ sb.WriteString(renderNormal(cc+1, selStart))
1224+ sb.WriteString(renderRange(selStart, selEnd, selSty))
1225+ sb.WriteString(renderNormal(selEnd, len(runes)))
1226+ case cc >= selEnd:
1227+ // [normal 0..selStart] [sel] [normal selEnd..cc] [cursor] [normal cc+1..end]
1228+ sb.WriteString(renderNormal(0, selStart))
1229+ sb.WriteString(renderRange(selStart, selEnd, selSty))
1230+ sb.WriteString(renderNormal(selEnd, cc))
1231+ sb.WriteString(cv)
1232+ if cc+1 <= len(runes) {
1233+ sb.WriteString(renderNormal(cc+1, len(runes)))
1234+ }
1235+ default:
1236+ // Cursor inside selection
1237+ // [normal 0..selStart] [sel selStart..cc] [cursor] [sel cc+1..selEnd] [normal selEnd..end]
1238+ sb.WriteString(renderNormal(0, selStart))
1239+ if cc > selStart {
1240+ sb.WriteString(renderRange(selStart, cc, selSty))
1241+ }
1242+ sb.WriteString(cv)
1243+ if cc+1 < selEnd {
1244+ sb.WriteString(renderRange(cc+1, selEnd, selSty))
1245+ }
1246+ sb.WriteString(renderNormal(selEnd, len(runes)))
1247+ }
1248+ return sb.String()
1249+ }
1250+
1251+ // No cursor: simple before/selected/after
1252+ var sb strings.Builder
1253+ sb.WriteString(renderNormal(0, selStart))
1254+ sb.WriteString(renderRange(selStart, selEnd, selSty))
1255+ sb.WriteString(renderNormal(selEnd, segLen))
1256+ return sb.String()
1257+}
1258+
8691259 // ---------------------------------------------------------------------------
8701260 // Placeholder view (shown when empty + unfocused)
8711261 // ---------------------------------------------------------------------------
internal/tui/styles.go+2−2
@@ -15,7 +15,7 @@ var (
1515 ColorMuted = lipgloss.Color("#6e6e6e") // Secondary / reasoning
1616 ColorDim = lipgloss.Color("#3f3f3f") // Tertiary / timestamps
1717 ColorBorder = lipgloss.Color("#1c1c1c") // Borders and dividers
18- ColorSurface = lipgloss.Color("#111111") // Subtle surface (selection)
18+ ColorSurface = ColorHighlight // Selection highlight — reuse accent
1919
2020 // Semantic aliases
2121 ColorError = lipgloss.Color("#932e2e")
@@ -53,7 +53,7 @@ func DefaultStyles() Styles {
5353 ToolArrow: bg.Foreground(ColorMuted),
5454
5555 Border: bg.Foreground(ColorBorder),
56- Selection: lipgloss.NewStyle().Background(ColorSurface),
56+ Selection: lipgloss.NewStyle().Background(ColorSurface).Foreground(ColorBg),
5757 BgFill: bg,
5858
5959 StatusText: bg.Foreground(ColorDim),
internal/tui/tui.go+201−6
@@ -11,6 +11,7 @@ import (
1111 "strings"
1212 "time"
1313
14+ "github.com/atotto/clipboard"
1415 "github.com/charmbracelet/bubbles/spinner"
1516 tea "github.com/charmbracelet/bubbletea"
1617 "github.com/charmbracelet/lipgloss"
@@ -135,6 +136,28 @@ const (
135136 focusEditor // Code viewer has focus
136137 )
137138
139+// ---------------------------------------------------------------------------
140+// Conversation selection (character-level)
141+// ---------------------------------------------------------------------------
142+
143+type convPos struct{ line, col int }
144+
145+// convSelection tracks a character-level selection in the conversation pane.
146+type convSelection struct {
147+ anchor convPos // Where the selection started
148+ active convPos // Current selection endpoint
149+}
150+
151+func (s convSelection) ordered() (start, end convPos) {
152+ if s.anchor.line > s.active.line ||
153+ (s.anchor.line == s.active.line && s.anchor.col > s.active.col) {
154+ return s.active, s.anchor
155+ }
156+ return s.anchor, s.active
157+}
158+
159+func (s convSelection) empty() bool { return s.anchor == s.active }
160+
138161 // ---------------------------------------------------------------------------
139162 // ELM messages
140163 // ---------------------------------------------------------------------------
@@ -280,6 +303,10 @@ type Model struct {
280303
281304 // Mouse state
282305 resizingPane bool
306+
307+ // Conversation selection (line-level, wrapped line indices)
308+ convSel *convSelection
309+ convDragging bool
283310 }
284311
285312 // New creates a new TUI model.
@@ -291,18 +318,22 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
291318 s.Spinner = spinner.Dot
292319 s.Style = cursorStyle.Background(ColorBg)
293320
321+ selStyle := sty.Selection
322+
294323 ed := editor.New()
295324 ed.ShowLineNumbers = true
296325 ed.ReadOnly = true
297326 ed.Language = "markdown"
298327 ed.SyntaxTheme = constants.SyntaxTheme
299328 ed.CursorStyle = cursorStyle
329+ ed.SelectionStyle = selStyle
300330 ed.LineNumStyle = lipgloss.NewStyle().Foreground(ColorBorder)
301331 ed.BgColor = ColorBg
302332
303333 ai := editor.New()
304334 ai.Placeholder = "Type a message..."
Cut short: this commit's diff is over 1000 lines.