editor.ts 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285
  1. import type { AutocompleteProvider, AutocompleteSuggestions } from "../autocomplete.ts";
  2. import { getKeybindings } from "../keybindings.ts";
  3. import { decodePrintableKey, matchesKey } from "../keys.ts";
  4. import { KillRing } from "../kill-ring.ts";
  5. import { type Component, CURSOR_MARKER, type Focusable, type TUI } from "../tui.ts";
  6. import { UndoStack } from "../undo-stack.ts";
  7. import { getGraphemeSegmenter, getWordSegmenter, isWhitespaceChar, truncateToWidth, visibleWidth } from "../utils.ts";
  8. import { findWordBackward, findWordForward } from "../word-navigation.ts";
  9. import { SelectList, type SelectListLayoutOptions, type SelectListTheme } from "./select-list.ts";
  10. const graphemeSegmenter = getGraphemeSegmenter();
  11. const wordSegmenter = getWordSegmenter();
  12. /** Regex matching paste markers like `[paste #1 +123 lines]` or `[paste #2 1234 chars]`. */
  13. const PASTE_MARKER_REGEX = /\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g;
  14. /** Non-global version for single-segment testing. */
  15. const PASTE_MARKER_SINGLE = /^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;
  16. /** Check if a segment is a paste marker (i.e. was merged by segmentWithMarkers). */
  17. function isPasteMarker(segment: string): boolean {
  18. return segment.length >= 10 && PASTE_MARKER_SINGLE.test(segment);
  19. }
  20. /**
  21. * A segmenter that wraps Intl.Segmenter and merges graphemes that fall
  22. * within paste markers into single atomic segments. This makes cursor
  23. * movement, deletion, word-wrap, etc. treat paste markers as single units.
  24. *
  25. * Only markers whose numeric ID exists in `validIds` are merged.
  26. */
  27. function segmentWithMarkers(
  28. text: string,
  29. baseSegmenter: Intl.Segmenter,
  30. validIds: Set<number>,
  31. ): Iterable<Intl.SegmentData> {
  32. // Fast path: no paste markers in the text or no valid IDs.
  33. if (validIds.size === 0 || !text.includes("[paste #")) {
  34. return baseSegmenter.segment(text);
  35. }
  36. // Find all marker spans with valid IDs.
  37. const markers: Array<{ start: number; end: number }> = [];
  38. for (const m of text.matchAll(PASTE_MARKER_REGEX)) {
  39. const id = Number.parseInt(m[1]!, 10);
  40. if (!validIds.has(id)) continue;
  41. markers.push({ start: m.index, end: m.index + m[0].length });
  42. }
  43. if (markers.length === 0) {
  44. return baseSegmenter.segment(text);
  45. }
  46. // Build merged segment list.
  47. const baseSegments = baseSegmenter.segment(text);
  48. const result: Intl.SegmentData[] = [];
  49. let markerIdx = 0;
  50. for (const seg of baseSegments) {
  51. // Skip past markers that are entirely before this segment.
  52. while (markerIdx < markers.length && markers[markerIdx]!.end <= seg.index) {
  53. markerIdx++;
  54. }
  55. const marker = markerIdx < markers.length ? markers[markerIdx]! : null;
  56. if (marker && seg.index >= marker.start && seg.index < marker.end) {
  57. // This segment falls inside a marker.
  58. // If this is the first segment of the marker, emit a merged segment.
  59. if (seg.index === marker.start) {
  60. const markerText = text.slice(marker.start, marker.end);
  61. result.push({
  62. segment: markerText,
  63. index: marker.start,
  64. input: text,
  65. });
  66. }
  67. // Otherwise skip (already merged into the first segment).
  68. } else {
  69. result.push(seg);
  70. }
  71. }
  72. return result;
  73. }
  74. /**
  75. * Represents a chunk of text for word-wrap layout.
  76. * Tracks both the text content and its position in the original line.
  77. */
  78. export interface TextChunk {
  79. text: string;
  80. startIndex: number;
  81. endIndex: number;
  82. }
  83. /**
  84. * Split a line into word-wrapped chunks.
  85. * Wraps at word boundaries when possible, falling back to character-level
  86. * wrapping for words longer than the available width.
  87. *
  88. * @param line - The text line to wrap
  89. * @param maxWidth - Maximum visible width per chunk
  90. * @param preSegmented - Optional pre-segmented graphemes (e.g. with paste-marker awareness).
  91. * When omitted the default Intl.Segmenter is used.
  92. * @returns Array of chunks with text and position information
  93. */
  94. export function wordWrapLine(line: string, maxWidth: number, preSegmented?: Intl.SegmentData[]): TextChunk[] {
  95. if (!line || maxWidth <= 0) {
  96. return [{ text: "", startIndex: 0, endIndex: 0 }];
  97. }
  98. const lineWidth = visibleWidth(line);
  99. if (lineWidth <= maxWidth) {
  100. return [{ text: line, startIndex: 0, endIndex: line.length }];
  101. }
  102. const chunks: TextChunk[] = [];
  103. const segments = preSegmented ?? [...graphemeSegmenter.segment(line)];
  104. let currentWidth = 0;
  105. let chunkStart = 0;
  106. // Wrap opportunity: the position after the last whitespace before a non-whitespace
  107. // grapheme, i.e. where a line break is allowed.
  108. let wrapOppIndex = -1;
  109. let wrapOppWidth = 0;
  110. for (let i = 0; i < segments.length; i++) {
  111. const seg = segments[i]!;
  112. const grapheme = seg.segment;
  113. const gWidth = visibleWidth(grapheme);
  114. const charIndex = seg.index;
  115. const isWs = !isPasteMarker(grapheme) && isWhitespaceChar(grapheme);
  116. // Overflow check before advancing.
  117. if (currentWidth + gWidth > maxWidth) {
  118. if (wrapOppIndex >= 0 && currentWidth - wrapOppWidth + gWidth <= maxWidth) {
  119. // Backtrack to last wrap opportunity (the remaining content
  120. // plus the current grapheme still fits within maxWidth).
  121. chunks.push({ text: line.slice(chunkStart, wrapOppIndex), startIndex: chunkStart, endIndex: wrapOppIndex });
  122. chunkStart = wrapOppIndex;
  123. currentWidth -= wrapOppWidth;
  124. } else if (chunkStart < charIndex) {
  125. // No viable wrap opportunity: force-break at current position.
  126. // This also handles the case where backtracking to a word
  127. // boundary wouldn't help because the remaining content plus
  128. // the current grapheme (e.g. a wide character) still exceeds
  129. // maxWidth.
  130. chunks.push({ text: line.slice(chunkStart, charIndex), startIndex: chunkStart, endIndex: charIndex });
  131. chunkStart = charIndex;
  132. currentWidth = 0;
  133. }
  134. wrapOppIndex = -1;
  135. }
  136. if (gWidth > maxWidth) {
  137. // Single atomic segment wider than maxWidth (e.g. paste marker
  138. // in a narrow terminal). Re-wrap it at grapheme granularity.
  139. // The segment remains logically atomic for cursor
  140. // movement / editing — the split is purely visual for word-wrap layout.
  141. const subChunks = wordWrapLine(grapheme, maxWidth);
  142. for (let j = 0; j < subChunks.length - 1; j++) {
  143. const sc = subChunks[j]!;
  144. chunks.push({ text: sc.text, startIndex: charIndex + sc.startIndex, endIndex: charIndex + sc.endIndex });
  145. }
  146. const last = subChunks[subChunks.length - 1]!;
  147. chunkStart = charIndex + last.startIndex;
  148. currentWidth = visibleWidth(last.text);
  149. wrapOppIndex = -1;
  150. continue;
  151. }
  152. // Advance.
  153. currentWidth += gWidth;
  154. // Record wrap opportunity: whitespace followed by non-whitespace.
  155. // Multiple spaces join (no break between them); the break point is
  156. // after the last space before the next word.
  157. const next = segments[i + 1];
  158. if (isWs && next && (isPasteMarker(next.segment) || !isWhitespaceChar(next.segment))) {
  159. wrapOppIndex = next.index;
  160. wrapOppWidth = currentWidth;
  161. }
  162. }
  163. // Push final chunk.
  164. chunks.push({ text: line.slice(chunkStart), startIndex: chunkStart, endIndex: line.length });
  165. return chunks;
  166. }
  167. // Kitty CSI-u sequences for printable keys, including optional shifted/base codepoints.
  168. interface EditorState {
  169. lines: string[];
  170. cursorLine: number;
  171. cursorCol: number;
  172. }
  173. interface LayoutLine {
  174. text: string;
  175. hasCursor: boolean;
  176. cursorPos?: number;
  177. }
  178. export interface EditorTheme {
  179. borderColor: (str: string) => string;
  180. selectList: SelectListTheme;
  181. }
  182. export interface EditorOptions {
  183. paddingX?: number;
  184. autocompleteMaxVisible?: number;
  185. }
  186. const SLASH_COMMAND_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {
  187. minPrimaryColumnWidth: 12,
  188. maxPrimaryColumnWidth: 32,
  189. };
  190. const ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS = 20;
  191. const DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS = ["@", "#"];
  192. function escapeCharacterClass(value: string): string {
  193. return value.replace(/[\\^$.*+?()[\]{}|-]/g, "\\$&");
  194. }
  195. function buildTriggerPattern(triggerCharacters: string[]): RegExp {
  196. return new RegExp(`(?:^|[\\s])[${triggerCharacters.map(escapeCharacterClass).join("")}][^\\s]*$`);
  197. }
  198. function buildDebouncePattern(triggerCharacters: string[]): RegExp {
  199. const escapedWithoutAt = triggerCharacters.filter((character) => character !== "@").map(escapeCharacterClass);
  200. return new RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${escapedWithoutAt.join("")}][^\\s]*)$`);
  201. }
  202. export class Editor implements Component, Focusable {
  203. private state: EditorState = {
  204. lines: [""],
  205. cursorLine: 0,
  206. cursorCol: 0,
  207. };
  208. /** Focusable interface - set by TUI when focus changes */
  209. focused: boolean = false;
  210. protected tui: TUI;
  211. private theme: EditorTheme;
  212. private paddingX: number = 0;
  213. // Store last render width for cursor navigation
  214. private lastWidth: number = 80;
  215. // Vertical scrolling support
  216. private scrollOffset: number = 0;
  217. // Border color (can be changed dynamically)
  218. public borderColor: (str: string) => string;
  219. // Autocomplete support
  220. private autocompleteProvider?: AutocompleteProvider;
  221. private autocompleteTriggerCharacters = [...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];
  222. private autocompleteTriggerPattern = buildTriggerPattern(this.autocompleteTriggerCharacters);
  223. private autocompleteDebouncePattern = buildDebouncePattern(this.autocompleteTriggerCharacters);
  224. private autocompleteList?: SelectList;
  225. private autocompleteState: "regular" | "force" | null = null;
  226. private autocompletePrefix: string = "";
  227. private autocompleteMaxVisible: number = 5;
  228. private autocompleteAbort?: AbortController;
  229. private autocompleteDebounceTimer?: ReturnType<typeof setTimeout>;
  230. private autocompleteRequestTask: Promise<void> = Promise.resolve();
  231. private autocompleteStartToken: number = 0;
  232. private autocompleteRequestId: number = 0;
  233. // Paste tracking for large pastes
  234. private pastes: Map<number, string> = new Map();
  235. private pasteCounter: number = 0;
  236. // Bracketed paste mode buffering
  237. private pasteBuffer: string = "";
  238. private isInPaste: boolean = false;
  239. // Prompt history for up/down navigation
  240. private history: string[] = [];
  241. private historyIndex: number = -1; // -1 = not browsing, 0 = most recent, 1 = older, etc.
  242. private historyDraft: EditorState | null = null;
  243. // Kill ring for Emacs-style kill/yank operations
  244. private killRing = new KillRing();
  245. private lastAction: "kill" | "yank" | "type-word" | null = null;
  246. // Character jump mode
  247. private jumpMode: "forward" | "backward" | null = null;
  248. // Preferred visual column for vertical cursor movement (sticky column)
  249. private preferredVisualCol: number | null = null;
  250. // When the cursor is snapped to the start of an atomic segment, e.g. a
  251. // paste marker, cursorCol no longer reflects where the cursor would have
  252. // landed. This field stores the pre-snap cursorCol so that the next
  253. // vertical move can resolve it to a visual column on whatever VL it belongs
  254. // to.
  255. private snappedFromCursorCol: number | null = null;
  256. // Undo support
  257. private undoStack = new UndoStack<EditorState>();
  258. public onSubmit?: (text: string) => void;
  259. public onChange?: (text: string) => void;
  260. public disableSubmit: boolean = false;
  261. constructor(tui: TUI, theme: EditorTheme, options: EditorOptions = {}) {
  262. this.tui = tui;
  263. this.theme = theme;
  264. this.borderColor = theme.borderColor;
  265. const paddingX = options.paddingX ?? 0;
  266. this.paddingX = Number.isFinite(paddingX) ? Math.max(0, Math.floor(paddingX)) : 0;
  267. const maxVisible = options.autocompleteMaxVisible ?? 5;
  268. this.autocompleteMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
  269. }
  270. /** Set of currently valid paste IDs, for marker-aware segmentation. */
  271. private validPasteIds(): Set<number> {
  272. return new Set(this.pastes.keys());
  273. }
  274. /** Segment text with paste-marker awareness, only merging markers with valid IDs. */
  275. private segment(text: string, mode: "word" | "grapheme"): Iterable<Intl.SegmentData> {
  276. return segmentWithMarkers(text, mode === "word" ? wordSegmenter : graphemeSegmenter, this.validPasteIds());
  277. }
  278. getPaddingX(): number {
  279. return this.paddingX;
  280. }
  281. setPaddingX(padding: number): void {
  282. const newPadding = Number.isFinite(padding) ? Math.max(0, Math.floor(padding)) : 0;
  283. if (this.paddingX !== newPadding) {
  284. this.paddingX = newPadding;
  285. this.tui.requestRender();
  286. }
  287. }
  288. getAutocompleteMaxVisible(): number {
  289. return this.autocompleteMaxVisible;
  290. }
  291. setAutocompleteMaxVisible(maxVisible: number): void {
  292. const newMaxVisible = Number.isFinite(maxVisible) ? Math.max(3, Math.min(20, Math.floor(maxVisible))) : 5;
  293. if (this.autocompleteMaxVisible !== newMaxVisible) {
  294. this.autocompleteMaxVisible = newMaxVisible;
  295. this.tui.requestRender();
  296. }
  297. }
  298. setAutocompleteProvider(provider: AutocompleteProvider): void {
  299. this.cancelAutocomplete();
  300. this.autocompleteProvider = provider;
  301. this.setAutocompleteTriggerCharacters(provider.triggerCharacters ?? []);
  302. }
  303. /**
  304. * Add a prompt to history for up/down arrow navigation.
  305. * Called after successful submission.
  306. */
  307. addToHistory(text: string): void {
  308. const trimmed = text.trim();
  309. if (!trimmed) return;
  310. // Don't add consecutive duplicates
  311. if (this.history.length > 0 && this.history[0] === trimmed) return;
  312. this.history.unshift(trimmed);
  313. // Limit history size
  314. if (this.history.length > 100) {
  315. this.history.pop();
  316. }
  317. }
  318. private isOnFirstVisualLine(): boolean {
  319. const visualLines = this.buildVisualLineMap(this.lastWidth);
  320. const currentVisualLine = this.findCurrentVisualLine(visualLines);
  321. return currentVisualLine === 0;
  322. }
  323. private isOnLastVisualLine(): boolean {
  324. const visualLines = this.buildVisualLineMap(this.lastWidth);
  325. const currentVisualLine = this.findCurrentVisualLine(visualLines);
  326. return currentVisualLine === visualLines.length - 1;
  327. }
  328. private navigateHistory(direction: 1 | -1): void {
  329. this.lastAction = null;
  330. if (this.history.length === 0) return;
  331. const newIndex = this.historyIndex - direction; // Up(-1) increases index, Down(1) decreases
  332. if (newIndex < -1 || newIndex >= this.history.length) return;
  333. // Capture state when first entering history browsing mode
  334. if (this.historyIndex === -1 && newIndex >= 0) {
  335. this.pushUndoSnapshot();
  336. this.historyDraft = structuredClone(this.state);
  337. }
  338. this.historyIndex = newIndex;
  339. if (this.historyIndex === -1) {
  340. const draft = this.historyDraft;
  341. this.historyDraft = null;
  342. if (draft) {
  343. this.state = draft;
  344. this.preferredVisualCol = null;
  345. this.snappedFromCursorCol = null;
  346. this.scrollOffset = 0;
  347. if (this.onChange) this.onChange(this.getText());
  348. } else {
  349. this.setTextInternal("");
  350. }
  351. } else {
  352. this.setTextInternal(this.history[this.historyIndex] || "", direction === -1 ? "start" : "end");
  353. }
  354. }
  355. private exitHistoryBrowsing(): void {
  356. this.historyIndex = -1;
  357. this.historyDraft = null;
  358. }
  359. /** Internal setText that doesn't reset history state - used by navigateHistory */
  360. private setTextInternal(text: string, cursorPlacement: "start" | "end" = "end"): void {
  361. const lines = text.split("\n");
  362. this.state.lines = lines.length === 0 ? [""] : lines;
  363. this.state.cursorLine = cursorPlacement === "start" ? 0 : this.state.lines.length - 1;
  364. this.setCursorCol(cursorPlacement === "start" ? 0 : this.state.lines[this.state.cursorLine]?.length || 0);
  365. // Reset scroll - render() will adjust to show cursor
  366. this.scrollOffset = 0;
  367. if (this.onChange) {
  368. this.onChange(this.getText());
  369. }
  370. }
  371. invalidate(): void {
  372. // No cached state to invalidate currently
  373. }
  374. render(width: number): string[] {
  375. const maxPadding = Math.max(0, Math.floor((width - 1) / 2));
  376. const paddingX = Math.min(this.paddingX, maxPadding);
  377. const contentWidth = Math.max(1, width - paddingX * 2);
  378. // Layout width: with padding the cursor can overflow into it,
  379. // without padding we reserve 1 column for the cursor.
  380. const layoutWidth = Math.max(1, contentWidth - (paddingX ? 0 : 1));
  381. // Store for cursor navigation (must match wrapping width)
  382. this.lastWidth = layoutWidth;
  383. const horizontal = this.borderColor("─");
  384. // Layout the text
  385. const layoutLines = this.layoutText(layoutWidth);
  386. // Calculate max visible lines: 30% of terminal height, minimum 5 lines
  387. const terminalRows = this.tui.terminal.rows;
  388. const maxVisibleLines = Math.max(5, Math.floor(terminalRows * 0.3));
  389. // Find the cursor line index in layoutLines
  390. let cursorLineIndex = layoutLines.findIndex((line) => line.hasCursor);
  391. if (cursorLineIndex === -1) cursorLineIndex = 0;
  392. // Adjust scroll offset to keep cursor visible
  393. if (cursorLineIndex < this.scrollOffset) {
  394. this.scrollOffset = cursorLineIndex;
  395. } else if (cursorLineIndex >= this.scrollOffset + maxVisibleLines) {
  396. this.scrollOffset = cursorLineIndex - maxVisibleLines + 1;
  397. }
  398. // Clamp scroll offset to valid range
  399. const maxScrollOffset = Math.max(0, layoutLines.length - maxVisibleLines);
  400. this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScrollOffset));
  401. // Get visible lines slice
  402. const visibleLines = layoutLines.slice(this.scrollOffset, this.scrollOffset + maxVisibleLines);
  403. const result: string[] = [];
  404. const leftPadding = " ".repeat(paddingX);
  405. const rightPadding = leftPadding;
  406. // Render top border (with scroll indicator if scrolled down)
  407. if (this.scrollOffset > 0) {
  408. const indicator = `─── ↑ ${this.scrollOffset} more `;
  409. const remaining = width - visibleWidth(indicator);
  410. if (remaining >= 0) {
  411. result.push(this.borderColor(indicator + "─".repeat(remaining)));
  412. } else {
  413. result.push(this.borderColor(truncateToWidth(indicator, width)));
  414. }
  415. } else {
  416. result.push(horizontal.repeat(width));
  417. }
  418. // Render each visible layout line
  419. // Emit hardware cursor marker when focused so TUI can position the
  420. // hardware cursor for IME candidate-window placement even while
  421. // autocomplete (e.g. slash-command menu) is visible.
  422. const emitCursorMarker = this.focused;
  423. for (const layoutLine of visibleLines) {
  424. let displayText = layoutLine.text;
  425. let lineVisibleWidth = visibleWidth(layoutLine.text);
  426. let cursorInPadding = false;
  427. // Add cursor if this line has it
  428. if (layoutLine.hasCursor && layoutLine.cursorPos !== undefined) {
  429. const before = displayText.slice(0, layoutLine.cursorPos);
  430. const after = displayText.slice(layoutLine.cursorPos);
  431. // Hardware cursor marker (zero-width, emitted before fake cursor for IME positioning)
  432. const marker = emitCursorMarker ? CURSOR_MARKER : "";
  433. if (after.length > 0) {
  434. // Cursor is on a character (grapheme) - replace it with highlighted version
  435. // Get the first grapheme from 'after'
  436. const afterGraphemes = [...this.segment(after, "grapheme")];
  437. const firstGrapheme = afterGraphemes[0]?.segment || "";
  438. const restAfter = after.slice(firstGrapheme.length);
  439. const cursor = `\x1b[7m${firstGrapheme}\x1b[0m`;
  440. displayText = before + marker + cursor + restAfter;
  441. // lineVisibleWidth stays the same - we're replacing, not adding
  442. } else {
  443. // Cursor is at the end - add highlighted space
  444. const cursor = "\x1b[7m \x1b[0m";
  445. displayText = before + marker + cursor;
  446. lineVisibleWidth = lineVisibleWidth + 1;
  447. // If cursor overflows content width into the padding, flag it
  448. if (lineVisibleWidth > contentWidth && paddingX > 0) {
  449. cursorInPadding = true;
  450. }
  451. }
  452. }
  453. // Calculate padding based on actual visible width
  454. const padding = " ".repeat(Math.max(0, contentWidth - lineVisibleWidth));
  455. const lineRightPadding = cursorInPadding ? rightPadding.slice(1) : rightPadding;
  456. // Render the line (no side borders, just horizontal lines above and below)
  457. result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`);
  458. }
  459. // Render bottom border (with scroll indicator if more content below)
  460. const linesBelow = layoutLines.length - (this.scrollOffset + visibleLines.length);
  461. if (linesBelow > 0) {
  462. const indicator = `─── ↓ ${linesBelow} more `;
  463. const remaining = width - visibleWidth(indicator);
  464. result.push(this.borderColor(indicator + "─".repeat(Math.max(0, remaining))));
  465. } else {
  466. result.push(horizontal.repeat(width));
  467. }
  468. // Add autocomplete list if active
  469. if (this.autocompleteState && this.autocompleteList) {
  470. const autocompleteResult = this.autocompleteList.render(contentWidth);
  471. for (const line of autocompleteResult) {
  472. const lineWidth = visibleWidth(line);
  473. const linePadding = " ".repeat(Math.max(0, contentWidth - lineWidth));
  474. result.push(`${leftPadding}${line}${linePadding}${rightPadding}`);
  475. }
  476. }
  477. return result;
  478. }
  479. handleInput(data: string): void {
  480. const kb = getKeybindings();
  481. // Handle character jump mode (awaiting next character to jump to)
  482. if (this.jumpMode !== null) {
  483. // Cancel if the hotkey is pressed again
  484. if (kb.matches(data, "tui.editor.jumpForward") || kb.matches(data, "tui.editor.jumpBackward")) {
  485. this.jumpMode = null;
  486. return;
  487. }
  488. const printable = decodePrintableKey(data) ?? (data.charCodeAt(0) >= 32 ? data : undefined);
  489. if (printable !== undefined) {
  490. // Printable character - perform the jump
  491. const direction = this.jumpMode;
  492. this.jumpMode = null;
  493. this.jumpToChar(printable, direction);
  494. return;
  495. }
  496. // Control character - cancel and fall through to normal handling
  497. this.jumpMode = null;
  498. }
  499. // Handle bracketed paste mode
  500. if (data.includes("\x1b[200~")) {
  501. this.isInPaste = true;
  502. this.pasteBuffer = "";
  503. data = data.replace("\x1b[200~", "");
  504. }
  505. if (this.isInPaste) {
  506. this.pasteBuffer += data;
  507. const endIndex = this.pasteBuffer.indexOf("\x1b[201~");
  508. if (endIndex !== -1) {
  509. const pasteContent = this.pasteBuffer.substring(0, endIndex);
  510. if (pasteContent.length > 0) {
  511. this.handlePaste(pasteContent);
  512. }
  513. this.isInPaste = false;
  514. const remaining = this.pasteBuffer.substring(endIndex + 6);
  515. this.pasteBuffer = "";
  516. if (remaining.length > 0) {
  517. this.handleInput(remaining);
  518. }
  519. return;
  520. }
  521. return;
  522. }
  523. // Ctrl+C - let parent handle (exit/clear)
  524. if (kb.matches(data, "tui.input.copy")) {
  525. return;
  526. }
  527. // Undo
  528. if (kb.matches(data, "tui.editor.undo")) {
  529. this.undo();
  530. return;
  531. }
  532. // Handle autocomplete mode
  533. if (this.autocompleteState && this.autocompleteList) {
  534. if (kb.matches(data, "tui.select.cancel")) {
  535. this.cancelAutocomplete();
  536. return;
  537. }
  538. if (kb.matches(data, "tui.select.up") || kb.matches(data, "tui.select.down")) {
  539. this.autocompleteList.handleInput(data);
  540. return;
  541. }
  542. if (kb.matches(data, "tui.input.tab")) {
  543. const selected = this.autocompleteList.getSelectedItem();
  544. if (selected && this.autocompleteProvider) {
  545. this.pushUndoSnapshot();
  546. this.lastAction = null;
  547. const result = this.autocompleteProvider.applyCompletion(
  548. this.state.lines,
  549. this.state.cursorLine,
  550. this.state.cursorCol,
  551. selected,
  552. this.autocompletePrefix,
  553. );
  554. this.state.lines = result.lines;
  555. this.state.cursorLine = result.cursorLine;
  556. this.setCursorCol(result.cursorCol);
  557. this.cancelAutocomplete();
  558. if (this.onChange) this.onChange(this.getText());
  559. }
  560. return;
  561. }
  562. if (kb.matches(data, "tui.select.confirm")) {
  563. const selected = this.autocompleteList.getSelectedItem();
  564. if (selected && this.autocompleteProvider) {
  565. this.pushUndoSnapshot();
  566. this.lastAction = null;
  567. const result = this.autocompleteProvider.applyCompletion(
  568. this.state.lines,
  569. this.state.cursorLine,
  570. this.state.cursorCol,
  571. selected,
  572. this.autocompletePrefix,
  573. );
  574. this.state.lines = result.lines;
  575. this.state.cursorLine = result.cursorLine;
  576. this.setCursorCol(result.cursorCol);
  577. if (this.autocompletePrefix.startsWith("/")) {
  578. this.cancelAutocomplete();
  579. // Fall through to submit
  580. } else {
  581. this.cancelAutocomplete();
  582. if (this.onChange) this.onChange(this.getText());
  583. return;
  584. }
  585. }
  586. }
  587. }
  588. // Tab - trigger completion
  589. if (kb.matches(data, "tui.input.tab") && !this.autocompleteState) {
  590. this.handleTabCompletion();
  591. return;
  592. }
  593. // Deletion actions
  594. if (kb.matches(data, "tui.editor.deleteToLineEnd")) {
  595. this.deleteToEndOfLine();
  596. return;
  597. }
  598. if (kb.matches(data, "tui.editor.deleteToLineStart")) {
  599. this.deleteToStartOfLine();
  600. return;
  601. }
  602. if (kb.matches(data, "tui.editor.deleteWordBackward")) {
  603. this.deleteWordBackwards();
  604. return;
  605. }
  606. if (kb.matches(data, "tui.editor.deleteWordForward")) {
  607. this.deleteWordForward();
  608. return;
  609. }
  610. if (kb.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, "shift+backspace")) {
  611. this.handleBackspace();
  612. return;
  613. }
  614. if (kb.matches(data, "tui.editor.deleteCharForward") || matchesKey(data, "shift+delete")) {
  615. this.handleForwardDelete();
  616. return;
  617. }
  618. // Kill ring actions
  619. if (kb.matches(data, "tui.editor.yank")) {
  620. this.yank();
  621. return;
  622. }
  623. if (kb.matches(data, "tui.editor.yankPop")) {
  624. this.yankPop();
  625. return;
  626. }
  627. // Cursor movement actions
  628. if (kb.matches(data, "tui.editor.cursorLineStart")) {
  629. this.moveToLineStart();
  630. return;
  631. }
  632. if (kb.matches(data, "tui.editor.cursorLineEnd")) {
  633. this.moveToLineEnd();
  634. return;
  635. }
  636. if (kb.matches(data, "tui.editor.cursorWordLeft")) {
  637. this.moveWordBackwards();
  638. return;
  639. }
  640. if (kb.matches(data, "tui.editor.cursorWordRight")) {
  641. this.moveWordForwards();
  642. return;
  643. }
  644. // New line
  645. if (
  646. kb.matches(data, "tui.input.newLine") ||
  647. (data.charCodeAt(0) === 10 && data.length > 1) ||
  648. data === "\x1b\r" ||
  649. data === "\x1b[13;2~" ||
  650. (data.length > 1 && data.includes("\x1b") && data.includes("\r")) ||
  651. (data === "\n" && data.length === 1)
  652. ) {
  653. if (this.shouldSubmitOnBackslashEnter(data, kb)) {
  654. this.handleBackspace();
  655. this.submitValue();
  656. return;
  657. }
  658. this.addNewLine();
  659. return;
  660. }
  661. // Submit (Enter)
  662. if (kb.matches(data, "tui.input.submit")) {
  663. if (this.disableSubmit) return;
  664. // Workaround for terminals without Shift+Enter support:
  665. // If char before cursor is \, delete it and insert newline instead of submitting.
  666. const currentLine = this.state.lines[this.state.cursorLine] || "";
  667. if (this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\") {
  668. this.handleBackspace();
  669. this.addNewLine();
  670. return;
  671. }
  672. this.submitValue();
  673. return;
  674. }
  675. // Arrow key navigation (with history support)
  676. if (kb.matches(data, "tui.editor.cursorUp")) {
  677. if (this.isOnFirstVisualLine() && this.history.length > 0) {
  678. this.navigateHistory(-1);
  679. } else if (this.isOnFirstVisualLine()) {
  680. // Already at top - jump to start of line
  681. this.moveToLineStart();
  682. } else {
  683. this.moveCursor(-1, 0);
  684. }
  685. return;
  686. }
  687. if (kb.matches(data, "tui.editor.cursorDown")) {
  688. if (this.historyIndex > -1 && this.isOnLastVisualLine()) {
  689. this.navigateHistory(1);
  690. } else if (this.isOnLastVisualLine()) {
  691. // Already at bottom - jump to end of line
  692. this.moveToLineEnd();
  693. } else {
  694. this.moveCursor(1, 0);
  695. }
  696. return;
  697. }
  698. if (kb.matches(data, "tui.editor.cursorRight")) {
  699. this.moveCursor(0, 1);
  700. return;
  701. }
  702. if (kb.matches(data, "tui.editor.cursorLeft")) {
  703. this.moveCursor(0, -1);
  704. return;
  705. }
  706. // Page up/down - scroll by page and move cursor
  707. if (kb.matches(data, "tui.editor.pageUp")) {
  708. this.pageScroll(-1);
  709. return;
  710. }
  711. if (kb.matches(data, "tui.editor.pageDown")) {
  712. this.pageScroll(1);
  713. return;
  714. }
  715. // Character jump mode triggers
  716. if (kb.matches(data, "tui.editor.jumpForward")) {
  717. this.jumpMode = "forward";
  718. return;
  719. }
  720. if (kb.matches(data, "tui.editor.jumpBackward")) {
  721. this.jumpMode = "backward";
  722. return;
  723. }
  724. // Shift+Space - insert regular space
  725. if (matchesKey(data, "shift+space")) {
  726. this.insertCharacter(" ");
  727. return;
  728. }
  729. const printable = decodePrintableKey(data);
  730. if (printable !== undefined) {
  731. this.insertCharacter(printable);
  732. return;
  733. }
  734. // Regular characters
  735. if (data.charCodeAt(0) >= 32) {
  736. this.insertCharacter(data);
  737. }
  738. }
  739. private layoutText(contentWidth: number): LayoutLine[] {
  740. const layoutLines: LayoutLine[] = [];
  741. if (this.state.lines.length === 0 || (this.state.lines.length === 1 && this.state.lines[0] === "")) {
  742. // Empty editor
  743. layoutLines.push({
  744. text: "",
  745. hasCursor: true,
  746. cursorPos: 0,
  747. });
  748. return layoutLines;
  749. }
  750. // Process each logical line
  751. for (let i = 0; i < this.state.lines.length; i++) {
  752. const line = this.state.lines[i] || "";
  753. const isCurrentLine = i === this.state.cursorLine;
  754. const lineVisibleWidth = visibleWidth(line);
  755. if (lineVisibleWidth <= contentWidth) {
  756. // Line fits in one layout line
  757. if (isCurrentLine) {
  758. layoutLines.push({
  759. text: line,
  760. hasCursor: true,
  761. cursorPos: this.state.cursorCol,
  762. });
  763. } else {
  764. layoutLines.push({
  765. text: line,
  766. hasCursor: false,
  767. });
  768. }
  769. } else {
  770. // Line needs wrapping - use word-aware wrapping
  771. const chunks = wordWrapLine(line, contentWidth, [...this.segment(line, "grapheme")]);
  772. for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
  773. const chunk = chunks[chunkIndex];
  774. if (!chunk) continue;
  775. const cursorPos = this.state.cursorCol;
  776. const isLastChunk = chunkIndex === chunks.length - 1;
  777. // Determine if cursor is in this chunk
  778. // For word-wrapped chunks, we need to handle the case where
  779. // cursor might be in trimmed whitespace at end of chunk
  780. let hasCursorInChunk = false;
  781. let adjustedCursorPos = 0;
  782. if (isCurrentLine) {
  783. if (isLastChunk) {
  784. // Last chunk: cursor belongs here if >= startIndex
  785. hasCursorInChunk = cursorPos >= chunk.startIndex;
  786. adjustedCursorPos = cursorPos - chunk.startIndex;
  787. } else {
  788. // Non-last chunk: cursor belongs here if in range [startIndex, endIndex)
  789. // But we need to handle the visual position in the trimmed text
  790. hasCursorInChunk = cursorPos >= chunk.startIndex && cursorPos < chunk.endIndex;
  791. if (hasCursorInChunk) {
  792. adjustedCursorPos = cursorPos - chunk.startIndex;
  793. // Clamp to text length (in case cursor was in trimmed whitespace)
  794. if (adjustedCursorPos > chunk.text.length) {
  795. adjustedCursorPos = chunk.text.length;
  796. }
  797. }
  798. }
  799. }
  800. if (hasCursorInChunk) {
  801. layoutLines.push({
  802. text: chunk.text,
  803. hasCursor: true,
  804. cursorPos: adjustedCursorPos,
  805. });
  806. } else {
  807. layoutLines.push({
  808. text: chunk.text,
  809. hasCursor: false,
  810. });
  811. }
  812. }
  813. }
  814. }
  815. return layoutLines;
  816. }
  817. getText(): string {
  818. return this.state.lines.join("\n");
  819. }
  820. private expandPasteMarkers(text: string): string {
  821. let result = text;
  822. for (const [pasteId, pasteContent] of this.pastes) {
  823. const markerRegex = new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`, "g");
  824. result = result.replace(markerRegex, () => pasteContent);
  825. }
  826. return result;
  827. }
  828. /**
  829. * Get text with paste markers expanded to their actual content.
  830. * Use this when you need the full content (e.g., for external editor).
  831. */
  832. getExpandedText(): string {
  833. return this.expandPasteMarkers(this.state.lines.join("\n"));
  834. }
  835. getLines(): string[] {
  836. return [...this.state.lines];
  837. }
  838. getCursor(): { line: number; col: number } {
  839. return { line: this.state.cursorLine, col: this.state.cursorCol };
  840. }
  841. setText(text: string): void {
  842. this.cancelAutocomplete();
  843. this.lastAction = null;
  844. this.exitHistoryBrowsing();
  845. const normalized = this.normalizeText(text);
  846. // Push undo snapshot if content differs (makes programmatic changes undoable)
  847. if (this.getText() !== normalized) {
  848. this.pushUndoSnapshot();
  849. }
  850. this.setTextInternal(normalized);
  851. }
  852. /**
  853. * Insert text at the current cursor position.
  854. * Used for programmatic insertion (e.g., clipboard image markers).
  855. * This is atomic for undo - single undo restores entire pre-insert state.
  856. */
  857. insertTextAtCursor(text: string): void {
  858. if (!text) return;
  859. this.cancelAutocomplete();
  860. this.pushUndoSnapshot();
  861. this.lastAction = null;
  862. this.exitHistoryBrowsing();
  863. this.insertTextAtCursorInternal(text);
  864. }
  865. /**
  866. * Normalize text for editor storage:
  867. * - Normalize line endings (\r\n and \r -> \n)
  868. * - Expand tabs to 4 spaces
  869. */
  870. private normalizeText(text: string): string {
  871. return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\t/g, " ");
  872. }
  873. /**
  874. * Internal text insertion at cursor. Handles single and multi-line text.
  875. * Does not push undo snapshots or trigger autocomplete - caller is responsible.
  876. * Normalizes line endings and calls onChange once at the end.
  877. */
  878. private insertTextAtCursorInternal(text: string): void {
  879. if (!text) return;
  880. // Normalize line endings and tabs
  881. const normalized = this.normalizeText(text);
  882. const insertedLines = normalized.split("\n");
  883. const currentLine = this.state.lines[this.state.cursorLine] || "";
  884. const beforeCursor = currentLine.slice(0, this.state.cursorCol);
  885. const afterCursor = currentLine.slice(this.state.cursorCol);
  886. if (insertedLines.length === 1) {
  887. // Single line - insert at cursor position
  888. this.state.lines[this.state.cursorLine] = beforeCursor + normalized + afterCursor;
  889. this.setCursorCol(this.state.cursorCol + normalized.length);
  890. } else {
  891. // Multi-line insertion
  892. this.state.lines = [
  893. // All lines before current line
  894. ...this.state.lines.slice(0, this.state.cursorLine),
  895. // The first inserted line merged with text before cursor
  896. beforeCursor + insertedLines[0],
  897. // All middle inserted lines
  898. ...insertedLines.slice(1, -1),
  899. // The last inserted line with text after cursor
  900. insertedLines[insertedLines.length - 1] + afterCursor,
  901. // All lines after current line
  902. ...this.state.lines.slice(this.state.cursorLine + 1),
  903. ];
  904. this.state.cursorLine += insertedLines.length - 1;
  905. this.setCursorCol((insertedLines[insertedLines.length - 1] || "").length);
  906. }
  907. if (this.onChange) {
  908. this.onChange(this.getText());
  909. }
  910. }
  911. // All the editor methods from before...
  912. private insertCharacter(char: string, skipUndoCoalescing?: boolean): void {
  913. this.exitHistoryBrowsing();
  914. // Undo coalescing (fish-style):
  915. // - Consecutive word chars coalesce into one undo unit
  916. // - Space captures state before itself (so undo removes space+following word together)
  917. // - Each space is separately undoable
  918. // Skip coalescing when called from atomic operations (e.g., handlePaste)
  919. if (!skipUndoCoalescing) {
  920. if (isWhitespaceChar(char) || this.lastAction !== "type-word") {
  921. this.pushUndoSnapshot();
  922. }
  923. this.lastAction = "type-word";
  924. }
  925. const line = this.state.lines[this.state.cursorLine] || "";
  926. const before = line.slice(0, this.state.cursorCol);
  927. const after = line.slice(this.state.cursorCol);
  928. this.state.lines[this.state.cursorLine] = before + char + after;
  929. this.setCursorCol(this.state.cursorCol + char.length);
  930. if (this.onChange) {
  931. this.onChange(this.getText());
  932. }
  933. // Check if we should trigger or update autocomplete
  934. if (!this.autocompleteState) {
  935. // Auto-trigger for "/" at the start of a line (slash commands)
  936. if (char === "/" && this.isAtStartOfMessage()) {
  937. this.tryTriggerAutocomplete();
  938. }
  939. // Auto-trigger for symbol-based completion like @, #, or provider triggers at token boundaries
  940. else if (this.autocompleteTriggerCharacters.includes(char)) {
  941. const currentLine = this.state.lines[this.state.cursorLine] || "";
  942. const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
  943. const charBeforeSymbol = textBeforeCursor[textBeforeCursor.length - 2];
  944. if (textBeforeCursor.length === 1 || charBeforeSymbol === " " || charBeforeSymbol === "\t") {
  945. this.tryTriggerAutocomplete();
  946. }
  947. }
  948. // Also auto-trigger when typing letters in a slash command or symbol completion context
  949. else if (/[a-zA-Z0-9.\-_]/.test(char)) {
  950. const currentLine = this.state.lines[this.state.cursorLine] || "";
  951. const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
  952. // Check if we're in a slash command (with or without space for arguments)
  953. if (this.isInSlashCommandContext(textBeforeCursor)) {
  954. this.tryTriggerAutocomplete();
  955. }
  956. // Check if we're in a symbol-based completion context like @, #, or provider triggers
  957. else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
  958. this.tryTriggerAutocomplete();
  959. }
  960. }
  961. } else {
  962. this.updateAutocomplete();
  963. }
  964. }
  965. private handlePaste(pastedText: string): void {
  966. this.cancelAutocomplete();
  967. this.exitHistoryBrowsing();
  968. this.lastAction = null;
  969. this.pushUndoSnapshot();
  970. // Some terminals (e.g. tmux popups with extended-keys-format=csi-u) re-encode
  971. // control bytes inside bracketed paste as CSI-u Ctrl+<letter> sequences
  972. // (ESC [ <codepoint> ; 5 u). Decode those back to their literal byte so the
  973. // per-char filter below preserves newlines instead of stripping ESC and
  974. // leaking the printable tail (e.g. "[106;5u") into the editor.
  975. const decodedText = pastedText.replace(/\x1b\[(\d+);5u/g, (match, code) => {
  976. const cp = Number(code);
  977. if (cp >= 97 && cp <= 122) return String.fromCharCode(cp - 96);
  978. if (cp >= 65 && cp <= 90) return String.fromCharCode(cp - 64);
  979. return match;
  980. });
  981. // Clean the pasted text: normalize line endings, expand tabs
  982. const cleanText = this.normalizeText(decodedText);
  983. // Filter out non-printable characters except newlines
  984. let filteredText = cleanText
  985. .split("")
  986. .filter((char) => char === "\n" || char.charCodeAt(0) >= 32)
  987. .join("");
  988. // If pasting a file path (starts with /, ~, or .) and the character before
  989. // the cursor is a word character, prepend a space for better readability
  990. if (/^[/~.]/.test(filteredText)) {
  991. const currentLine = this.state.lines[this.state.cursorLine] || "";
  992. const charBeforeCursor = this.state.cursorCol > 0 ? currentLine[this.state.cursorCol - 1] : "";
  993. if (charBeforeCursor && /\w/.test(charBeforeCursor)) {
  994. filteredText = ` ${filteredText}`;
  995. }
  996. }
  997. // Split into lines to check for large paste
  998. const pastedLines = filteredText.split("\n");
  999. // Check if this is a large paste (> 10 lines or > 1000 characters)
  1000. const totalChars = filteredText.length;
  1001. if (pastedLines.length > 10 || totalChars > 1000) {
  1002. // Store the paste and insert a marker
  1003. this.pasteCounter++;
  1004. const pasteId = this.pasteCounter;
  1005. this.pastes.set(pasteId, filteredText);
  1006. // Insert marker like "[paste #1 +123 lines]" or "[paste #1 1234 chars]"
  1007. const marker =
  1008. pastedLines.length > 10
  1009. ? `[paste #${pasteId} +${pastedLines.length} lines]`
  1010. : `[paste #${pasteId} ${totalChars} chars]`;
  1011. this.insertTextAtCursorInternal(marker);
  1012. return;
  1013. }
  1014. if (pastedLines.length === 1) {
  1015. // Single line - insert atomically (do not trigger autocomplete during paste)
  1016. this.insertTextAtCursorInternal(filteredText);
  1017. return;
  1018. }
  1019. // Multi-line paste - use direct state manipulation
  1020. this.insertTextAtCursorInternal(filteredText);
  1021. }
  1022. private addNewLine(): void {
  1023. this.cancelAutocomplete();
  1024. this.exitHistoryBrowsing();
  1025. this.lastAction = null;
  1026. this.pushUndoSnapshot();
  1027. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1028. const before = currentLine.slice(0, this.state.cursorCol);
  1029. const after = currentLine.slice(this.state.cursorCol);
  1030. // Split current line
  1031. this.state.lines[this.state.cursorLine] = before;
  1032. this.state.lines.splice(this.state.cursorLine + 1, 0, after);
  1033. // Move cursor to start of new line
  1034. this.state.cursorLine++;
  1035. this.setCursorCol(0);
  1036. if (this.onChange) {
  1037. this.onChange(this.getText());
  1038. }
  1039. }
  1040. private shouldSubmitOnBackslashEnter(data: string, kb: ReturnType<typeof getKeybindings>): boolean {
  1041. if (this.disableSubmit) return false;
  1042. if (!matchesKey(data, "enter")) return false;
  1043. const submitKeys = kb.getKeys("tui.input.submit");
  1044. const hasShiftEnter = submitKeys.includes("shift+enter") || submitKeys.includes("shift+return");
  1045. if (!hasShiftEnter) return false;
  1046. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1047. return this.state.cursorCol > 0 && currentLine[this.state.cursorCol - 1] === "\\";
  1048. }
  1049. private submitValue(): void {
  1050. this.cancelAutocomplete();
  1051. const result = this.expandPasteMarkers(this.state.lines.join("\n")).trim();
  1052. this.state = { lines: [""], cursorLine: 0, cursorCol: 0 };
  1053. this.pastes.clear();
  1054. this.pasteCounter = 0;
  1055. this.exitHistoryBrowsing();
  1056. this.scrollOffset = 0;
  1057. this.undoStack.clear();
  1058. this.lastAction = null;
  1059. if (this.onChange) this.onChange("");
  1060. if (this.onSubmit) this.onSubmit(result);
  1061. }
  1062. private handleBackspace(): void {
  1063. this.exitHistoryBrowsing();
  1064. this.lastAction = null;
  1065. if (this.state.cursorCol > 0) {
  1066. this.pushUndoSnapshot();
  1067. // Delete grapheme before cursor (handles emojis, combining characters, etc.)
  1068. const line = this.state.lines[this.state.cursorLine] || "";
  1069. const beforeCursor = line.slice(0, this.state.cursorCol);
  1070. // Find the last grapheme in the text before cursor
  1071. const graphemes = [...this.segment(beforeCursor, "grapheme")];
  1072. const lastGrapheme = graphemes[graphemes.length - 1];
  1073. const graphemeLength = lastGrapheme ? lastGrapheme.segment.length : 1;
  1074. const before = line.slice(0, this.state.cursorCol - graphemeLength);
  1075. const after = line.slice(this.state.cursorCol);
  1076. this.state.lines[this.state.cursorLine] = before + after;
  1077. this.setCursorCol(this.state.cursorCol - graphemeLength);
  1078. } else if (this.state.cursorLine > 0) {
  1079. this.pushUndoSnapshot();
  1080. // Merge with previous line
  1081. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1082. const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
  1083. this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
  1084. this.state.lines.splice(this.state.cursorLine, 1);
  1085. this.state.cursorLine--;
  1086. this.setCursorCol(previousLine.length);
  1087. }
  1088. if (this.onChange) {
  1089. this.onChange(this.getText());
  1090. }
  1091. // Update or re-trigger autocomplete after backspace
  1092. if (this.autocompleteState) {
  1093. this.updateAutocomplete();
  1094. } else {
  1095. // If autocomplete was cancelled (no matches), re-trigger if we're in a completable context
  1096. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1097. const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
  1098. // Slash command context
  1099. if (this.isInSlashCommandContext(textBeforeCursor)) {
  1100. this.tryTriggerAutocomplete();
  1101. }
  1102. // Symbol-based completion context like @, #, or provider triggers
  1103. else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
  1104. this.tryTriggerAutocomplete();
  1105. }
  1106. }
  1107. }
  1108. /**
  1109. * Set cursor column and clear preferredVisualCol.
  1110. * Use this for all non-vertical cursor movements to reset sticky column behavior.
  1111. */
  1112. private setCursorCol(col: number): void {
  1113. this.state.cursorCol = col;
  1114. this.preferredVisualCol = null;
  1115. this.snappedFromCursorCol = null;
  1116. }
  1117. /**
  1118. * Move cursor to a target visual line, applying sticky column logic.
  1119. * Shared by moveCursor() and pageScroll().
  1120. */
  1121. private moveToVisualLine(
  1122. visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
  1123. currentVisualLine: number,
  1124. targetVisualLine: number,
  1125. ): void {
  1126. const currentVL = visualLines[currentVisualLine];
  1127. const targetVL = visualLines[targetVisualLine];
  1128. if (!(currentVL && targetVL)) return;
  1129. // When the cursor was snapped to a segment start, resolve the pre-snap
  1130. // position against the VL it belongs to. This gives the correct visual
  1131. // column even after a resize reshuffles VLs.
  1132. let currentVisualCol: number;
  1133. if (this.snappedFromCursorCol !== null) {
  1134. const vlIndex = this.findVisualLineAt(visualLines, currentVL.logicalLine, this.snappedFromCursorCol);
  1135. currentVisualCol = this.snappedFromCursorCol - visualLines[vlIndex].startCol;
  1136. } else {
  1137. currentVisualCol = this.state.cursorCol - currentVL.startCol;
  1138. }
  1139. // For non-last segments, clamp to length-1 to stay within the segment
  1140. const isLastSourceSegment =
  1141. currentVisualLine === visualLines.length - 1 ||
  1142. visualLines[currentVisualLine + 1]?.logicalLine !== currentVL.logicalLine;
  1143. const sourceMaxVisualCol = isLastSourceSegment ? currentVL.length : Math.max(0, currentVL.length - 1);
  1144. const isLastTargetSegment =
  1145. targetVisualLine === visualLines.length - 1 ||
  1146. visualLines[targetVisualLine + 1]?.logicalLine !== targetVL.logicalLine;
  1147. const targetMaxVisualCol = isLastTargetSegment ? targetVL.length : Math.max(0, targetVL.length - 1);
  1148. const moveToVisualCol = this.computeVerticalMoveColumn(currentVisualCol, sourceMaxVisualCol, targetMaxVisualCol);
  1149. // Set cursor position
  1150. this.state.cursorLine = targetVL.logicalLine;
  1151. const targetCol = targetVL.startCol + moveToVisualCol;
  1152. const logicalLine = this.state.lines[targetVL.logicalLine] || "";
  1153. this.state.cursorCol = Math.min(targetCol, logicalLine.length);
  1154. // Snap cursor to atomic segment boundary (e.g. paste markers)
  1155. // so the cursor never lands in the middle of a multi-grapheme unit.
  1156. // Single-grapheme segments don't need snapping.
  1157. const segments = [...this.segment(logicalLine, "grapheme")];
  1158. for (const seg of segments) {
  1159. if (seg.index > this.state.cursorCol) break;
  1160. if (seg.segment.length <= 1) continue;
  1161. if (this.state.cursorCol < seg.index + seg.segment.length) {
  1162. const isContinuation = seg.index < targetVL.startCol;
  1163. const isMovingDown = targetVisualLine > currentVisualLine;
  1164. if (isContinuation && isMovingDown) {
  1165. // The segment started on a previous visual line, and we
  1166. // already visited it on the way down. Skip all remaining
  1167. // continuation VLs and land on the first VL past it.
  1168. const segEnd = seg.index + seg.segment.length;
  1169. let next = targetVisualLine + 1;
  1170. while (
  1171. next < visualLines.length &&
  1172. visualLines[next].logicalLine === targetVL.logicalLine &&
  1173. visualLines[next].startCol < segEnd
  1174. ) {
  1175. next++;
  1176. }
  1177. if (next < visualLines.length) {
  1178. this.moveToVisualLine(visualLines, currentVisualLine, next);
  1179. return;
  1180. }
  1181. }
  1182. // Snap to the start of the segment so it gets highlighted.
  1183. // Store the pre-snap position so the next vertical move can
  1184. // resolve it to the correct visual column.
  1185. this.snappedFromCursorCol = this.state.cursorCol;
  1186. this.state.cursorCol = seg.index;
  1187. return;
  1188. }
  1189. }
  1190. // No snap occurred – we moved out of the atomic segment.
  1191. this.snappedFromCursorCol = null;
  1192. }
  1193. /**
  1194. * Compute the target visual column for vertical cursor movement.
  1195. * Implements the sticky column decision table:
  1196. *
  1197. * | P | S | T | U | Scenario | Set Preferred | Move To |
  1198. * |---|---|---|---| ---------------------------------------------------- |---------------|-------------|
  1199. * | 0 | * | 0 | - | Start nav, target fits | null | current |
  1200. * | 0 | * | 1 | - | Start nav, target shorter | current | target end |
  1201. * | 1 | 0 | 0 | 0 | Clamped, target fits preferred | null | preferred |
  1202. * | 1 | 0 | 0 | 1 | Clamped, target longer but still can't fit preferred | keep | target end |
  1203. * | 1 | 0 | 1 | - | Clamped, target even shorter | keep | target end |
  1204. * | 1 | 1 | 0 | - | Rewrapped, target fits current | null | current |
  1205. * | 1 | 1 | 1 | - | Rewrapped, target shorter than current | current | target end |
  1206. *
  1207. * Where:
  1208. * - P = preferred col is set
  1209. * - S = cursor in middle of source line (not clamped to end)
  1210. * - T = target line shorter than current visual col
  1211. * - U = target line shorter than preferred col
  1212. */
  1213. private computeVerticalMoveColumn(
  1214. currentVisualCol: number,
  1215. sourceMaxVisualCol: number,
  1216. targetMaxVisualCol: number,
  1217. ): number {
  1218. const hasPreferred = this.preferredVisualCol !== null; // P
  1219. const cursorInMiddle = currentVisualCol < sourceMaxVisualCol; // S
  1220. const targetTooShort = targetMaxVisualCol < currentVisualCol; // T
  1221. if (!hasPreferred || cursorInMiddle) {
  1222. if (targetTooShort) {
  1223. // Cases 2 and 7
  1224. this.preferredVisualCol = currentVisualCol;
  1225. return targetMaxVisualCol;
  1226. }
  1227. // Cases 1 and 6
  1228. this.preferredVisualCol = null;
  1229. return currentVisualCol;
  1230. }
  1231. const targetCantFitPreferred = targetMaxVisualCol < this.preferredVisualCol!; // U
  1232. if (targetTooShort || targetCantFitPreferred) {
  1233. // Cases 4 and 5
  1234. return targetMaxVisualCol;
  1235. }
  1236. // Case 3
  1237. const result = this.preferredVisualCol!;
  1238. this.preferredVisualCol = null;
  1239. return result;
  1240. }
  1241. private moveToLineStart(): void {
  1242. this.lastAction = null;
  1243. this.setCursorCol(0);
  1244. }
  1245. private moveToLineEnd(): void {
  1246. this.lastAction = null;
  1247. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1248. this.setCursorCol(currentLine.length);
  1249. }
  1250. private deleteToStartOfLine(): void {
  1251. this.exitHistoryBrowsing();
  1252. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1253. if (this.state.cursorCol > 0) {
  1254. this.pushUndoSnapshot();
  1255. // Calculate text to be deleted and save to kill ring (backward deletion = prepend)
  1256. const deletedText = currentLine.slice(0, this.state.cursorCol);
  1257. this.killRing.push(deletedText, { prepend: true, accumulate: this.lastAction === "kill" });
  1258. this.lastAction = "kill";
  1259. // Delete from start of line up to cursor
  1260. this.state.lines[this.state.cursorLine] = currentLine.slice(this.state.cursorCol);
  1261. this.setCursorCol(0);
  1262. } else if (this.state.cursorLine > 0) {
  1263. this.pushUndoSnapshot();
  1264. // At start of line - merge with previous line, treating newline as deleted text
  1265. this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
  1266. this.lastAction = "kill";
  1267. const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
  1268. this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
  1269. this.state.lines.splice(this.state.cursorLine, 1);
  1270. this.state.cursorLine--;
  1271. this.setCursorCol(previousLine.length);
  1272. }
  1273. if (this.onChange) {
  1274. this.onChange(this.getText());
  1275. }
  1276. }
  1277. private deleteToEndOfLine(): void {
  1278. this.exitHistoryBrowsing();
  1279. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1280. if (this.state.cursorCol < currentLine.length) {
  1281. this.pushUndoSnapshot();
  1282. // Calculate text to be deleted and save to kill ring (forward deletion = append)
  1283. const deletedText = currentLine.slice(this.state.cursorCol);
  1284. this.killRing.push(deletedText, { prepend: false, accumulate: this.lastAction === "kill" });
  1285. this.lastAction = "kill";
  1286. // Delete from cursor to end of line
  1287. this.state.lines[this.state.cursorLine] = currentLine.slice(0, this.state.cursorCol);
  1288. } else if (this.state.cursorLine < this.state.lines.length - 1) {
  1289. this.pushUndoSnapshot();
  1290. // At end of line - merge with next line, treating newline as deleted text
  1291. this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
  1292. this.lastAction = "kill";
  1293. const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
  1294. this.state.lines[this.state.cursorLine] = currentLine + nextLine;
  1295. this.state.lines.splice(this.state.cursorLine + 1, 1);
  1296. }
  1297. if (this.onChange) {
  1298. this.onChange(this.getText());
  1299. }
  1300. }
  1301. private deleteWordBackwards(): void {
  1302. this.exitHistoryBrowsing();
  1303. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1304. // If at start of line, behave like backspace at column 0 (merge with previous line)
  1305. if (this.state.cursorCol === 0) {
  1306. if (this.state.cursorLine > 0) {
  1307. this.pushUndoSnapshot();
  1308. // Treat newline as deleted text (backward deletion = prepend)
  1309. this.killRing.push("\n", { prepend: true, accumulate: this.lastAction === "kill" });
  1310. this.lastAction = "kill";
  1311. const previousLine = this.state.lines[this.state.cursorLine - 1] || "";
  1312. this.state.lines[this.state.cursorLine - 1] = previousLine + currentLine;
  1313. this.state.lines.splice(this.state.cursorLine, 1);
  1314. this.state.cursorLine--;
  1315. this.setCursorCol(previousLine.length);
  1316. }
  1317. } else {
  1318. this.pushUndoSnapshot();
  1319. // Save lastAction before cursor movement (moveWordBackwards resets it)
  1320. const wasKill = this.lastAction === "kill";
  1321. const oldCursorCol = this.state.cursorCol;
  1322. this.moveWordBackwards();
  1323. const deleteFrom = this.state.cursorCol;
  1324. this.setCursorCol(oldCursorCol);
  1325. const deletedText = currentLine.slice(deleteFrom, this.state.cursorCol);
  1326. this.killRing.push(deletedText, { prepend: true, accumulate: wasKill });
  1327. this.lastAction = "kill";
  1328. this.state.lines[this.state.cursorLine] =
  1329. currentLine.slice(0, deleteFrom) + currentLine.slice(this.state.cursorCol);
  1330. this.setCursorCol(deleteFrom);
  1331. }
  1332. if (this.onChange) {
  1333. this.onChange(this.getText());
  1334. }
  1335. }
  1336. private deleteWordForward(): void {
  1337. this.exitHistoryBrowsing();
  1338. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1339. // If at end of line, merge with next line (delete the newline)
  1340. if (this.state.cursorCol >= currentLine.length) {
  1341. if (this.state.cursorLine < this.state.lines.length - 1) {
  1342. this.pushUndoSnapshot();
  1343. // Treat newline as deleted text (forward deletion = append)
  1344. this.killRing.push("\n", { prepend: false, accumulate: this.lastAction === "kill" });
  1345. this.lastAction = "kill";
  1346. const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
  1347. this.state.lines[this.state.cursorLine] = currentLine + nextLine;
  1348. this.state.lines.splice(this.state.cursorLine + 1, 1);
  1349. }
  1350. } else {
  1351. this.pushUndoSnapshot();
  1352. // Save lastAction before cursor movement (moveWordForwards resets it)
  1353. const wasKill = this.lastAction === "kill";
  1354. const oldCursorCol = this.state.cursorCol;
  1355. this.moveWordForwards();
  1356. const deleteTo = this.state.cursorCol;
  1357. this.setCursorCol(oldCursorCol);
  1358. const deletedText = currentLine.slice(this.state.cursorCol, deleteTo);
  1359. this.killRing.push(deletedText, { prepend: false, accumulate: wasKill });
  1360. this.lastAction = "kill";
  1361. this.state.lines[this.state.cursorLine] =
  1362. currentLine.slice(0, this.state.cursorCol) + currentLine.slice(deleteTo);
  1363. }
  1364. if (this.onChange) {
  1365. this.onChange(this.getText());
  1366. }
  1367. }
  1368. private handleForwardDelete(): void {
  1369. this.exitHistoryBrowsing();
  1370. this.lastAction = null;
  1371. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1372. if (this.state.cursorCol < currentLine.length) {
  1373. this.pushUndoSnapshot();
  1374. // Delete grapheme at cursor position (handles emojis, combining characters, etc.)
  1375. const afterCursor = currentLine.slice(this.state.cursorCol);
  1376. // Find the first grapheme at cursor
  1377. const graphemes = [...this.segment(afterCursor, "grapheme")];
  1378. const firstGrapheme = graphemes[0];
  1379. const graphemeLength = firstGrapheme ? firstGrapheme.segment.length : 1;
  1380. const before = currentLine.slice(0, this.state.cursorCol);
  1381. const after = currentLine.slice(this.state.cursorCol + graphemeLength);
  1382. this.state.lines[this.state.cursorLine] = before + after;
  1383. } else if (this.state.cursorLine < this.state.lines.length - 1) {
  1384. this.pushUndoSnapshot();
  1385. // At end of line - merge with next line
  1386. const nextLine = this.state.lines[this.state.cursorLine + 1] || "";
  1387. this.state.lines[this.state.cursorLine] = currentLine + nextLine;
  1388. this.state.lines.splice(this.state.cursorLine + 1, 1);
  1389. }
  1390. if (this.onChange) {
  1391. this.onChange(this.getText());
  1392. }
  1393. // Update or re-trigger autocomplete after forward delete
  1394. if (this.autocompleteState) {
  1395. this.updateAutocomplete();
  1396. } else {
  1397. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1398. const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
  1399. // Slash command context
  1400. if (this.isInSlashCommandContext(textBeforeCursor)) {
  1401. this.tryTriggerAutocomplete();
  1402. }
  1403. // Symbol-based completion context like @, #, or provider triggers
  1404. else if (this.autocompleteTriggerPattern.test(textBeforeCursor)) {
  1405. this.tryTriggerAutocomplete();
  1406. }
  1407. }
  1408. }
  1409. /**
  1410. * Build a mapping from visual lines to logical positions.
  1411. * Returns an array where each element represents a visual line with:
  1412. * - logicalLine: index into this.state.lines
  1413. * - startCol: starting column in the logical line
  1414. * - length: length of this visual line segment
  1415. */
  1416. private buildVisualLineMap(width: number): Array<{ logicalLine: number; startCol: number; length: number }> {
  1417. const visualLines: Array<{ logicalLine: number; startCol: number; length: number }> = [];
  1418. for (let i = 0; i < this.state.lines.length; i++) {
  1419. const line = this.state.lines[i] || "";
  1420. const lineVisWidth = visibleWidth(line);
  1421. if (line.length === 0) {
  1422. // Empty line still takes one visual line
  1423. visualLines.push({ logicalLine: i, startCol: 0, length: 0 });
  1424. } else if (lineVisWidth <= width) {
  1425. visualLines.push({ logicalLine: i, startCol: 0, length: line.length });
  1426. } else {
  1427. // Line needs wrapping - use word-aware wrapping
  1428. const chunks = wordWrapLine(line, width, [...this.segment(line, "grapheme")]);
  1429. for (const chunk of chunks) {
  1430. visualLines.push({
  1431. logicalLine: i,
  1432. startCol: chunk.startIndex,
  1433. length: chunk.endIndex - chunk.startIndex,
  1434. });
  1435. }
  1436. }
  1437. }
  1438. return visualLines;
  1439. }
  1440. /**
  1441. * Find the visual line index that contains the given logical position.
  1442. */
  1443. private findVisualLineAt(
  1444. visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
  1445. line: number,
  1446. col: number,
  1447. ): number {
  1448. for (let i = 0; i < visualLines.length; i++) {
  1449. const vl = visualLines[i];
  1450. if (!vl || vl.logicalLine !== line) continue;
  1451. const offset = col - vl.startCol;
  1452. // Cursor is in this segment if it's within range. For the last
  1453. // segment of a logical line, cursor can be at length (end position)
  1454. const isLastSegmentOfLine = i === visualLines.length - 1 || visualLines[i + 1]?.logicalLine !== vl.logicalLine;
  1455. if (offset >= 0 && (offset < vl.length || (isLastSegmentOfLine && offset === vl.length))) {
  1456. return i;
  1457. }
  1458. }
  1459. return visualLines.length - 1;
  1460. }
  1461. /**
  1462. * Find the visual line index for the current cursor position.
  1463. */
  1464. private findCurrentVisualLine(
  1465. visualLines: Array<{ logicalLine: number; startCol: number; length: number }>,
  1466. ): number {
  1467. return this.findVisualLineAt(visualLines, this.state.cursorLine, this.state.cursorCol);
  1468. }
  1469. private moveCursor(deltaLine: number, deltaCol: number): void {
  1470. this.lastAction = null;
  1471. const visualLines = this.buildVisualLineMap(this.lastWidth);
  1472. const currentVisualLine = this.findCurrentVisualLine(visualLines);
  1473. if (deltaLine !== 0) {
  1474. const targetVisualLine = currentVisualLine + deltaLine;
  1475. if (targetVisualLine >= 0 && targetVisualLine < visualLines.length) {
  1476. this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
  1477. }
  1478. }
  1479. if (deltaCol !== 0) {
  1480. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1481. if (deltaCol > 0) {
  1482. // Moving right - move by one grapheme (handles emojis, combining characters, etc.)
  1483. if (this.state.cursorCol < currentLine.length) {
  1484. const afterCursor = currentLine.slice(this.state.cursorCol);
  1485. const graphemes = [...this.segment(afterCursor, "grapheme")];
  1486. const firstGrapheme = graphemes[0];
  1487. this.setCursorCol(this.state.cursorCol + (firstGrapheme ? firstGrapheme.segment.length : 1));
  1488. } else if (this.state.cursorLine < this.state.lines.length - 1) {
  1489. // Wrap to start of next logical line
  1490. this.state.cursorLine++;
  1491. this.setCursorCol(0);
  1492. } else {
  1493. // At end of last line - can't move, but set preferredVisualCol for up/down navigation
  1494. const currentVL = visualLines[currentVisualLine];
  1495. if (currentVL) {
  1496. this.preferredVisualCol = this.state.cursorCol - currentVL.startCol;
  1497. }
  1498. }
  1499. } else {
  1500. // Moving left - move by one grapheme (handles emojis, combining characters, etc.)
  1501. if (this.state.cursorCol > 0) {
  1502. const beforeCursor = currentLine.slice(0, this.state.cursorCol);
  1503. const graphemes = [...this.segment(beforeCursor, "grapheme")];
  1504. const lastGrapheme = graphemes[graphemes.length - 1];
  1505. this.setCursorCol(this.state.cursorCol - (lastGrapheme ? lastGrapheme.segment.length : 1));
  1506. } else if (this.state.cursorLine > 0) {
  1507. // Wrap to end of previous logical line
  1508. this.state.cursorLine--;
  1509. const prevLine = this.state.lines[this.state.cursorLine] || "";
  1510. this.setCursorCol(prevLine.length);
  1511. }
  1512. }
  1513. }
  1514. // Keep an open autocomplete picker in sync with the new cursor
  1515. // position: cursor movement changes the text before the cursor, so a
  1516. // picker computed for the old position is stale. Re-query so it
  1517. // refreshes — or closes when the new position yields no suggestions —
  1518. // mirroring insertCharacter()/handleBackspace(). Without this, arrowing
  1519. // left from `/cmd ` back into the command name leaves the argument
  1520. // picker showing against a `/cmd` prefix (and a Tab there would
  1521. // concatenate the stale suggestion onto the partial command name).
  1522. if (this.autocompleteState) {
  1523. this.updateAutocomplete();
  1524. }
  1525. }
  1526. /**
  1527. * Scroll by a page (direction: -1 for up, 1 for down).
  1528. * Moves cursor by the page size while keeping it in bounds.
  1529. */
  1530. private pageScroll(direction: -1 | 1): void {
  1531. this.lastAction = null;
  1532. const terminalRows = this.tui.terminal.rows;
  1533. const pageSize = Math.max(5, Math.floor(terminalRows * 0.3));
  1534. const visualLines = this.buildVisualLineMap(this.lastWidth);
  1535. const currentVisualLine = this.findCurrentVisualLine(visualLines);
  1536. const targetVisualLine = Math.max(0, Math.min(visualLines.length - 1, currentVisualLine + direction * pageSize));
  1537. this.moveToVisualLine(visualLines, currentVisualLine, targetVisualLine);
  1538. }
  1539. private moveWordBackwards(): void {
  1540. this.lastAction = null;
  1541. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1542. // If at start of line, move to end of previous line
  1543. if (this.state.cursorCol === 0) {
  1544. if (this.state.cursorLine > 0) {
  1545. this.state.cursorLine--;
  1546. const prevLine = this.state.lines[this.state.cursorLine] || "";
  1547. this.setCursorCol(prevLine.length);
  1548. }
  1549. return;
  1550. }
  1551. this.setCursorCol(
  1552. findWordBackward(currentLine, this.state.cursorCol, {
  1553. segment: (text) => this.segment(text, "word"),
  1554. isAtomicSegment: isPasteMarker,
  1555. }),
  1556. );
  1557. }
  1558. /**
  1559. * Yank (paste) the most recent kill ring entry at cursor position.
  1560. */
  1561. private yank(): void {
  1562. if (this.killRing.length === 0) return;
  1563. this.pushUndoSnapshot();
  1564. const text = this.killRing.peek()!;
  1565. this.insertYankedText(text);
  1566. this.lastAction = "yank";
  1567. }
  1568. /**
  1569. * Cycle through kill ring (only works immediately after yank or yank-pop).
  1570. * Replaces the last yanked text with the previous entry in the ring.
  1571. */
  1572. private yankPop(): void {
  1573. // Only works if we just yanked and have more than one entry
  1574. if (this.lastAction !== "yank" || this.killRing.length <= 1) return;
  1575. this.pushUndoSnapshot();
  1576. // Delete the previously yanked text (still at end of ring before rotation)
  1577. this.deleteYankedText();
  1578. // Rotate the ring: move end to front
  1579. this.killRing.rotate();
  1580. // Insert the new most recent entry (now at end after rotation)
  1581. const text = this.killRing.peek()!;
  1582. this.insertYankedText(text);
  1583. this.lastAction = "yank";
  1584. }
  1585. /**
  1586. * Insert text at cursor position (used by yank operations).
  1587. */
  1588. private insertYankedText(text: string): void {
  1589. this.exitHistoryBrowsing();
  1590. const lines = text.split("\n");
  1591. if (lines.length === 1) {
  1592. // Single line - insert at cursor
  1593. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1594. const before = currentLine.slice(0, this.state.cursorCol);
  1595. const after = currentLine.slice(this.state.cursorCol);
  1596. this.state.lines[this.state.cursorLine] = before + text + after;
  1597. this.setCursorCol(this.state.cursorCol + text.length);
  1598. } else {
  1599. // Multi-line insert
  1600. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1601. const before = currentLine.slice(0, this.state.cursorCol);
  1602. const after = currentLine.slice(this.state.cursorCol);
  1603. // First line merges with text before cursor
  1604. this.state.lines[this.state.cursorLine] = before + (lines[0] || "");
  1605. // Insert middle lines
  1606. for (let i = 1; i < lines.length - 1; i++) {
  1607. this.state.lines.splice(this.state.cursorLine + i, 0, lines[i] || "");
  1608. }
  1609. // Last line merges with text after cursor
  1610. const lastLineIndex = this.state.cursorLine + lines.length - 1;
  1611. this.state.lines.splice(lastLineIndex, 0, (lines[lines.length - 1] || "") + after);
  1612. // Update cursor position
  1613. this.state.cursorLine = lastLineIndex;
  1614. this.setCursorCol((lines[lines.length - 1] || "").length);
  1615. }
  1616. if (this.onChange) {
  1617. this.onChange(this.getText());
  1618. }
  1619. }
  1620. /**
  1621. * Delete the previously yanked text (used by yank-pop).
  1622. * The yanked text is derived from killRing[end] since it hasn't been rotated yet.
  1623. */
  1624. private deleteYankedText(): void {
  1625. const yankedText = this.killRing.peek();
  1626. if (!yankedText) return;
  1627. const yankLines = yankedText.split("\n");
  1628. if (yankLines.length === 1) {
  1629. // Single line - delete backward from cursor
  1630. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1631. const deleteLen = yankedText.length;
  1632. const before = currentLine.slice(0, this.state.cursorCol - deleteLen);
  1633. const after = currentLine.slice(this.state.cursorCol);
  1634. this.state.lines[this.state.cursorLine] = before + after;
  1635. this.setCursorCol(this.state.cursorCol - deleteLen);
  1636. } else {
  1637. // Multi-line delete - cursor is at end of last yanked line
  1638. const startLine = this.state.cursorLine - (yankLines.length - 1);
  1639. const startCol = (this.state.lines[startLine] || "").length - (yankLines[0] || "").length;
  1640. // Get text after cursor on current line
  1641. const afterCursor = (this.state.lines[this.state.cursorLine] || "").slice(this.state.cursorCol);
  1642. // Get text before yank start position
  1643. const beforeYank = (this.state.lines[startLine] || "").slice(0, startCol);
  1644. // Remove all lines from startLine to cursorLine and replace with merged line
  1645. this.state.lines.splice(startLine, yankLines.length, beforeYank + afterCursor);
  1646. // Update cursor
  1647. this.state.cursorLine = startLine;
  1648. this.setCursorCol(startCol);
  1649. }
  1650. if (this.onChange) {
  1651. this.onChange(this.getText());
  1652. }
  1653. }
  1654. private pushUndoSnapshot(): void {
  1655. this.undoStack.push(this.state);
  1656. }
  1657. private undo(): void {
  1658. this.exitHistoryBrowsing();
  1659. const snapshot = this.undoStack.pop();
  1660. if (!snapshot) return;
  1661. Object.assign(this.state, snapshot);
  1662. this.lastAction = null;
  1663. this.preferredVisualCol = null;
  1664. if (this.onChange) {
  1665. this.onChange(this.getText());
  1666. }
  1667. }
  1668. /**
  1669. * Jump to the first occurrence of a character in the specified direction.
  1670. * Multi-line search. Case-sensitive. Skips the current cursor position.
  1671. */
  1672. private jumpToChar(char: string, direction: "forward" | "backward"): void {
  1673. this.lastAction = null;
  1674. const isForward = direction === "forward";
  1675. const lines = this.state.lines;
  1676. const end = isForward ? lines.length : -1;
  1677. const step = isForward ? 1 : -1;
  1678. for (let lineIdx = this.state.cursorLine; lineIdx !== end; lineIdx += step) {
  1679. const line = lines[lineIdx] || "";
  1680. const isCurrentLine = lineIdx === this.state.cursorLine;
  1681. // Current line: start after/before cursor; other lines: search full line
  1682. const searchFrom = isCurrentLine
  1683. ? isForward
  1684. ? this.state.cursorCol + 1
  1685. : this.state.cursorCol - 1
  1686. : undefined;
  1687. const idx = isForward ? line.indexOf(char, searchFrom) : line.lastIndexOf(char, searchFrom);
  1688. if (idx !== -1) {
  1689. this.state.cursorLine = lineIdx;
  1690. this.setCursorCol(idx);
  1691. return;
  1692. }
  1693. }
  1694. // No match found - cursor stays in place
  1695. }
  1696. private moveWordForwards(): void {
  1697. this.lastAction = null;
  1698. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1699. // If at end of line, move to start of next line
  1700. if (this.state.cursorCol >= currentLine.length) {
  1701. if (this.state.cursorLine < this.state.lines.length - 1) {
  1702. this.state.cursorLine++;
  1703. this.setCursorCol(0);
  1704. }
  1705. return;
  1706. }
  1707. this.setCursorCol(
  1708. findWordForward(currentLine, this.state.cursorCol, {
  1709. segment: (text) => this.segment(text, "word"),
  1710. isAtomicSegment: isPasteMarker,
  1711. }),
  1712. );
  1713. }
  1714. // Slash menu only allowed on the first line of the editor
  1715. private isSlashMenuAllowed(): boolean {
  1716. return this.state.cursorLine === 0;
  1717. }
  1718. // Helper method to check if cursor is at start of message (for slash command detection)
  1719. private isAtStartOfMessage(): boolean {
  1720. if (!this.isSlashMenuAllowed()) return false;
  1721. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1722. const beforeCursor = currentLine.slice(0, this.state.cursorCol);
  1723. return beforeCursor.trim() === "" || beforeCursor.trim() === "/";
  1724. }
  1725. private isInSlashCommandContext(textBeforeCursor: string): boolean {
  1726. return this.isSlashMenuAllowed() && textBeforeCursor.trimStart().startsWith("/");
  1727. }
  1728. // Autocomplete methods
  1729. /**
  1730. * Find the best autocomplete item index for the given prefix.
  1731. * Returns -1 if no match is found.
  1732. *
  1733. * Match priority:
  1734. * 1. Exact match (prefix === item.value) -> always selected
  1735. * 2. Prefix match -> first item whose value starts with prefix
  1736. * 3. No match -> -1 (keep default highlight)
  1737. *
  1738. * Matching is case-sensitive and checks item.value only.
  1739. */
  1740. private getBestAutocompleteMatchIndex(items: Array<{ value: string; label: string }>, prefix: string): number {
  1741. if (!prefix) return -1;
  1742. let firstPrefixIndex = -1;
  1743. for (let i = 0; i < items.length; i++) {
  1744. const value = items[i]!.value;
  1745. if (value === prefix) {
  1746. return i; // Exact match always wins
  1747. }
  1748. if (firstPrefixIndex === -1 && value.startsWith(prefix)) {
  1749. firstPrefixIndex = i;
  1750. }
  1751. }
  1752. return firstPrefixIndex;
  1753. }
  1754. private createAutocompleteList(
  1755. prefix: string,
  1756. items: Array<{ value: string; label: string; description?: string }>,
  1757. ): SelectList {
  1758. const layout = prefix.startsWith("/") ? SLASH_COMMAND_SELECT_LIST_LAYOUT : undefined;
  1759. return new SelectList(items, this.autocompleteMaxVisible, this.theme.selectList, layout);
  1760. }
  1761. private tryTriggerAutocomplete(explicitTab: boolean = false): void {
  1762. this.requestAutocomplete({ force: false, explicitTab });
  1763. }
  1764. private handleTabCompletion(): void {
  1765. if (!this.autocompleteProvider) return;
  1766. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1767. const beforeCursor = currentLine.slice(0, this.state.cursorCol);
  1768. if (this.isInSlashCommandContext(beforeCursor) && !beforeCursor.trimStart().includes(" ")) {
  1769. this.handleSlashCommandCompletion();
  1770. } else {
  1771. this.forceFileAutocomplete(true);
  1772. }
  1773. }
  1774. private handleSlashCommandCompletion(): void {
  1775. this.requestAutocomplete({ force: false, explicitTab: true });
  1776. }
  1777. private forceFileAutocomplete(explicitTab: boolean = false): void {
  1778. this.requestAutocomplete({ force: true, explicitTab });
  1779. }
  1780. private requestAutocomplete(options: { force: boolean; explicitTab: boolean }): void {
  1781. if (!this.autocompleteProvider) return;
  1782. if (options.force) {
  1783. const shouldTrigger =
  1784. !this.autocompleteProvider.shouldTriggerFileCompletion ||
  1785. this.autocompleteProvider.shouldTriggerFileCompletion(
  1786. this.state.lines,
  1787. this.state.cursorLine,
  1788. this.state.cursorCol,
  1789. );
  1790. if (!shouldTrigger) {
  1791. return;
  1792. }
  1793. }
  1794. this.cancelAutocompleteRequest();
  1795. const startToken = ++this.autocompleteStartToken;
  1796. const debounceMs = this.getAutocompleteDebounceMs(options);
  1797. if (debounceMs > 0) {
  1798. this.autocompleteDebounceTimer = setTimeout(() => {
  1799. this.autocompleteDebounceTimer = undefined;
  1800. void this.startAutocompleteRequest(startToken, options);
  1801. }, debounceMs);
  1802. return;
  1803. }
  1804. void this.startAutocompleteRequest(startToken, options);
  1805. }
  1806. private async startAutocompleteRequest(
  1807. startToken: number,
  1808. options: { force: boolean; explicitTab: boolean },
  1809. ): Promise<void> {
  1810. const previousTask = this.autocompleteRequestTask;
  1811. this.autocompleteRequestTask = (async () => {
  1812. await previousTask;
  1813. if (startToken !== this.autocompleteStartToken || !this.autocompleteProvider) {
  1814. return;
  1815. }
  1816. const controller = new AbortController();
  1817. this.autocompleteAbort = controller;
  1818. const requestId = ++this.autocompleteRequestId;
  1819. const snapshotText = this.getText();
  1820. const snapshotLine = this.state.cursorLine;
  1821. const snapshotCol = this.state.cursorCol;
  1822. await this.runAutocompleteRequest(requestId, controller, snapshotText, snapshotLine, snapshotCol, options);
  1823. })();
  1824. await this.autocompleteRequestTask;
  1825. }
  1826. private setAutocompleteTriggerCharacters(triggerCharacters: string[]): void {
  1827. const next = [...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];
  1828. for (const character of triggerCharacters) {
  1829. if (character.length !== 1 || character === "/" || isWhitespaceChar(character) || next.includes(character)) {
  1830. continue;
  1831. }
  1832. next.push(character);
  1833. }
  1834. this.autocompleteTriggerCharacters = next;
  1835. this.autocompleteTriggerPattern = buildTriggerPattern(next);
  1836. this.autocompleteDebouncePattern = buildDebouncePattern(next);
  1837. }
  1838. private getAutocompleteDebounceMs(options: { force: boolean; explicitTab: boolean }): number {
  1839. if (options.explicitTab || options.force) {
  1840. return 0;
  1841. }
  1842. const currentLine = this.state.lines[this.state.cursorLine] || "";
  1843. const textBeforeCursor = currentLine.slice(0, this.state.cursorCol);
  1844. return this.autocompleteDebouncePattern.test(textBeforeCursor) ? ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS : 0;
  1845. }
  1846. private async runAutocompleteRequest(
  1847. requestId: number,
  1848. controller: AbortController,
  1849. snapshotText: string,
  1850. snapshotLine: number,
  1851. snapshotCol: number,
  1852. options: { force: boolean; explicitTab: boolean },
  1853. ): Promise<void> {
  1854. if (!this.autocompleteProvider) return;
  1855. const suggestions = await this.autocompleteProvider.getSuggestions(
  1856. this.state.lines,
  1857. this.state.cursorLine,
  1858. this.state.cursorCol,
  1859. { signal: controller.signal, force: options.force },
  1860. );
  1861. if (!this.isAutocompleteRequestCurrent(requestId, controller, snapshotText, snapshotLine, snapshotCol)) {
  1862. return;
  1863. }
  1864. this.autocompleteAbort = undefined;
  1865. if (!suggestions || !Array.isArray(suggestions.items) || suggestions.items.length === 0) {
  1866. this.cancelAutocomplete();
  1867. this.tui.requestRender();
  1868. return;
  1869. }
  1870. if (options.force && options.explicitTab && suggestions.items.length === 1) {
  1871. const item = suggestions.items[0]!;
  1872. this.pushUndoSnapshot();
  1873. this.lastAction = null;
  1874. const result = this.autocompleteProvider.applyCompletion(
  1875. this.state.lines,
  1876. this.state.cursorLine,
  1877. this.state.cursorCol,
  1878. item,
  1879. suggestions.prefix,
  1880. );
  1881. this.state.lines = result.lines;
  1882. this.state.cursorLine = result.cursorLine;
  1883. this.setCursorCol(result.cursorCol);
  1884. if (this.onChange) this.onChange(this.getText());
  1885. this.tui.requestRender();
  1886. return;
  1887. }
  1888. this.applyAutocompleteSuggestions(suggestions, options.force ? "force" : "regular");
  1889. this.tui.requestRender();
  1890. }
  1891. private isAutocompleteRequestCurrent(
  1892. requestId: number,
  1893. controller: AbortController,
  1894. snapshotText: string,
  1895. snapshotLine: number,
  1896. snapshotCol: number,
  1897. ): boolean {
  1898. return (
  1899. !controller.signal.aborted &&
  1900. requestId === this.autocompleteRequestId &&
  1901. this.getText() === snapshotText &&
  1902. this.state.cursorLine === snapshotLine &&
  1903. this.state.cursorCol === snapshotCol
  1904. );
  1905. }
  1906. private applyAutocompleteSuggestions(suggestions: AutocompleteSuggestions, state: "regular" | "force"): void {
  1907. this.autocompletePrefix = suggestions.prefix;
  1908. this.autocompleteList = this.createAutocompleteList(suggestions.prefix, suggestions.items);
  1909. const bestMatchIndex = this.getBestAutocompleteMatchIndex(suggestions.items, suggestions.prefix);
  1910. if (bestMatchIndex >= 0) {
  1911. this.autocompleteList.setSelectedIndex(bestMatchIndex);
  1912. }
  1913. this.autocompleteState = state;
  1914. }
  1915. private cancelAutocompleteRequest(): void {
  1916. this.autocompleteStartToken += 1;
  1917. if (this.autocompleteDebounceTimer) {
  1918. clearTimeout(this.autocompleteDebounceTimer);
  1919. this.autocompleteDebounceTimer = undefined;
  1920. }
  1921. this.autocompleteAbort?.abort();
  1922. this.autocompleteAbort = undefined;
  1923. }
  1924. private clearAutocompleteUi(): void {
  1925. this.autocompleteState = null;
  1926. this.autocompleteList = undefined;
  1927. this.autocompletePrefix = "";
  1928. }
  1929. private cancelAutocomplete(): void {
  1930. this.cancelAutocompleteRequest();
  1931. this.clearAutocompleteUi();
  1932. }
  1933. public isShowingAutocomplete(): boolean {
  1934. return this.autocompleteState !== null;
  1935. }
  1936. private updateAutocomplete(): void {
  1937. if (!this.autocompleteState || !this.autocompleteProvider) return;
  1938. this.requestAutocomplete({ force: this.autocompleteState === "force", explicitTab: false });
  1939. }
  1940. }