1package tui
2
3import (
4 "fmt"
5 "net/url"
6 "os"
7 "path/filepath"
8 "regexp"
9 "strings"
10
11 "github.com/mattn/go-runewidth"
12)
13
14// Editor is a simple multi-line text editor for the input area.
15//
16// Users can type, paste, move the cursor, and submit. The editor
17// exposes its rendered height and the current cursor row/col for the
18// outer renderer. It does NOT draw itself directly; instead, Render()
19// returns the visible lines.
20type Editor struct {
21 // Lines is the current buffer, one entry per line.
22 Lines []string
23 CursorR int // row index into Lines
24 CursorC int // rune index into Lines[CursorR]
25 Prompt string
26 MaxWidth int
27
28 // lastRenderWidth is the column count passed to the most recent
29 // Render() call. Up/Down key handling needs this to walk the
30 // same visual layout the user sees: a logical line that wraps to
31 // two rows should respond to Up by moving to the previous visual
32 // row, not do nothing because CursorR is already 0.
33 lastRenderWidth int
34
35 // pastes stores the full content of every multi-line paste,
36 // keyed by the id embedded in the visible placeholder token.
37 // Pasted text is collapsed to "[paste #N +L lines]" in the
38 // editor so a 500-line drop doesn't explode the input area;
39 // SubmitValue() expands placeholders back to their real bodies
40 // right before the prompt goes to the agent. The map is reset
41 // on Clear() so stale pastes never leak into a follow-up turn.
42 pastes map[int]string
43 pasteSeq int
44
45 // files and dirs store full paths of drag-dropped items, keyed
46 // by separate sequence ids. The editor shows compact chips like
47 // [file:1:name] and [dir:1:name/] and SubmitValue() expands
48 // them back to the full path.
49 files map[int]string
50 fileSeq int
51 dirs map[int]string
52 dirSeq int
53}
54
55// NewEditor returns an empty editor with the given prompt.
56func NewEditor(prompt string) *Editor {
57 return &Editor{
58 Lines: []string{""},
59 Prompt: prompt,
60 }
61}
62
63// Value returns the buffer as a single string, WITHOUT expanding
64// paste placeholders. Used for anything that should reflect what's
65// visible on screen (history, slash-command detection, editor
66// state). For the string that actually goes to the agent, use
67// SubmitValue(), which expands each [paste #N +L lines] token
68// back into the full pasted body.
69func (e *Editor) Value() string { return strings.Join(e.Lines, "\n") }
70
71// SubmitValue returns the buffer with every paste placeholder
72// expanded to its stored body. Call once at submit time; the
73// expansion is lossless (placeholders are only injected in
74// HandleKey for KeyPaste with multi-line content).
75//
76// Expansion is non-destructive: the internal paste map isn't
77// touched. Clear() is what resets both the placeholder text and
78// the map, and the caller already calls Clear() right after
79// reading SubmitValue() as part of the submit flow.
80func (e *Editor) SubmitValue() string {
81 raw := e.Value()
82 if len(e.pastes) > 0 && strings.Contains(raw, "[pasted text #") {
83 raw = expandPastePlaceholders(raw, e.pastes)
84 }
85 if (len(e.files) > 0 || len(e.dirs) > 0) && (strings.Contains(raw, "[file:") || strings.Contains(raw, "[dir:")) {
86 raw = expandFilePlaceholders(raw, e.files, e.dirs)
87 }
88 return raw
89}
90
91// SetValue replaces the buffer and places the cursor at the end.
92// Also drops any stored pastes because the placeholders they back
93// are now gone from the visible text.
94func (e *Editor) SetValue(s string) {
95 s = normalizeEditorText(s)
96 e.Lines = strings.Split(s, "\n")
97 if len(e.Lines) == 0 {
98 e.Lines = []string{""}
99 }
100 e.CursorR = len(e.Lines) - 1
101 e.CursorC = runeLen(e.Lines[e.CursorR])
102 e.pastes = nil
103 e.pasteSeq = 0
104 e.files = nil
105 e.fileSeq = 0
106 e.dirs = nil
107 e.dirSeq = 0
108}
109
110// Clear resets the buffer.
111func (e *Editor) Clear() { e.SetValue("") }
112
113// IsEmpty reports whether the buffer has no visible content.
114func (e *Editor) IsEmpty() bool {
115 return len(e.Lines) == 1 && e.Lines[0] == ""
116}
117
118// HandleKey applies k to the editor. It returns submit=true when
119// the user pressed enter and there is content to send; the caller
120// should read SubmitValue() and then Clear().
121func (e *Editor) HandleKey(k Key) (submit bool) {
122 switch k.Kind {
123 case KeyRune:
124 if k.Alt && (k.Rune == '\r' || k.Rune == '\n') {
125 e.newline()
126 return false
127 }
128 e.insert(string(k.Rune))
129 case KeyEnter:
130 // Shift+Enter would be a separate key in some terminals; we treat
131 // the literal newline byte as Enter. Newline on submit is a decision
132 // for the outer UI via slash commands. Here Enter submits.
133 return true
134 case KeyBackspace:
135 if k.Alt {
136 // Alt+Backspace (Option+Delete on macOS) — delete previous word.
137 e.deleteWord()
138 } else {
139 e.backspace()
140 }
141 case KeyDelete:
142 e.delete()
143 case KeyLeft:
144 if k.Alt {
145 e.moveWordLeft()
146 } else {
147 e.moveLeft()
148 }
149 case KeyRight:
150 if k.Alt {
151 e.moveWordRight()
152 } else {
153 e.moveRight()
154 }
155 case KeyUp:
156 // Visual-row navigation. When a single logical line wraps
157 // to several visual rows, Up needs to climb one visual
158 // row — which may mean moving within the same
159 // e.Lines[CursorR] back toward an earlier rune index,
160 // not jumping to CursorR-1. Buffer-line navigation is
161 // subsumed: a visual row above may also live in the
162 // previous logical line when a short line precedes a
163 // wrapped one.
164 e.MoveVertical(-1)
165 case KeyDown:
166 e.MoveVertical(+1)
167 case KeyHome, KeyCtrlA:
168 e.CursorC = 0
169 case KeyEnd, KeyCtrlE:
170 e.CursorC = runeLen(e.Lines[e.CursorR])
171 case KeyCtrlU:
172 e.Lines[e.CursorR] = substringAfter(e.Lines[e.CursorR], e.CursorC)
173 e.CursorC = 0
174 case KeyCtrlK:
175 e.Lines[e.CursorR] = substringBefore(e.Lines[e.CursorR], e.CursorC)
176 case KeyCtrlW:
177 e.deleteWord()
178 case KeyPaste:
179 paste := normalizeEditorText(k.Paste)
180 // Large multi-line pastes are collapsed to a short
181 // placeholder token so the editor doesn't balloon to
182 // hundreds of rows. The full body is stashed in e.pastes,
183 // keyed by a monotonically increasing id, and swapped
184 // back in at submit time via SubmitValue. Threshold:
185 // two or more newlines triggers collapse; one-liners and
186 // drag-dropped file paths fall through to the original
187 // insert path (including file-path quoting).
188 if pasteShouldCollapse(paste) {
189 if e.pastes == nil {
190 e.pastes = map[int]string{}
191 }
192 e.pasteSeq++
193 id := e.pasteSeq
194 e.pastes[id] = paste
195 e.insert(formatPastePlaceholder(id, paste))
196 } else {
197 // macOS Terminal / iTerm / Ghostty deliver drag-dropped
198 // files as bracketed-paste text. Detect that pattern
199 // and collapse long paths to a [file:basename] chip.
200 inserted := e.collapseOrQuoteFilePaths(paste)
201 e.insert(inserted)
202 }
203 case KeyEsc:
204 e.Clear()
205 }
206 return false
207}
208
209// quotePastedFilePaths returns paste with any drag-dropped file
210// paths wrapped in single quotes. Heuristics:
211//
212// - one line only; multi-line text is returned unchanged so we
213// never touch a real paste of code.
214// - whitespace-separated tokens are inspected one by one. A token
215// that looks like a filesystem path (absolute, ~/relative, or
216// file:// URL) is normalised and re-quoted; everything else is
217// left exactly as the user dropped it.
218// - terminal-style backslash escapes ("foo\ bar.png") are folded
219// back to literal characters before quoting, since wrapping in
220// single quotes makes them unnecessary.
221// - file:// URLs are URL-decoded and stripped of the scheme so
222// the agent receives a plain filesystem path.
223// - if a path contains a literal single quote, it's escaped using
224// the standard '\” splice.
225//
226// Pastes that don't contain any path-shaped tokens are returned
227// unchanged.
228func quotePastedFilePaths(paste string) string {
229 if paste == "" || strings.ContainsRune(paste, '\n') {
230 return paste
231 }
232 trimmed := strings.TrimSpace(paste)
233 if trimmed == "" {
234 return paste
235 }
236
237 // Split on runs of whitespace, preserving the original separators
238 // so multi-file drops keep their spacing on rebuild. Backslash
239 // before a space is treated as part of the preceding token, since
240 // macOS Terminal escapes spaces in dropped paths that way.
241 tokens := splitPreservingSeparators(paste)
242 changed := false
243 for i, tk := range tokens {
244 if tk.isSpace {
245 continue
246 }
247 if p, ok := normalisePathToken(tk.text); ok {
248 tokens[i].text = singleQuote(p)
249 changed = true
250 }
251 }
252 if !changed {
253 return paste
254 }
255 var out strings.Builder
256 out.Grow(len(paste) + 8)
257 for _, tk := range tokens {
258 out.WriteString(tk.text)
259 }
260 return out.String()
261}
262
263type pasteToken struct {
264 text string
265 isSpace bool
266}
267
268// splitPreservingSeparators splits s into runs of whitespace and
269// runs of non-whitespace, keeping the separator runs intact so a
270// rebuild via concatenation reproduces the original string exactly.
271// A backslash immediately followed by a space ("\ ") is treated as
272// part of the preceding non-whitespace run, since that's how macOS
273// Terminal escapes spaces in drag-dropped file paths.
274func splitPreservingSeparators(s string) []pasteToken {
275 runes := []rune(s)
276 var out []pasteToken
277 var buf strings.Builder
278 inSpace := false
279 flush := func() {
280 if buf.Len() == 0 {
281 return
282 }
283 out = append(out, pasteToken{text: buf.String(), isSpace: inSpace})
284 buf.Reset()
285 }
286 for i := 0; i < len(runes); i++ {
287 r := runes[i]
288 isEscapedSpace := r == '\\' && i+1 < len(runes) && (runes[i+1] == ' ' || runes[i+1] == '\t')
289 rSpace := !isEscapedSpace && (r == ' ' || r == '\t')
290 if buf.Len() == 0 {
291 inSpace = rSpace
292 } else if rSpace != inSpace {
293 flush()
294 inSpace = rSpace
295 }
296 if isEscapedSpace {
297 // Skip the backslash; emit the literal space as part of
298 // this non-whitespace token. normalisePathToken's
299 // unescapeBackslashes is now redundant for this path but
300 // stays in case some other source escapes other chars.
301 buf.WriteRune(runes[i+1])
302 i++
303 continue
304 }
305 buf.WriteRune(r)
306 }
307 flush()
308 return out
309}
310
311// normalisePathToken decides whether tk is a drag-dropped path and,
312// if so, returns the cleaned-up path string.
313//
314// To avoid mistaking URL path segments (e.g. "/de/downloads/foo"
315// pasted from a browser address bar) for filesystem paths, the
316// candidate must point to an entry that actually exists on disk.
317// Drag-and-drop from a file manager always satisfies this; a
318// hand-typed URL fragment doesn't, so it falls through to the
319// regular insert path untouched.
320func normalisePathToken(tk string) (string, bool) {
321 // Strip pre-existing surrounding quotes; we'll re-quote consistently.
322 if n := len(tk); n >= 2 {
323 if (tk[0] == '\'' && tk[n-1] == '\'') || (tk[0] == '"' && tk[n-1] == '"') {
324 tk = tk[1 : n-1]
325 }
326 }
327
328 // file:// URL form: decode and strip the scheme.
329 if strings.HasPrefix(tk, "file://") {
330 decoded, err := url.PathUnescape(strings.TrimPrefix(tk, "file://"))
331 if err != nil {
332 return "", false
333 }
334 if decoded == "" || decoded[0] != '/' {
335 return "", false
336 }
337 if !pathExists(decoded) {
338 return "", false
339 }
340 return decoded, true
341 }
342
343 // Looks-like-a-path heuristic: starts with /, ~, ~/. Must contain
344 // at least one path separator after the prefix (otherwise a bare
345 // "/" or "~" gets quoted, which is never what the user meant).
346 if !strings.HasPrefix(tk, "/") && !strings.HasPrefix(tk, "~") {
347 return "", false
348 }
349 if !strings.ContainsAny(tk[1:], "/.") {
350 return "", false
351 }
352 unescaped := unescapeBackslashes(tk)
353 if strings.ContainsAny(unescaped, "|;&$`<>") {
354 return "", false
355 }
356 if !pathExists(unescaped) {
357 return "", false
358 }
359 return unescaped, true
360}
361
362// pathExists reports whether p resolves to an existing filesystem
363// entry (file, directory, or symlink target). "~" / "~/" prefixes
364// are expanded relative to the current user's home directory before
365// the check, mirroring how the agent will later read the path.
366func pathExists(p string) bool {
367 if p == "" {
368 return false
369 }
370 expanded := p
371 if p == "~" || strings.HasPrefix(p, "~/") {
372 home, err := os.UserHomeDir()
373 if err != nil || home == "" {
374 return false
375 }
376 if p == "~" {
377 expanded = home
378 } else {
379 expanded = filepath.Join(home, p[2:])
380 }
381 }
382 _, err := os.Stat(expanded)
383 return err == nil
384}
385
386// unescapeBackslashes turns "foo\ bar" into "foo bar". Terminal
387// drag-and-drop on macOS uses backslash escaping by default; quoting
388// makes that unnecessary.
389func unescapeBackslashes(s string) string {
390 if !strings.Contains(s, `\`) {
391 return s
392 }
393 var out strings.Builder
394 out.Grow(len(s))
395 prev := false
396 for _, r := range s {
397 if prev {
398 out.WriteRune(r)
399 prev = false
400 continue
401 }
402 if r == '\\' {
403 prev = true
404 continue
405 }
406 out.WriteRune(r)
407 }
408 if prev {
409 out.WriteRune('\\')
410 }
411 return out.String()
412}
413
414// singleQuote wraps s in single quotes, escaping any embedded single
415// quote using the splice idiom: 'foo'\”bar' for foo'bar.
416func singleQuote(s string) string {
417 return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
418}
419
420// Insert places s into the editor at the cursor, splitting on
421// newlines so multi-line pastes preserve their structure.
422func (e *Editor) Insert(s string) { e.insert(s) }
423
424func (e *Editor) insert(s string) {
425 s = normalizeEditorText(s)
426 line := e.Lines[e.CursorR]
427 pre := substringBefore(line, e.CursorC)
428 post := substringAfter(line, e.CursorC)
429 // Split pasted text on newlines.
430 parts := strings.Split(s, "\n")
431 if len(parts) == 1 {
432 e.Lines[e.CursorR] = pre + s + post
433 e.CursorC += runeLen(s)
434 return
435 }
436 newLines := make([]string, 0, len(e.Lines)+len(parts)-1)
437 newLines = append(newLines, e.Lines[:e.CursorR]...)
438 newLines = append(newLines, pre+parts[0])
439 for i := 1; i < len(parts)-1; i++ {
440 newLines = append(newLines, parts[i])
441 }
442 last := parts[len(parts)-1]
443 newLines = append(newLines, last+post)
444 newLines = append(newLines, e.Lines[e.CursorR+1:]...)
445 e.Lines = newLines
446 e.CursorR += len(parts) - 1
447 e.CursorC = runeLen(last)
448}
449
450func (e *Editor) newline() {
451 line := e.Lines[e.CursorR]
452 pre := substringBefore(line, e.CursorC)
453 post := substringAfter(line, e.CursorC)
454 e.Lines[e.CursorR] = pre
455 e.Lines = append(e.Lines, "")
456 copy(e.Lines[e.CursorR+2:], e.Lines[e.CursorR+1:])
457 e.Lines[e.CursorR+1] = post
458 e.CursorR++
459 e.CursorC = 0
460}
461
462func (e *Editor) backspace() {
463 if e.CursorC == 0 {
464 if e.CursorR == 0 {
465 return
466 }
467 prev := e.Lines[e.CursorR-1]
468 cur := e.Lines[e.CursorR]
469 e.Lines = append(e.Lines[:e.CursorR], e.Lines[e.CursorR+1:]...)
470 e.CursorR--
471 e.CursorC = runeLen(prev)
472 e.Lines[e.CursorR] = prev + cur
473 return
474 }
475 line := e.Lines[e.CursorR]
476 e.Lines[e.CursorR] = substringBefore(line, e.CursorC-1) + substringAfter(line, e.CursorC)
477 e.CursorC--
478}
479
480func (e *Editor) delete() {
481 line := e.Lines[e.CursorR]
482 if e.CursorC == runeLen(line) {
483 if e.CursorR == len(e.Lines)-1 {
484 return
485 }
486 next := e.Lines[e.CursorR+1]
487 e.Lines = append(e.Lines[:e.CursorR+1], e.Lines[e.CursorR+2:]...)
488 e.Lines[e.CursorR] = line + next
489 return
490 }
491 e.Lines[e.CursorR] = substringBefore(line, e.CursorC) + substringAfter(line, e.CursorC+1)
492}
493
494// moveWordLeft jumps the cursor to the start of the previous word,
495// using the same word-separator rules as deleteWord. If already at the
496// start of the line, wraps to the end of the previous line.
497func (e *Editor) moveWordLeft() {
498 if e.CursorC == 0 {
499 if e.CursorR > 0 {
500 e.CursorR--
501 e.CursorC = runeLen(e.Lines[e.CursorR])
502 }
503 return
504 }
505 r := []rune(e.Lines[e.CursorR])
506 i := e.CursorC
507 for i > 0 && isWordSep(r[i-1]) {
508 i--
509 }
510 for i > 0 && !isWordSep(r[i-1]) {
511 i--
512 }
513 e.CursorC = i
514}
515
516// moveWordRight jumps the cursor to the start of the next word. If
517// already at the end of the line, wraps to the start of the next line.
518func (e *Editor) moveWordRight() {
519 line := e.Lines[e.CursorR]
520 if e.CursorC >= runeLen(line) {
521 if e.CursorR < len(e.Lines)-1 {
522 e.CursorR++
523 e.CursorC = 0
524 }
525 return
526 }
527 r := []rune(line)
528 i := e.CursorC
529 for i < len(r) && !isWordSep(r[i]) {
530 i++
531 }
532 for i < len(r) && isWordSep(r[i]) {
533 i++
534 }
535 e.CursorC = i
536}
537
538func (e *Editor) moveLeft() {
539 if e.CursorC > 0 {
540 e.CursorC--
541 return
542 }
543 if e.CursorR > 0 {
544 e.CursorR--
545 e.CursorC = runeLen(e.Lines[e.CursorR])
546 }
547}
548
549func (e *Editor) moveRight() {
550 if e.CursorC < runeLen(e.Lines[e.CursorR]) {
551 e.CursorC++
552 return
553 }
554 if e.CursorR < len(e.Lines)-1 {
555 e.CursorR++
556 e.CursorC = 0
557 }
558}
559
560// moveCursorVisual moves the cursor one visual row in direction
561// dir (-1 = up, +1 = down) through the wrapped layout the user
562// sees on screen. Handles both multi-line logical inputs and the
563// case where a single long line wraps across several visual
564// rows.
565//
566// Algorithm: rebuild the same wrapped layout Render produces,
567// tagging each visual row with (logicalRow, runeOffsetStart,
568// runeOffsetEnd, leadingWidth). Find the row the cursor sits on,
569// then pick (row+dir) and map the cursor's current visual column
570// (minus the target row's leading indent) to a rune index inside
571// that row's slice of its logical line. No-op at the top/bottom
572// edges of the whole buffer.
573// MoveVertical moves the cursor one visual row up/down through the
574// rendered editor layout. It returns true when the cursor moved, false
575// at the top/bottom edge. Callers can use false to fall back to outer
576// UI scrolling.
577func (e *Editor) MoveVertical(dir int) bool {
578 width := e.lastRenderWidth
579 if width <= 0 {
580 // Fall back to logical-line navigation if Render hasn't
581 // been called yet (shouldn't happen in practice; the
582 // host always renders once before accepting input).
583 return e.moveCursorLogical(dir)
584 }
585
586 type vrow struct {
587 logical int // e.Lines index
588 runeStart int // rune offset into e.Lines[logical]
589 runeEnd int // exclusive
590 leadWidth int // width of prompt / cont indent on this row
591 leadPrefix string // the prefix used (prompt on row 0, indent on cont)
592 }
593
594 // Match Render's layout exactly: strip ANSI from the prompt before
595 // wrapping, otherwise escape bytes count as body runes and Up/Down
596 // lands in the wrong visual cell when the prompt is styled.
597 plainPrompt := stripANSI(e.Prompt)
598 promptLen := runewidth.StringWidth(plainPrompt)
599 indent := strings.Repeat(" ", promptLen)
600
601 var rows []vrow
602 curVRow, curVCol := 0, 0
603 for r, line := range e.Lines {
604 prefix := indent
605 if r == 0 {
606 prefix = plainPrompt
607 }
608 wrapped := wrapLine(prefix+line, width, indent)
609 lineRunes := []rune(line)
610 seen := 0
611 for wi, w := range wrapped {
612 var leadW int
613 var leadP string
614 body := w
615 if wi == 0 {
616 if strings.HasPrefix(body, prefix) {
617 body = body[len(prefix):]
618 }
619 leadW = promptLen
620 leadP = prefix
621 } else {
622 if strings.HasPrefix(body, indent) {
623 body = body[len(indent):]
624 }
625 leadW = promptLen
626 leadP = indent
627 }
628 bodyRunes := []rune(body)
629 start := seen
630 end := seen + len(bodyRunes)
631 rows = append(rows, vrow{
632 logical: r, runeStart: start, runeEnd: end,
633 leadWidth: leadW, leadPrefix: leadP,
634 })
635 // Record where the cursor currently sits.
636 if r == e.CursorR && e.CursorC >= start && e.CursorC <= end {
637 curVRow = len(rows) - 1
638 inner := e.CursorC - start
639 if inner < 0 {
640 inner = 0
641 }
642 if inner > len(bodyRunes) {
643 inner = len(bodyRunes)
644 }
645 curVCol = leadW + runewidth.StringWidth(string(bodyRunes[:inner]))
646 }
647 seen = end
648 // Word-wrap often drops a single space at the boundary.
649 for seen < len(lineRunes) && lineRunes[seen] == ' ' {
650 seen++
651 }
652 }
653 }
654
655 target := curVRow + dir
656 if target < 0 || target >= len(rows) {
657 return false
658 }
659 tr := rows[target]
660 line := e.Lines[tr.logical]
661 lineRunes := []rune(line)
662 bodyRunes := lineRunes[tr.runeStart:tr.runeEnd]
663
664 // Find the rune offset inside bodyRunes whose visible column
665 // most closely matches curVCol after accounting for leadWidth.
666 want := curVCol - tr.leadWidth
667 if want < 0 {
668 want = 0
669 }
670 best := 0
671 bestW := 0
672 for i := 1; i <= len(bodyRunes); i++ {
673 w := runewidth.StringWidth(string(bodyRunes[:i]))
674 if w > want {
675 break
676 }
677 best = i
678 bestW = w
679 if w == want {
680 break
681 }
682 }
683 _ = bestW
684 e.CursorR = tr.logical
685 e.CursorC = tr.runeStart + best
686 return true
687}
688
689// moveCursorLogical is the pre-visual-navigation fallback used
690// when Render hasn't told us the terminal width yet. Walks the
691// e.Lines array directly.
692func (e *Editor) moveCursorLogical(dir int) bool {
693 switch {
694 case dir < 0 && e.CursorR > 0:
695 e.CursorR--
696 case dir > 0 && e.CursorR < len(e.Lines)-1:
697 e.CursorR++
698 default:
699 return false
700 }
701 if e.CursorC > runeLen(e.Lines[e.CursorR]) {
702 e.CursorC = runeLen(e.Lines[e.CursorR])
703 }
704 return true
705}
706
707func (e *Editor) deleteWord() {
708 line := e.Lines[e.CursorR]
709 if e.CursorC == 0 {
710 e.backspace()
711 return
712 }
713 r := []rune(line)
714 i := e.CursorC
715 // Step 1: walk over any trailing whitespace to the left of the cursor.
716 for i > 0 && isWordSep(r[i-1]) {
717 i--
718 }
719 // Step 2: walk over the word itself (non-separator runes).
720 for i > 0 && !isWordSep(r[i-1]) {
721 i--
722 }
723 e.Lines[e.CursorR] = string(r[:i]) + string(r[e.CursorC:])
724 e.CursorC = i
725}
726
727// isWordSep reports whether r is a word separator. Anything that isn't
728// a letter, digit, or underscore counts as a separator so delete-word
729// feels natural on paths, code, and prose.
730func isWordSep(r rune) bool {
731 switch {
732 case r == '_':
733 return false
734 case r >= '0' && r <= '9':
735 return false
736 case r >= 'a' && r <= 'z':
737 return false
738 case r >= 'A' && r <= 'Z':
739 return false
740 case r >= 0x80:
741 // Treat all non-ASCII as word chars so CJK/äöü don't get chopped.
742 return false
743 }
744 return true
745}
746
747// ---- rendering ----
748
749// Render returns the editor's visible lines (wrapped to width).
750// visualRow/visualCol describe where the cursor lands within the returned lines.
751func (e *Editor) Render(width int) (lines []string, visualRow, visualCol int) {
752 e.lastRenderWidth = width
753 // The Prompt may carry ANSI styling (theme-coloured glyph + reset).
754 // We must compute wrap geometry using its *visible* width only;
755 // otherwise the raw escape bytes leak into wrapLine's per-rune
756 // width accounting and the cursor column lands inside the row
757 // instead of at the end. See the wrapLine docs for why we keep it
758 // ANSI-unaware: the rest of the codebase relies on its simple
759 // rune-based behaviour for plain text and would regress if we
760 // taught it about escape sequences here. Strip ANSI from the
761 // prompt used for layout, then re-apply the original styling to
762 // the very first wrapped row before returning.
763 plainPrompt := stripANSI(e.Prompt)
764 promptLen := runewidth.StringWidth(plainPrompt)
765 indent := strings.Repeat(" ", promptLen)
766
767 for r, line := range e.Lines {
768 var prefix string
769 if r == 0 {
770 prefix = plainPrompt
771 } else {
772 prefix = indent
773 }
774 wrapped := wrapLine(prefix+line, width, indent)
775 if r == e.CursorR {
776 // Compute where CursorC lands inside the wrapped rows by
777 // walking the wrapped output character-by-character and
778 // tracking which wrapped row + column corresponds to the
779 // cursor's rune index in `line`. This is the only reliable
780 // answer under word-wrap, where a simple (promptLen+col)/width
781 // formula overshoots when wrapLine broke on a space.
782 targetRunes := e.CursorC
783 row, col := locateCursor(wrapped, prefix, line, targetRunes, indent)
784 visualRow = len(lines) + row
785 visualCol = col
786 }
787 // Re-attach the styled prompt to the very first wrapped row of
788 // the first logical line. All later rows are indent-only and
789 // don't need styling. The replacement is byte-exact because the
790 // plain prompt sits at the row's start.
791 if r == 0 && len(wrapped) > 0 && strings.HasPrefix(wrapped[0], plainPrompt) {
792 wrapped[0] = e.Prompt + wrapped[0][len(plainPrompt):]
793 }
794 lines = append(lines, wrapped...)
795 }
796 return lines, visualRow, visualCol
797}
798
799// locateCursor finds the wrapped row + visible column corresponding to
800// `targetRunes` rune positions into the logical `line`, given that the
801// wrapped output `wrapped` started with `prefix` on its first row and
802// uses `cont` as the continuation indent on subsequent rows.
803func locateCursor(wrapped []string, prefix, line string, targetRunes int, cont string) (int, int) {
804 prefixW := visibleWidth(prefix)
805 contW := visibleWidth(cont)
806 lineRunes := []rune(line)
807 if targetRunes > len(lineRunes) {
808 targetRunes = len(lineRunes)
809 }
810
811 seenRunes := 0
812 for row, w := range wrapped {
813 // strip leading prefix / continuation indent before counting runes
814 body := w
815 var leadW int
816 if row == 0 {
817 if strings.HasPrefix(body, prefix) {
818 body = body[len(prefix):]
819 }
820 leadW = prefixW
821 } else {
822 if strings.HasPrefix(body, cont) {
823 body = body[len(cont):]
824 }
825 leadW = contW
826 }
827 bodyRunes := []rune(body)
828 // Could this wrapped row contain the cursor?
829 if targetRunes <= seenRunes+len(bodyRunes) {
830 // Column inside body.
831 inner := targetRunes - seenRunes
832 if inner < 0 {
833 inner = 0
834 }
835 col := leadW + runewidth.StringWidth(string(bodyRunes[:inner]))
836 return row, col
837 }
838 seenRunes += len(bodyRunes)
839 // Word-wrap may have dropped whitespace at the boundary; skip the
840 // corresponding runes in `line` so counts stay aligned.
841 for seenRunes < len(lineRunes) && lineRunes[seenRunes] == ' ' {
842 seenRunes++
843 if seenRunes >= targetRunes {
844 // Cursor landed in the skipped whitespace — place it at
845 // the start of the next wrapped row.
846 nextRow := row + 1
847 if nextRow >= len(wrapped) {
848 nextRow = row
849 }
850 return nextRow, contW
851 }
852 }
853 }
854 // Fallback: end of the last wrapped row.
855 if len(wrapped) == 0 {
856 return 0, prefixW
857 }
858 last := wrapped[len(wrapped)-1]
859 return len(wrapped) - 1, visibleWidth(last)
860}
861
862// ---- helpers ----
863
864func substringBefore(s string, col int) string {
865 r := []rune(s)
866 if col > len(r) {
867 col = len(r)
868 }
869 return string(r[:col])
870}
871
872func substringAfter(s string, col int) string {
873 r := []rune(s)
874 if col > len(r) {
875 col = len(r)
876 }
877 return string(r[col:])
878}
879
880func runeLen(s string) int { return len([]rune(s)) }
881
882// normalizeEditorText converts all common line endings to \n before text
883// reaches the renderer. A literal carriage return would move the terminal
884// cursor back to column 0 and overwrite the left side of the input row.
885func normalizeEditorText(s string) string {
886 if !strings.ContainsRune(s, '\r') {
887 return s
888 }
889 s = strings.ReplaceAll(s, "\r\n", "\n")
890 return strings.ReplaceAll(s, "\r", "\n")
891}
892
893func visualColumn(s string, runeCol int) int {
894 r := []rune(s)
895 if runeCol > len(r) {
896 runeCol = len(r)
897 }
898 return runewidth.StringWidth(string(r[:runeCol]))
899}
900
901func visibleWidth(s string) int {
902 return runewidth.StringWidth(stripANSI(s))
903}
904
905func stripANSI(s string) string {
906 // Minimal ANSI stripper; handles CSI sequences (ESC [ ... final).
907 var out []rune
908 i := 0
909 runes := []rune(s)
910 for i < len(runes) {
911 if runes[i] == 0x1b && i+1 < len(runes) && runes[i+1] == '[' {
912 i += 2
913 for i < len(runes) {
914 c := runes[i]
915 i++
916 if c >= 0x40 && c <= 0x7e {
917 break
918 }
919 }
920 continue
921 }
922 out = append(out, runes[i])
923 i++
924 }
925 return string(out)
926}
927
928// WrapANSILine is the exported form of wrapANSILine so other modes /
929// dialogs can reuse the same visible-width-aware wrap behavior.
930func WrapANSILine(s string, limit int) []string { return wrapANSILine(s, limit) }
931
932// wrapANSILine folds a string that may contain ANSI CSI escapes so that
933// the visible width of each line stays within limit. Breaks happen on
934// spaces when possible, falling back to mid-token splits for very long
935// unbroken runs. Escape sequences are preserved verbatim and never
936// counted toward the visible column.
937func wrapANSILine(s string, limit int) []string {
938 if limit <= 0 {
939 return []string{s}
940 }
941 if visibleWidth(s) <= limit {
942 return []string{s}
943 }
944 runes := []rune(s)
945 var out []string
946 var line strings.Builder
947 var word strings.Builder
948 lineW := 0
949 wordW := 0
950
951 flushLine := func() {
952 out = append(out, line.String())
953 line.Reset()
954 lineW = 0
955 }
956 flushWord := func() {
957 if word.Len() == 0 {
958 return
959 }
960 if lineW+wordW > limit && lineW > 0 {
961 flushLine()
962 }
963 // If the word alone is bigger than the limit, split it by runes.
964 if wordW > limit {
965 wr := []rune(word.String())
966 for i := 0; i < len(wr); {
967 r := wr[i]
968 if r == 0x1b && i+1 < len(wr) && wr[i+1] == '[' {
969 line.WriteRune(r)
970 line.WriteRune(wr[i+1])
971 i += 2
972 for i < len(wr) {
973 c := wr[i]
974 line.WriteRune(c)
975 i++
976 if c >= 0x40 && c <= 0x7e {
977 break
978 }
979 }
980 continue
981 }
982 rw := runewidth.RuneWidth(r)
983 if lineW+rw > limit && lineW > 0 {
984 flushLine()
985 }
986 line.WriteRune(r)
987 lineW += rw
988 i++
989 }
990 word.Reset()
991 wordW = 0
992 return
993 }
994 line.WriteString(word.String())
995 lineW += wordW
996 word.Reset()
997 wordW = 0
998 }
999
1000 for i := 0; i < len(runes); {
1001 r := runes[i]
1002 if r == 0x1b && i+1 < len(runes) && runes[i+1] == '[' {
1003 word.WriteRune(r)
1004 word.WriteRune(runes[i+1])
1005 i += 2
1006 for i < len(runes) {
1007 c := runes[i]
1008 word.WriteRune(c)
1009 i++
1010 if c >= 0x40 && c <= 0x7e {
1011 break
1012 }
1013 }
1014 continue
1015 }
1016 if r == ' ' || r == '\t' {
1017 flushWord()
1018 rw := runewidth.RuneWidth(r)
1019 if lineW+rw > limit && lineW > 0 {
1020 flushLine()
1021 i++
1022 continue
1023 }
1024 line.WriteRune(r)
1025 lineW += rw
1026 i++
1027 continue
1028 }
1029 word.WriteRune(r)
1030 wordW += runewidth.RuneWidth(r)
1031 i++
1032 }
1033 flushWord()
1034 if line.Len() > 0 {
1035 flushLine()
1036 }
1037 if len(out) == 0 {
1038 out = []string{""}
1039 }
1040 return out
1041}
1042
1043func wrapLine(s string, width int, cont string) []string {
1044 if width <= 0 {
1045 return []string{s}
1046 }
1047
1048 // Tokenize on spaces while preserving their widths. Runs of spaces
1049 // stay attached to the preceding word so trailing whitespace doesn't
1050 // create empty wrapped lines.
1051 type token struct {
1052 text string
1053 width int
1054 space bool // true if this token is whitespace only
1055 }
1056 var tokens []token
1057 {
1058 var buf strings.Builder
1059 var bufW int
1060 inSpace := false
1061 flush := func() {
1062 if buf.Len() == 0 {
1063 return
1064 }
1065 tokens = append(tokens, token{text: buf.String(), width: bufW, space: inSpace})
1066 buf.Reset()
1067 bufW = 0
1068 }
1069 for _, r := range s {
1070 rSpace := r == ' ' || r == '\t'
1071 if buf.Len() == 0 {
1072 inSpace = rSpace
1073 } else if rSpace != inSpace {
1074 flush()
1075 inSpace = rSpace
1076 }
1077 buf.WriteRune(r)
1078 bufW += runewidth.RuneWidth(r)
1079 }
1080 flush()
1081 }
1082
1083 var out []string
1084 var cur strings.Builder
1085 curW := 0
1086 firstLine := true
1087 contW := visibleWidth(cont)
1088
1089 newLine := func() {
1090 out = append(out, cur.String())
1091 cur.Reset()
1092 curW = 0
1093 // After flushing, everything we append next is a CONTINUATION
1094 // row, which must start with the cont indent so the editor's
1095 // visual cursor alignment stays consistent. The old code only
1096 // wrote cont when !firstLine BEFORE toggling firstLine, which
1097 // meant the very first wrap never got its indent. That caused
1098 // the terminal cursor to land in the wrong column after a
1099 // multi-line paste.
1100 firstLine = false
1101 cur.WriteString(cont)
1102 curW = contW
1103 }
1104
1105 for i := 0; i < len(tokens); i++ {
1106 tk := tokens[i]
1107
1108 // Drop leading whitespace after a wrap.
1109 if tk.space && curW == contW && !firstLine {
1110 continue
1111 }
1112
1113 if curW+tk.width <= width {
1114 cur.WriteString(tk.text)
1115 curW += tk.width
1116 continue
1117 }
1118
1119 // Token overflows.
1120 //
1121 // If the token on its own is wider than what fits on a
1122 // continuation line (width - contW), it'll need to be split
1123 // rune-by-rune no matter what. In that case, don't break
1124 // first: let the rune-split start right here at the current
1125 // column and wrap naturally. Breaking first would strand the
1126 // prompt (on firstLine) or the cont indent (on later lines)
1127 // on a row by itself, which is the drag-drop-long-path bug.
1128 if tk.width > width-contW {
1129 // Rune-by-rune starting from the current column. newLine()
1130 // inside handles wrapping and re-indents.
1131 for _, r := range tk.text {
1132 rw := runewidth.RuneWidth(r)
1133 if curW+rw > width {
1134 newLine()
1135 }
1136 cur.WriteRune(r)
1137 curW += rw
1138 }
1139 continue
1140 }
1141
1142 // Token fits on a fresh continuation line; break first, then
1143 // emit it whole.
1144 if cur.Len() > 0 && !(firstLine && curW == 0) {
1145 trimmed := strings.TrimRight(cur.String(), " \t")
1146 cur.Reset()
1147 cur.WriteString(trimmed)
1148 curW = visibleWidth(trimmed)
1149 newLine()
1150 if tk.space {
1151 continue
1152 }
1153 }
1154 cur.WriteString(tk.text)
1155 curW += tk.width
1156 }
1157
1158 if cur.Len() > 0 || len(out) == 0 {
1159 out = append(out, cur.String())
1160 }
1161 return out
1162}
1163
1164func max(a, b int) int {
1165 if a > b {
1166 return a
1167 }
1168 return b
1169}
1170
1171// pasteCollapseLineThreshold and pasteCollapseCharThreshold govern
1172// when a bracketed paste gets collapsed to a [pasted text #N ...]
1173// placeholder instead of being inserted inline. Either trigger
1174// alone is enough — a 500-line log dump and a 1200-character
1175// one-line log entry both bloat the editor in ways the user
1176// doesn't want to scroll through while composing a prompt.
1177const (
1178 pasteCollapseLineThreshold = 10
1179 pasteCollapseCharThreshold = 1000
1180)
1181
1182// pasteShouldCollapse reports whether a pasted chunk is big enough
1183// to deserve a placeholder token instead of being inserted verbatim.
1184// Collapse on > 10 lines OR > 1000 characters, whichever fires
1185// first.
1186func pasteShouldCollapse(s string) bool {
1187 return countLines(s) > pasteCollapseLineThreshold || len(s) > pasteCollapseCharThreshold
1188}
1189
1190// formatPastePlaceholder builds the visible marker for a
1191// collapsed paste. Two shapes:
1192//
1193// [pasted text #N +L lines] — used when the line count is the
1194// trigger (multi-line dumps)
1195// [pasted text #N C chars] — used when the character count is
1196// the trigger (long single-line
1197// or near-single-line pastes)
1198//
1199// Line-triggered takes precedence so a 12-line 4000-char paste
1200// reads as "+12 lines", not "4000 chars".
1201func formatPastePlaceholder(id int, body string) string {
1202 if countLines(body) > pasteCollapseLineThreshold {
1203 return fmt.Sprintf("[pasted text #%d +%d lines]", id, countLines(body))
1204 }
1205 return fmt.Sprintf("[pasted text #%d %d chars]", id, len(body))
1206}
1207
1208// countLines returns the number of visual lines in s. A trailing
1209// newline is not counted as an extra empty line so
1210// "foo\nbar\n" reads as 2 lines (what the user expects in the
1211// "+N lines" summary) instead of 3.
1212func countLines(s string) int {
1213 if s == "" {
1214 return 0
1215 }
1216 n := strings.Count(s, "\n")
1217 if !strings.HasSuffix(s, "\n") {
1218 n++
1219 }
1220 return n
1221}
1222
1223// pastePlaceholderRE matches both placeholder shapes the editor
1224// emits for a collapsed paste:
1225//
1226// [pasted text #N +L lines] — multi-line trigger
1227// [pasted text #N C chars] — long-char trigger
1228//
1229// Capture group 1 is the numeric id used to look up the full
1230// body in e.pastes; the rest of the token is free-form and gets
1231// discarded during expansion.
1232var pastePlaceholderRE = regexp.MustCompile(`\[pasted text #(\d+) (?:\+\d+ lines?|\d+ chars?)\]`)
1233var filePlaceholderRE = regexp.MustCompile(`\[(file|dir):(\d+):[^\]]+\]`)
1234
1235// expandPastePlaceholders returns raw with every paste token
1236// swapped for the body stored under its id in pastes. Tokens
1237// whose id isn't in the map are left as-is (user deleted the
1238// corresponding entry somehow, or the id is spurious user text
1239// that happens to match the shape).
1240func expandPastePlaceholders(raw string, pastes map[int]string) string {
1241 return pastePlaceholderRE.ReplaceAllStringFunc(raw, func(match string) string {
1242 groups := pastePlaceholderRE.FindStringSubmatch(match)
1243 if len(groups) < 2 {
1244 return match
1245 }
1246 var id int
1247 if _, err := fmt.Sscanf(groups[1], "%d", &id); err != nil {
1248 return match
1249 }
1250 if body, ok := pastes[id]; ok {
1251 return body
1252 }
1253 return match
1254 })
1255}
1256
1257// expandFilePlaceholders returns raw with every [file:N:name] and
1258// [dir:N:name/] token swapped for the full path stored under its id.
1259func expandFilePlaceholders(raw string, files, dirs map[int]string) string {
1260 return filePlaceholderRE.ReplaceAllStringFunc(raw, func(match string) string {
1261 groups := filePlaceholderRE.FindStringSubmatch(match)
1262 if len(groups) < 3 {
1263 return match
1264 }
1265 kind := groups[1] // "file" or "dir"
1266 var id int
1267 if _, err := fmt.Sscanf(groups[2], "%d", &id); err != nil {
1268 return match
1269 }
1270 var m map[int]string
1271 if kind == "dir" {
1272 m = dirs
1273 } else {
1274 m = files
1275 }
1276 if path, ok := m[id]; ok {
1277 return path
1278 }
1279 return match
1280 })
1281}
1282
1283// collapseOrQuoteFilePaths checks if the paste is a file path and
1284// collapses it to a [file:basename] chip. URLs are left as-is.
1285// Non-path pastes fall through to quotePastedFilePaths.
1286func (e *Editor) collapseOrQuoteFilePaths(paste string) string {
1287 if paste == "" || strings.ContainsRune(paste, '\n') {
1288 return quotePastedFilePaths(paste)
1289 }
1290 trimmed := strings.TrimSpace(paste)
1291 // Don't collapse URLs.
1292 if strings.HasPrefix(trimmed, "http://") || strings.HasPrefix(trimmed, "https://") {
1293 return paste
1294 }
1295 // Check if it's a single file path.
1296 p, ok := normalisePathToken(trimmed)
1297 if !ok {
1298 return quotePastedFilePaths(paste)
1299 }
1300 // Only collapse if the path is long enough to benefit.
1301 base := filepath.Base(p)
1302 if len(p) <= len(base)+5 {
1303 // Short path like "./foo.txt" - just quote it.
1304 return singleQuote(p)
1305 }
1306 // Check if it's a directory.
1307 info, err := os.Stat(p)
1308 if err == nil && info.IsDir() {
1309 if e.dirs == nil {
1310 e.dirs = map[int]string{}
1311 }
1312 e.dirSeq++
1313 e.dirs[e.dirSeq] = singleQuote(p)
1314 return fmt.Sprintf("[dir:%d:%s/]", e.dirSeq, base)
1315 }
1316 if e.files == nil {
1317 e.files = map[int]string{}
1318 }
1319 e.fileSeq++
1320 e.files[e.fileSeq] = singleQuote(p)
1321 return fmt.Sprintf("[file:%d:%s]", e.fileSeq, base)
1322}