From c1ee7d4b0babd0de0d1198a7c1ece2a387c97c0d Mon Sep 17 00:00:00 2001 From: Marijn Haverbeke Date: Sat, 30 Nov 2024 09:54:28 +0100 Subject: [PATCH] Properly shorten replace markers when out of range for the query FIX: When replacing a regexp match, don't expand multi-digit replacement markers to numbers beyond the captured group count in the query. Closes https://github.com/codemirror/dev/issues/1477 --- src/search.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/search.ts b/src/search.ts index e454121..59bf579 100644 --- a/src/search.ts +++ b/src/search.ts @@ -298,11 +298,15 @@ class RegExpQuery extends QueryType { } getReplacement(result: RegExpResult) { - return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => - i == "$" ? "$" - : i == "&" ? result.match[0] - : i != "0" && +i < result.match.length ? result.match[i] - : m) + return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => { + if (i == "&") return result.match[0] + if (i == "$") return "$" + for (let l = i.length; l > 0; l--) { + let n = +i.slice(0, l) + if (n > 0 && n < result.match.length) return result.match[n] + i.slice(l) + } + return m + }) } matchAll(state: EditorState, limit: number) {