mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-17 13:01:24 +00:00
* fix(autocomplete): sync ghost text to live input on every keystroke Ghost text was displayed based on whatever input was passed to GhostTextAddon.show() at fetch time. Between a user's keystroke and the next debounced fetchSuggestions firing (~100ms), the on-screen line had already advanced one character but ghost.getGhostText() still returned the pre-update tail. Pressing → during that window pasted the stale tail on top of the new char — e.g. type "do", suggestion shows "cker ls"; type "c", accept immediately → "doc" + "cker ls" lands as "doccker ls" instead of the expected "docker ls". Two-layer fix: 1. New GhostTextAddon.adjustToInput(newInput) that re-renders the ghost against a fresh input without waiting for a new fetch: shrinks / grows the tail if the suggestion still prefix-matches, hides otherwise. Called from handleInput after every buffer mutation (printable, backspace, Ctrl-W, paste tail) when the buffer is reliable. Unreliable-buffer paths skip the call to avoid making the ghost lie. 2. Defense-in-depth at both ghost-accept sites (→ and Ctrl-→): recompute the tail against the live typed buffer instead of trusting getGhostText's show()-time state. If the suggestion no longer prefixes the live buffer, hide without writing. Ctrl-→ additionally resyncs ghost.show() to the live buffer before picking the next word so getNextWord operates on an up-to-date tail. * fix(autocomplete): defer ghost text updates to the next xterm render The previous pass made adjustToInput re-show the ghost synchronously on every keystroke, but xterm hasn't echoed the triggering char yet at that moment — cursorX is still the pre-keystroke position. Painting the shrunken tail there left it visibly overlapping with the char xterm was about to draw, and the ghost only snapped to the right column on the next onRender tick. That one-frame overlap is the "jitter" the reporter still saw. Switch adjustToInput to a defer-and-reapply pattern: - On every keystroke that should re-align the ghost, stash the desired input in pendingInput and hide the element immediately. The transient blank frame is preferable to an overlap glyph. - The existing term.onRender listener now checks for a pending update first: by that tick xterm has processed the echo, cursorX has advanced, and we can paint the new tail at the correct column via applyInputUpdate. - New isActive() exposes "has a live suggestion even if hidden waiting for render" so a fast "type + →" / "type + Ctrl-→" sequence in the hide-until-render gap still hits the accept branch and grabs the recomputed tail from the live buffer. show() and hide() clear pendingInput so an explicit state change supersedes any queued adjust. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): restore ghost text, predict-anchor-shift on each keystroke The previous refactor broke inline completion entirely: 1. useTerminalAutocomplete force-disabled showGhostText whenever showPopupMenu was on — and both are true by default, so ghost never rendered. 2. GhostTextAddon put its overlay container *under* xterm's screen via insertBefore + no z-index. xterm's default renderer paints theme.background across every cell including empty ones, so the ghost was fully occluded by the canvas even when the hook *did* call show(). Fixes both issues and lands the correct per-keystroke strategy the jitter report was asking for: - Drop the showGhostText-vs-showPopupMenu gate; respect user settings. - Put the ghost container back on top of the screen (appendChild + z-index 1). - Track anchorInputLength at show() time. adjustToInput now advances the ghost's left by (newInput.length - anchorInputLength) cells *synchronously* — i.e. it predicts where xterm's cursor will land once the echo arrives, instead of re-reading the live cursorX that hasn't advanced yet. textContent is trimmed in the same call, so ghost + real-input stay aligned across SSH echo latency with no one-frame overlap or blank gap. - Updated GhostTextAddon.test.ts expectations for the new behavior (and cast the fake-document through unknown to fix the pre-existing TS error). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): address ghost text review feedback Follow-ups on the predict-anchor-shift from the previous commit, based on a code-reviewer pass: - Backspace / Ctrl-W de-sync: updatePosition's Math.max(0, ...) was clamping the delta to zero when newInput shrank below the show-time input length. The ghost then stayed pinned at the original anchor column while the real cursor walked back left, leaving a gap between the cursor and the ghost. Let the delta go negative so the ghost tracks the cursor backwards; clamp the resulting left at 0 instead of clamping the delta. - Resize staleness: onResize now also resets lastLeft/lastTop and re-renders, so the dedup cache in updatePosition doesn't hide a now-stale pixel coordinate after xterm recomputes cell dims. - Added a regression test for the backspace path covering both the step-back-below-anchor case and the clamp-at-0-on-overshoot case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): don't accept whole suggestion when buffer is unreliable Codex flagged (#815 P1 ×2) that the live-buffer recompute on → and Ctrl-→ falls into a degenerate path when typedBufferReliableRef is false. My previous cut used live = "" as the fallback, but fullSuggestion.startsWith("") is always true — so: - → would write the entire suggestion over whatever is on the line (post history-recall ↑, Ctrl-R reverse search, etc.). - Ctrl-→ would reanchor the ghost at the start and getNextWord would hand back the first token, duplicating leading content on top of the recalled command. When the buffer is unreliable, empty buffer ≠ empty line — the line has content we're not tracking. Fall back to the ghost's own cached state instead of recomputing: - → reliable: recompute tail vs live buffer, flip buffer to the accepted suggestion, reliability back on. - → unreliable: use ghost.getGhostText() (shown-at-show-time tail) and don't touch the buffer/reliability flag. - Ctrl-→ reliable: resync ghost to live, then proceed as before. - Ctrl-→ unreliable: skip the resync, derive the shrink baseline from fullSuggestion - current-ghost-tail so the next-word logic still works off whatever the ghost was actually showing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): hide ghost on single-byte cursor/recall control chars Reviewer caught that Ctrl-P / Ctrl-N / Ctrl-R / Ctrl-A / Ctrl-E and friends flip typedBufferReliableRef to false but don't hide the ghost — leaving it rendering a tail tied to the pre-recall line. The previous commit's unreliable-→ fallback then reads that stale tail via ghost.getGhostText() and writes it onto the recalled line, reproducing the very duplication class the fallback was meant to prevent (just triggered by Ctrl-P instead of ↑). Mirror what the escape-sequence branch already does: clearState() + return. Once the ghost is hidden, ghost.isActive() is false at the → and Ctrl-→ gates, so the accept-path doesn't fire at all until a fresh fetchSuggestions re-anchors it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): drop accepted-command cache on cursor/recall keys Reviewer pointed out that the early returns in the single-byte ctrl-char and escape-sequence branches leave lastAcceptedCommandRef untouched. If the user accepts a suggestion via → and then immediately hits Ctrl-R or ↑ to pick a different command, the fast Enter path (lines ~611-612) still reads the cached accepted command and records it — logging the old suggestion instead of whichever command the reverse-search or history-recall actually ran. Null lastAcceptedCommandRef at the top of both branches (same place we hide the ghost and flip reliability off) so accept + recall + Enter records the recalled command, not the stale accept. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): also null accepted-command cache on Ctrl-C / Ctrl-U Reviewer flagged this class of bug is still reachable via Ctrl-C / Ctrl-U. The branch handling those kills the zle line, but the early return leaves lastAcceptedCommandRef pointing at a command that is no longer on the line: accept "git status" via → → Ctrl-C to abandon → type "ls" → Enter logs "git status" via the fast path instead of "ls". Same one-liner as the other early-return branches: null the cache alongside clearState(). Now the cache's lifetime truly ends at any event that invalidates the accept. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): null accepted-command cache on bracketed paste too Fifth-pass reviewer caught the last symmetric gap: the bracketed-paste branch appends pasted bytes to the buffer but leaves lastAcceptedCommandRef set. Accept "git status" via → then bracketed-paste " --short" (no embedded newline), press Enter — the fast path at line 611 still reads "git status" and logs that instead of "git status --short". Mirror the non-bracketed paste branch: null the cache before clearState() returns. All handleInput paths that extend or invalidate the line now consistently end the cache's lifetime. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): predict ghost column by cell width + wrap at EOL Review caught two geometry bugs in GhostTextAddon.updatePosition that only surfaced outside the ASCII happy path: - CJK / fullwidth / emoji glyphs occupy two xterm cells but the predictor advanced by one char-length per code unit, so ghost drifted one cell left for every wide char typed and visibly overlapped the user's glyph. - When the predicted column crossed term.cols the real cursor wrapped to the next row, but the predictor just piled more pixels onto `left` — ghost walked off the right edge instead of following onto the next line. Fix both by switching from code-unit count to a small EAW-style width classifier, then applying row wrapping via col = (anchorX + cellDelta) % cols rowOffset = Math.floor((anchorX + cellDelta) / cols) against the current term.cols. Fake terminal in the test suite now exposes cols/rows so the unit tests can exercise both invariants: - "advances the anchor by two cells when a CJK glyph is typed" - "wraps the ghost to the next row when the predicted column crosses cols" Known limitation the review already flagged: on backspace-after-wide we don't have per-grapheme widths to reverse exactly, so the negative delta falls back to code-unit width on the deleted slice. The slice is `currentSuggestion[currentInput.length..anchorInputLength]` which is the same text the user would have typed, so it's correct when only ASCII edits; wide-char backspace can still drift by one cell. Fixing this cleanly needs a per-grapheme buffer and is out of scope. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): honor showGhostText toggle while a ghost is on screen Codex flagged (#815 P2) that fetchSuggestions gates new ghost shows on settingsRef.current.showGhostText, but handleInput's adjustToInput call had no such guard. A ghost that was already active at the moment the user turned showGhostText off would keep tracking the typed buffer via adjustToInput on every keystroke, so the "disabled" setting only took hold after some unrelated path called clearState(). Two-part fix: - Add a useEffect watching settings.showGhostText. When it flips false, hide the active ghost immediately so the disabled setting applies to whatever was already on screen. - Gate the adjustToInput call in handleInput behind settingsRef.current.showGhostText too, so subsequent keystrokes under the disabled setting don't try to move or re-show a ghost. Codex's earlier P2 about wrap-at-EOL on line 236 is already resolved bye61f0e8b(predict-column-with-wrap + CJK width); that comment is against an older commit. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): self-heal stale anchor + handle backward-wrap on delete Codex flagged two real geometry gaps in the predict-anchor-shift math: 1. Stale anchor on high-latency shells. show() captures cursorX from xterm at debounce-fire time, but under SSH round-trip latency the user's latest keystroke may not have echoed yet — cursorX is still the pre-echo column. With updatePosition now purely anchor-based (no longer reading live cursorX on every render), that stale anchor becomes frozen; the ghost stays one-plus cells off for the whole suggestion session until another show() rebuilds it. 2. Backspace crossing a wrapped row boundary. Math.max(0, ...) clamped targetCol at zero, so deletions past column 0 stayed pinned to the current row instead of wrapping back to the previous row — exactly the symmetric case the forward wrap added ine61f0e8bhandles. Fixes: - Self-heal in updatePosition: while no adjustToInput has moved us from the show-time baseline (currentInput.length === anchorInputLength), re-read live cursorX/Y each render tick. Once the user starts typing the anchor is frozen and delta math takes over. - Normalize the wrap for negative targetCol: `col = targetCol % cols` plus `if (col < 0) col += cols`, `rowOffset = Math.floor(targetCol/cols)` naturally yielding -1 on underflow. Clamp `top` at row 0 so a runaway negative doesn't render above the terminal. Two new tests cover both invariants: - "self-heals a stale anchor on render while no adjustToInput has fired" - "wraps the ghost to the previous row when deletion crosses a row boundary" Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(autocomplete): restore ghost/popup mutual-exclusivity guard in hook Codex flagged (#815 P2) that dropping the popup-wins-over-ghost normalization inside useTerminalAutocomplete weakens the hook's own defensive invariant. The repo enforces mutual exclusivity in two places already — SettingsTerminalTab toggles one off when the other turns on, and domain/models.ts normalizes stored settings so autocompletePopupMenu === true forces autocompleteGhostText to false — so on the normal Terminal.tsx → store path only one of the two arrives as true. But the hook's own defaults (DEFAULT_AUTOCOMPLETE_SETTINGS) have both flags true, and any caller that builds settings directly from those defaults (tests, future embedders) would end up rendering popup + inline ghost simultaneously against the repo-wide contract. Restore the guard, comment it as defensive rather than load-bearing so future readers don't mistake it for the hiding-invisible-ghost bug I was fixing last time (that was really the insertBefore / z-index issue in GhostTextAddon.ts, not this normalization). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
326 lines
12 KiB
TypeScript
326 lines
12 KiB
TypeScript
/**
|
|
* Ghost Text addon for xterm.js.
|
|
* Renders inline suggestion text after the cursor in a dimmed style,
|
|
* similar to fish shell's autosuggestions.
|
|
*
|
|
* Uses a CSS overlay positioned relative to the terminal cursor,
|
|
* avoiding modification of the terminal buffer.
|
|
*/
|
|
|
|
import type { Terminal as XTerm, IDisposable } from "@xterm/xterm";
|
|
import { getXTermCellDimensions, invalidateCellDimensionCache } from "./xtermUtils";
|
|
|
|
/**
|
|
* Minimal East-Asian-Width-style classifier: returns 2 for wide glyphs
|
|
* (CJK ideographs, fullwidth forms, most emoji, hangul syllables) and
|
|
* 1 otherwise. Not full wcwidth — just enough to keep the predicted
|
|
* ghost column from drifting by one cell per CJK char typed.
|
|
*/
|
|
function codePointCellWidth(cp: number): number {
|
|
if (
|
|
(cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
|
|
(cp >= 0x2e80 && cp <= 0x303e) || // CJK Radicals, Kangxi
|
|
(cp >= 0x3041 && cp <= 0x33ff) || // Hiragana, Katakana, CJK Compat
|
|
(cp >= 0x3400 && cp <= 0x4dbf) || // CJK Extension A
|
|
(cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified Ideographs
|
|
(cp >= 0xa000 && cp <= 0xa4cf) || // Yi
|
|
(cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables
|
|
(cp >= 0xf900 && cp <= 0xfaff) || // CJK Compat Ideographs
|
|
(cp >= 0xfe30 && cp <= 0xfe4f) || // CJK Compat Forms
|
|
(cp >= 0xff00 && cp <= 0xff60) || // Fullwidth forms
|
|
(cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth signs
|
|
(cp >= 0x1f300 && cp <= 0x1faff) || // Emoji blocks
|
|
(cp >= 0x20000 && cp <= 0x3fffd) // CJK Extension B-F, G
|
|
) {
|
|
return 2;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
function stringCellWidth(s: string): number {
|
|
let w = 0;
|
|
for (const ch of s) {
|
|
const cp = ch.codePointAt(0) ?? 0;
|
|
w += codePointCellWidth(cp);
|
|
}
|
|
return w;
|
|
}
|
|
|
|
export class GhostTextAddon implements IDisposable {
|
|
private term: XTerm | null = null;
|
|
private ghostElement: HTMLSpanElement | null = null;
|
|
private containerElement: HTMLDivElement | null = null;
|
|
private currentSuggestion: string = "";
|
|
private currentInput: string = "";
|
|
/** Cursor column captured at show() time — the anchor the ghost was painted from. */
|
|
private anchorCursorX = 0;
|
|
/** Cursor row captured at show() time. */
|
|
private anchorCursorY = 0;
|
|
/** Length of currentInput at show() time — lets adjustToInput shift left
|
|
* by (newInput.length - anchorInputLength) cells without having to
|
|
* re-read xterm's cursorX (which hasn't advanced yet at keystroke time). */
|
|
private anchorInputLength = 0;
|
|
private disposed = false;
|
|
private disposables: IDisposable[] = [];
|
|
private lastLeft = -1;
|
|
private lastTop = -1;
|
|
|
|
activate(term: XTerm): void {
|
|
this.term = term;
|
|
|
|
const termElement = term.element;
|
|
if (!termElement) return;
|
|
|
|
this.containerElement = document.createElement("div");
|
|
this.containerElement.className = "xterm-ghost-text-container";
|
|
Object.assign(this.containerElement.style, {
|
|
position: "absolute",
|
|
top: "0",
|
|
left: "0",
|
|
width: "100%",
|
|
height: "100%",
|
|
pointerEvents: "none",
|
|
overflow: "hidden",
|
|
// Sit above xterm's canvas — xterm's default renderer paints its
|
|
// theme.background across every cell including empty ones, so a
|
|
// ghost placed beneath the canvas would be completely occluded.
|
|
zIndex: "1",
|
|
});
|
|
|
|
this.ghostElement = document.createElement("span");
|
|
this.ghostElement.className = "xterm-ghost-text";
|
|
Object.assign(this.ghostElement.style, {
|
|
position: "absolute",
|
|
opacity: "0.4",
|
|
pointerEvents: "none",
|
|
whiteSpace: "pre",
|
|
fontFamily: "inherit",
|
|
fontSize: "inherit",
|
|
lineHeight: "inherit",
|
|
color: "inherit",
|
|
display: "none",
|
|
});
|
|
|
|
this.containerElement.appendChild(this.ghostElement);
|
|
|
|
const screenEl = termElement.querySelector(".xterm-screen");
|
|
if (screenEl) {
|
|
screenEl.appendChild(this.containerElement);
|
|
} else {
|
|
termElement.appendChild(this.containerElement);
|
|
}
|
|
|
|
this.disposables.push(
|
|
term.onRender(() => {
|
|
if (this.isVisible()) {
|
|
this.updatePosition();
|
|
}
|
|
}),
|
|
);
|
|
|
|
// Invalidate cell dimension cache on resize so measurements stay
|
|
// accurate, and force a pixel-coord recompute on the next render —
|
|
// otherwise the lastLeft/lastTop short-circuit in updatePosition
|
|
// would keep the ghost at stale pixel coordinates until the user
|
|
// typed again.
|
|
this.disposables.push(
|
|
term.onResize(() => {
|
|
invalidateCellDimensionCache();
|
|
this.lastLeft = -1;
|
|
this.lastTop = -1;
|
|
if (this.isVisible()) this.updatePosition();
|
|
}),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Show ghost text suggestion.
|
|
* @param fullSuggestion The complete suggested command
|
|
* @param currentInput The text the user has typed so far
|
|
*/
|
|
show(fullSuggestion: string, currentInput: string): void {
|
|
if (this.disposed || !this.ghostElement || !this.term) return;
|
|
|
|
const ghostText = fullSuggestion.startsWith(currentInput)
|
|
? fullSuggestion.substring(currentInput.length)
|
|
: "";
|
|
|
|
if (!ghostText) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
|
|
this.currentSuggestion = fullSuggestion;
|
|
this.currentInput = currentInput;
|
|
this.anchorCursorX = this.term.buffer.active.cursorX;
|
|
this.anchorCursorY = this.term.buffer.active.cursorY;
|
|
this.anchorInputLength = currentInput.length;
|
|
// Force position recalc since the text also changed.
|
|
this.lastLeft = -1;
|
|
this.lastTop = -1;
|
|
|
|
this.updatePosition();
|
|
this.ghostElement.textContent = ghostText;
|
|
this.ghostElement.style.display = "block";
|
|
// Set font properties once per show (not per frame in updatePosition)
|
|
this.ghostElement.style.fontSize = `${this.term.options.fontSize}px`;
|
|
this.ghostElement.style.fontFamily = this.term.options.fontFamily || "inherit";
|
|
}
|
|
|
|
hide(): void {
|
|
if (this.ghostElement) {
|
|
this.ghostElement.style.display = "none";
|
|
this.ghostElement.textContent = "";
|
|
}
|
|
this.currentSuggestion = "";
|
|
this.currentInput = "";
|
|
this.anchorInputLength = 0;
|
|
}
|
|
|
|
/**
|
|
* Re-align the ghost against a freshly-updated user input synchronously.
|
|
* Called from handleInput on every keystroke that mutates the typed
|
|
* buffer so ghost text never falls out of sync with what the user has
|
|
* actually typed.
|
|
*
|
|
* Implementation relies on the predict-anchor-shift trick rather than
|
|
* re-reading xterm's live cursorX: xterm hasn't echoed the triggering
|
|
* keystroke yet at this point, so cursorX still points at the
|
|
* pre-keystroke column. Instead we track the cursor column captured
|
|
* at show() time and advance the ghost's left by the number of chars
|
|
* typed since — so the tail aligns with where the real cursor *will*
|
|
* land once the echo arrives, even across SSH round-trip latency.
|
|
*/
|
|
adjustToInput(newInput: string): void {
|
|
if (this.disposed || !this.ghostElement || !this.currentSuggestion) return;
|
|
if (!this.currentSuggestion.startsWith(newInput)) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
this.currentInput = newInput;
|
|
const ghostText = this.currentSuggestion.substring(newInput.length);
|
|
if (!ghostText) {
|
|
this.hide();
|
|
return;
|
|
}
|
|
// Force position recomputation — updatePosition skips DOM writes
|
|
// when the left/top cache hasn't changed, but we also need the new
|
|
// textContent to flush.
|
|
this.lastLeft = -1;
|
|
this.lastTop = -1;
|
|
this.ghostElement.textContent = ghostText;
|
|
this.updatePosition();
|
|
this.ghostElement.style.display = "block";
|
|
}
|
|
|
|
getSuggestion(): string {
|
|
return this.currentSuggestion;
|
|
}
|
|
|
|
isVisible(): boolean {
|
|
return !!(this.ghostElement && this.ghostElement.style.display !== "none" &&
|
|
this.currentSuggestion);
|
|
}
|
|
|
|
/**
|
|
* True when the ghost has a live suggestion even if it's momentarily
|
|
* shown underneath the real text while the user keeps typing within
|
|
* the prediction. Accept-path gates should use this instead of
|
|
* isVisible() so the suggestion remains available even while its
|
|
* leading characters are fully covered by real glyphs.
|
|
*/
|
|
isActive(): boolean {
|
|
return !this.disposed && !!this.currentSuggestion;
|
|
}
|
|
|
|
getGhostText(): string {
|
|
if (!this.currentSuggestion || !this.currentInput) return "";
|
|
return this.currentSuggestion.startsWith(this.currentInput)
|
|
? this.currentSuggestion.substring(this.currentInput.length)
|
|
: "";
|
|
}
|
|
|
|
getNextWord(): string {
|
|
const ghost = this.getGhostText();
|
|
if (!ghost) return "";
|
|
|
|
const trimmed = ghost.replace(/^\s+/, "");
|
|
const leadingSpace = ghost.length - trimmed.length;
|
|
|
|
if (trimmed.length === 0) return ghost; // Only whitespace
|
|
|
|
// Search for word boundary starting from index 1 (skip leading separator chars like /)
|
|
const wordEnd = trimmed.substring(1).search(/[\s/\\-]/);
|
|
if (wordEnd < 0) return ghost; // Single word, accept all
|
|
|
|
// Include leading whitespace + the word up to (and including) the separator
|
|
return ghost.substring(0, leadingSpace + 1 + wordEnd + 1);
|
|
}
|
|
|
|
private updatePosition(): void {
|
|
if (!this.term || !this.ghostElement) return;
|
|
|
|
// Self-heal a stale anchor: when show() fires during the SSH
|
|
// keystroke→echo gap, cursorX captured there is still the
|
|
// pre-echo column. While no adjustToInput has moved us from the
|
|
// show-time baseline, re-read live cursor on each render tick so
|
|
// the anchor snaps to the echoed position once it arrives.
|
|
if (this.currentInput.length === this.anchorInputLength) {
|
|
this.anchorCursorX = this.term.buffer.active.cursorX;
|
|
this.anchorCursorY = this.term.buffer.active.cursorY;
|
|
}
|
|
|
|
const dims = getXTermCellDimensions(this.term);
|
|
|
|
// Advance (or walk back) the anchor column by the cell width of
|
|
// whatever the user has typed since show() was called. Using cell
|
|
// width (not code-unit length) lets CJK / emoji / fullwidth glyphs
|
|
// advance by 2 cells instead of 1. Backspace / Ctrl-W produces a
|
|
// negative delta by shrinking currentInput below anchorInputLength.
|
|
const cellDelta = this.currentInput.length >= this.anchorInputLength
|
|
? stringCellWidth(this.currentInput.slice(this.anchorInputLength))
|
|
: -stringCellWidth(
|
|
// currentSuggestion[0..anchorInputLength] equals what was typed
|
|
// when show() fired (prefix-match invariant), so its slice gives
|
|
// the correct cell widths for the deleted glyphs.
|
|
this.currentSuggestion.slice(this.currentInput.length, this.anchorInputLength),
|
|
);
|
|
const cols = Math.max(1, this.term.cols);
|
|
const targetCol = this.anchorCursorX + cellDelta;
|
|
// Wrap the predicted cursor position across line boundaries in both
|
|
// directions — the real xterm cursor wraps to the next row once it
|
|
// crosses cols forward, and to the previous row when a deletion
|
|
// crosses back past column 0. JS `%` returns negative for negative
|
|
// dividends, so normalize both col and rowOffset explicitly.
|
|
let col = targetCol % cols;
|
|
let rowOffset = Math.floor(targetCol / cols);
|
|
if (col < 0) {
|
|
col += cols;
|
|
}
|
|
// Clamp to the visible top row so a runaway negative delta (e.g.
|
|
// deleted past the prompt) doesn't render above the terminal.
|
|
const top = Math.max(0, this.anchorCursorY + rowOffset) * dims.height;
|
|
const left = col * dims.width;
|
|
|
|
// Skip DOM writes if position hasn't changed (avoids unnecessary style recalc)
|
|
if (left === this.lastLeft && top === this.lastTop) return;
|
|
this.lastLeft = left;
|
|
this.lastTop = top;
|
|
|
|
this.ghostElement.style.left = `${left}px`;
|
|
this.ghostElement.style.top = `${top}px`;
|
|
this.ghostElement.style.lineHeight = `${dims.height}px`;
|
|
this.ghostElement.style.height = `${dims.height}px`;
|
|
}
|
|
|
|
dispose(): void {
|
|
this.disposed = true;
|
|
for (const d of this.disposables) d.dispose();
|
|
this.disposables = [];
|
|
this.containerElement?.remove();
|
|
this.containerElement = null;
|
|
this.ghostElement = null;
|
|
this.term = null;
|
|
}
|
|
}
|