import { CustomEditor } from "@earendil-works/pi-coding-agent"; import { type AutocompleteProvider, decodeKittyPrintable, Editor, type EditorTheme, type Keybinding, matchesKey, type TUI, } from "@earendil-works/pi-tui"; import { dbg } from "./debug.ts"; import { closerFor, type Item, indentTarget, insideFence, isEmptyItem, isEmptyPair, leadingSpaces, looksCompletable, outdentTarget, pairAction, parseItem, } from "./text.ts"; const PASTE_START = "\x1b[200~"; const PASTE_END = "\x1b[201~"; const PASTE_MARKER = /\[paste #\d+ /u; type Keys = ConstructorParameters[2]; type Action = NonNullable< NonNullable>[1]>["action"] >; // Raw sequences fed to the base editor for primitive moves. Each candidate is // accepted only when the user's keybindings still map it to the wanted action. const SEQUENCES = { home: ["tui.editor.cursorLineStart", ["\x1b[H", "\x01"]], end: ["tui.editor.cursorLineEnd", ["\x1b[F", "\x05"]], left: ["tui.editor.cursorLeft", ["\x1b[D", "\x02"]], right: ["tui.editor.cursorRight", ["\x1b[C", "\x06"]], backspace: ["tui.editor.deleteCharBackward", ["\x7f", "\b"]], delete: ["tui.editor.deleteCharForward", ["\x1b[3~"]], killLine: ["tui.editor.deleteToLineStart", ["\x15"]], } as const satisfies Record; type Primitive = keyof typeof SEQUENCES; const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" }); function graphemeCount(text: string): number { let count = 0; for (const _ of segmenter.segment(text)) count++; return count; } function typedCharacter(data: string): string | undefined { const kitty = decodeKittyPrintable(data); if (kitty !== undefined) return kitty; if (data.length === 0 || data.includes("\x1b")) return undefined; const [first] = data; if (first === undefined || first.length !== data.length) return undefined; return data >= " " && data !== "\x7f" ? data : undefined; } /** * Prompt editor with small writing niceties. Every shortcut is conditional and * falls back to Pi's own behavior, so plain prose is never rewritten. */ export class KeysmashEditor extends CustomEditor { readonly #keys: Keys; readonly #tui: TUI; readonly #sequences = new Map(); #pasting = false; #jumping = false; #hasAutocomplete = false; #pendingIndent: { text: string; line: number; col: number } | undefined; constructor(tui: TUI, theme: EditorTheme, keybindings: Keys) { super(tui, theme, keybindings); this.#keys = keybindings; this.#tui = tui; for (const [name, [action, candidates]] of Object.entries(SEQUENCES) as [ Primitive, readonly [Keybinding, readonly string[]], ][]) { const found = candidates.find((data) => keybindings.matches(data, action), ); if (found !== undefined) this.#sequences.set(name, found); } } override setAutocompleteProvider(provider: AutocompleteProvider): void { this.#hasAutocomplete = true; super.setAutocompleteProvider({ triggerCharacters: provider.triggerCharacters ?? [], applyCompletion: (...args) => provider.applyCompletion(...args), shouldTriggerFileCompletion: (...args) => provider.shouldTriggerFileCompletion?.(...args) ?? true, getSuggestions: async (lines, line, col, options) => { const pending = this.#pendingIndent; const suggestions = await provider.getSuggestions( lines, line, col, options, ); // Native completion gets first refusal, including plain filenames. // Never indent in response to a cancelled or stale lookup. const cursor = this.getCursor(); if ( options.force && !options.signal.aborted && !suggestions?.items.length && pending !== undefined && this.#pendingIndent === pending && this.getText() === pending.text && cursor.line === pending.line && cursor.col === pending.col ) if (this.#shift(true)) this.#tui.requestRender(); return suggestions; }, }); } override handleInput(data: string): void { this.#pendingIndent = undefined; // Extension shortcuts outrank every nicety; running one here consumes the key. const raw = this.#passthrough(data) || (!this.onExtensionShortcut?.(data) && !this.#smart(data)); if (raw) super.handleInput(data); } // Keys bound to an app action, such as Alt+Enter for follow-up, stay Pi's. #claimedByApp(data: string, except?: string): boolean { for (const action of this.actionHandlers.keys()) if (action !== except && this.#keys.matches(data, action)) return true; return false; } // Paste streams and character-jump targets must reach the editor untouched. #passthrough(data: string): boolean { const start = data.lastIndexOf(PASTE_START); if (start !== -1) this.#pasting = true; if (this.#pasting) { if (data.indexOf(PASTE_END, Math.max(start, 0)) !== -1) this.#pasting = false; return true; } if (this.#jumping) { this.#jumping = false; return true; } if ( this.#keys.matches(data, "tui.editor.jumpForward") || this.#keys.matches(data, "tui.editor.jumpBackward") ) { this.#jumping = true; return true; } return this.isShowingAutocomplete(); } #smart(data: string): boolean { const keys = this.#keys; if ( this.#claimedByApp( data, matchesKey(data, "shift+tab") ? "app.thinking.cycle" : undefined, ) ) return false; if (this.#isNewline(data)) return this.#newline(data, false); if (this.#isBackslashEnter(data)) return this.#newline(data, true); if (keys.matches(data, "tui.input.tab")) { if (!this.#hasAutocomplete) return this.#shift(true); this.#pendingIndent = { text: this.getText(), ...this.getCursor() }; return false; } if (matchesKey(data, "shift+tab")) return this.#shift(false); if (keys.matches(data, "tui.editor.deleteCharBackward")) return this.#backspace(data); const typed = typedCharacter(data); return typed !== undefined && this.#type(data, typed); } #isNewline(data: string): boolean { if (this.#claimedByApp(data)) return false; return ( this.#keys.matches(data, "tui.input.newLine") || (data.charCodeAt(0) === 10 && data.length > 1) || data === "\x1b\r" || data === "\x1b[13;2~" || (data.length > 1 && data.includes("\x1b") && data.includes("\r")) || data === "\n" ); } // Terminals without Shift+Enter use "\" then Enter for a newline. #isBackslashEnter(data: string): boolean { if (this.disableSubmit || !this.#keys.matches(data, "tui.input.submit")) return false; const { line, col } = this.getCursor(); return col > 0 && this.getLines()[line]?.[col - 1] === "\\"; } #send(primitive: Primitive): boolean { const data = this.#sequences.get(primitive); if (data === undefined) return false; // Bypass CustomEditor so app shortcuts cannot claim these sequences. Editor.prototype.handleInput.call(this, data); return true; } #has(...primitives: Primitive[]): boolean { return primitives.every((name) => this.#sequences.has(name)); } #skip(reason: "missing-key" | "paste-marker"): false { dbg?.("edit.skip", { reason }); return false; } #done(action: Action): true { dbg?.("edit.apply", { action }); return true; } #newline(data: string, backslash: boolean): boolean { const { line, col } = this.getCursor(); const lines = this.getLines(); const raw = lines[line] ?? ""; // The editor drops the backslash when it turns Enter into a newline. const text = backslash ? raw.slice(0, col - 1) + raw.slice(col) : raw; const at = backslash ? col - 1 : col; const item = insideFence(lines, line) ? undefined : parseItem(text); if (item) { if (isEmptyItem(item) && at === text.length) return this.#leaveItem(item, lines, line, backslash); return at > item.prefix.length ? this.#continue(data, item.next, "continue") : false; } const indent = leadingSpaces(text); return indent > 0 && text.trim() !== "" && at > indent ? this.#continue(data, " ".repeat(indent), "keep-indent") : false; } #continue(data: string, prefix: string, action: Action): boolean { super.handleInput(data); const { line, col } = this.getCursor(); if (col === 0 && line > 0) this.insertTextAtCursor(prefix); return this.#done(action); } // Enter on an empty item steps out: one level up, or off the list. #leaveItem( item: Item, lines: readonly string[], line: number, backslash: boolean, ): boolean { if (!this.#has("killLine")) return this.#skip("missing-key"); if (backslash) this.#send("backspace"); const target = item.kind === "quote" ? undefined : outdentTarget(lines, line); if (target !== undefined && this.#reindent(target - item.indent)) return this.#done("outdent-empty"); this.#send("killLine"); return this.#done("exit"); } #shift(forward: boolean): boolean { const { line } = this.getCursor(); const lines = this.getLines(); const text = lines[line] ?? ""; const item = parseItem(text); if (!item || insideFence(lines, line)) return false; const { col } = this.getCursor(); if ( forward && col > item.prefix.length && looksCompletable(text.slice(0, col)) ) return false; const target = forward ? indentTarget(lines, line) : outdentTarget(lines, line); if (target === undefined) return false; return this.#reindent(target - item.indent) ? this.#done(forward ? "indent" : "outdent") : false; } // Change the current line's indent, keeping the cursor on the same text. #reindent(delta: number): boolean { if (delta === 0) return false; if ( !this.#has("home", "end", "right") || (delta < 0 && !this.#has("killLine")) ) return this.#skip("missing-key"); const { line, col } = this.getCursor(); const text = this.getLines()[line] ?? ""; if (PASTE_MARKER.test(text)) return this.#skip("paste-marker"); if (delta < 0 && leadingSpaces(text) < -delta) return false; const atEnd = col === text.length; const before = atEnd ? 0 : graphemeCount(text.slice(0, col)); this.#send("home"); let rights = before; if (delta > 0) { this.insertTextAtCursor(" ".repeat(delta)); } else { // One kill is one undo step; deleting space by space is several. for (let i = 0; i < -delta; i++) this.#send("right"); this.#send("killLine"); rights = Math.max(0, before + delta); } if (atEnd) this.#send("end"); else for (let i = 0; i < rights; i++) this.#send("right"); return true; } #backspace(data: string): boolean { const { line, col } = this.getCursor(); const lines = this.getLines(); const text = lines[line] ?? ""; const item = insideFence(lines, line) ? undefined : parseItem(text); // Backspace on a bare marker steps out like Enter does. if (item && isEmptyItem(item) && col === text.length) return this.#leaveItem(item, lines, line, false); if ( this.#has("delete") && isEmptyPair(text.slice(0, col), text.slice(col)) ) { super.handleInput(data); this.#send("delete"); return this.#done("unpair"); } return false; } #type(data: string, typed: string): boolean { const { line, col } = this.getCursor(); const text = this.getLines()[line] ?? ""; const action = pairAction(typed, text.slice(0, col), text.slice(col)); if (action === "overtype") { if (!this.#send("right")) return false; return this.#done("overtype"); } if (action === "pair" && this.#has("left")) { super.handleInput(data); this.insertTextAtCursor(closerFor(typed)); this.#send("left"); return this.#done("pair"); } return false; } }