diff --git a/packages/tui/src/prompt/part.ts b/packages/tui/src/prompt/part.ts index 18c6534f6f0..aee23d30333 100644 --- a/packages/tui/src/prompt/part.ts +++ b/packages/tui/src/prompt/part.ts @@ -3,9 +3,17 @@ import { promptOffsetIndex } from "./display" export function expandPastedTextPlaceholders( text: string, - pasted: readonly { text: string; source: { text: string } }[], + pasted: readonly { text: string; source: { text: string; start?: number } }[], ) { - return pasted.reduce((result, part) => result.replace(part.source.text, part.text), text) + let cursor = 0 + let result = "" + for (const part of pasted.toSorted((a, b) => (a.source.start ?? 0) - (b.source.start ?? 0))) { + const index = text.indexOf(part.source.text, cursor) + if (index === -1) continue + result += text.slice(cursor, index) + part.text + cursor = index + part.source.text.length + } + return result + text.slice(cursor) } export function expandTrackedPastedText( diff --git a/packages/tui/test/prompt/part.test.ts b/packages/tui/test/prompt/part.test.ts index ab76f7822e5..29a5ecab615 100644 --- a/packages/tui/test/prompt/part.test.ts +++ b/packages/tui/test/prompt/part.test.ts @@ -1,6 +1,6 @@ import { expect, test } from "bun:test" import { measureEditText } from "@opentui/core" -import { expandTrackedPastedText } from "../../src/prompt/part" +import { expandPastedTextPlaceholders, expandTrackedPastedText } from "../../src/prompt/part" const widthMethod = "wcwidth" const measure = (text: string) => measureEditText(text, { widthMethod }) @@ -21,3 +21,20 @@ test.each([ }) expect(expandTrackedPastedText(pieces.join(marker), ranges, widthMethod)).toBe(pieces.join(pasted)) }) + +test("expands clipboard placeholders literally in document order without re-matching expanded text", () => { + const first = "echo $$ && replace('$&', `$`cmd``, $'\\n') and literal [Pasted ~4 lines]" + const second = "second\npasted\nfour\nlines" + expect( + expandPastedTextPlaceholders("prefix [Pasted ~3 lines] middle [Pasted ~4 lines] suffix", [ + { text: first, source: { text: "[Pasted ~3 lines]", start: 7 } }, + { text: second, source: { text: "[Pasted ~4 lines]", start: 32 } }, + ]), + ).toBe(`prefix ${first} middle ${second} suffix`) + expect( + expandPastedTextPlaceholders("prefix [Pasted ~3 lines] middle [Pasted ~3 lines] suffix", [ + { text: second, source: { text: "[Pasted ~3 lines]", start: 32 } }, + { text: first, source: { text: "[Pasted ~3 lines]", start: 7 } }, + ]), + ).toBe(`prefix ${first} middle ${second} suffix`) +})