import type { PromptBuffer } from "./buffer.js"; function sameSnapshot(left: PromptBuffer, right: PromptBuffer): boolean { return ( left.cursor.line === right.cursor.line && left.cursor.column === right.cursor.column && left.lines.length === right.lines.length && left.lines.every((line, index) => line === right.lines[index]) ); } function cloneSnapshot(buffer: PromptBuffer): PromptBuffer { return { lines: [...buffer.lines], cursor: { ...buffer.cursor }, ...(buffer.pasteMarkerIds === undefined ? {} : { pasteMarkerIds: new Set(buffer.pasteMarkerIds) }), }; } /** Private Readline undo history, independent of Pi's native editor stack. */ export class ReadlineUndoStack { readonly #snapshots: PromptBuffer[] = []; record(buffer: PromptBuffer, current?: PromptBuffer): void { const snapshot = cloneSnapshot(buffer); if (current !== undefined && sameSnapshot(snapshot, current)) return; if ( this.#snapshots.some( (entry, index) => index === this.#snapshots.length - 1 && sameSnapshot(entry, snapshot), ) ) return; this.#snapshots.push(snapshot); } undo(): PromptBuffer | undefined { return this.#snapshots.pop(); } clear(): void { this.#snapshots.length = 0; } }