Elffuss BraidHub

kikocis/continue public

Merge pull request #6464 from continuedev/nate/search-and-replace-improvements

refactor findSearchMatch
Changeset4073142854bc03c10a7a1b5d4ebd790a7cff8621f67f39f4be8ec31f88b3fbba
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-07-05 10:03 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-05 10:03 -07:00
Parentsf840a2b4e8a4, 3ecf862e2425

Browse the files at this changeset

5 files changed

modified core/edit/searchAndReplace/findSearchMatch.test.ts +593 −211
@@ -1,319 +1,546 @@
11 import { findSearchMatch } from "./findSearchMatch";
22
3-describe("findSearchMatch", () => {
4- describe("Exact matches", () => {
5- it("should find exact match at the beginning of file", () => {
6- const fileContent = `function hello() {
3+describe("Exact matches", () => {
4+ it("should find exact match at the beginning of file", () => {
5+ const fileContent = `function hello() {
76 console.log("world");
87 }`;
9- const searchContent = `function hello() {
8+ const searchContent = `function hello() {
109 console.log("world");
1110 }`;
1211
13- const result = findSearchMatch(fileContent, searchContent);
12+ const result = findSearchMatch(fileContent, searchContent);
1413
15- expect(result).toEqual({
16- startIndex: 0,
17- endIndex: fileContent.length,
18- });
14+ expect(result).toEqual({
15+ startIndex: 0,
16+ endIndex: fileContent.length,
17+ strategyName: "exactMatch",
1918 });
19+ });
2020
21- it("should find exact match in the middle of file", () => {
22- const fileContent = `const a = 1;
21+ it("should find exact match in the middle of file", () => {
22+ const fileContent = `const a = 1;
2323 function hello() {
2424 console.log("world");
2525 }
2626 const b = 2;`;
27- const searchContent = `function hello() {
27+ const searchContent = `function hello() {
2828 console.log("world");
2929 }`;
3030
31- const result = findSearchMatch(fileContent, searchContent);
31+ const result = findSearchMatch(fileContent, searchContent);
3232
33- expect(result).toEqual({
34- startIndex: 13, // After "const a = 1;\n"
35- endIndex: 13 + searchContent.length,
36- });
33+ expect(result).toEqual({
34+ startIndex: 13, // After "const a = 1;\n"
35+ endIndex: 13 + searchContent.length,
36+ strategyName: "exactMatch",
3737 });
38+ });
3839
39- it("should find exact match at the end of file", () => {
40- const fileContent = `const a = 1;
40+ it("should find exact match at the end of file", () => {
41+ const fileContent = `const a = 1;
4142 function hello() {
4243 console.log("world");
4344 }`;
44- const searchContent = `function hello() {
45+ const searchContent = `function hello() {
4546 console.log("world");
4647 }`;
4748
48- const result = findSearchMatch(fileContent, searchContent);
49+ const result = findSearchMatch(fileContent, searchContent);
4950
50- expect(result).toEqual({
51- startIndex: 13, // After "const a = 1;\n"
52- endIndex: fileContent.length,
53- });
51+ expect(result).toEqual({
52+ startIndex: 13, // After "const a = 1;\n"
53+ endIndex: fileContent.length,
54+ strategyName: "exactMatch",
5455 });
56+ });
5557
56- it("should find exact match with single line", () => {
57- const fileContent = `const a = 1;
58+ it("should find exact match with single line", () => {
59+ const fileContent = `const a = 1;
5860 const b = 2;
5961 const c = 3;`;
60- const searchContent = `const b = 2;`;
62+ const searchContent = `const b = 2;`;
6163
62- const result = findSearchMatch(fileContent, searchContent);
64+ const result = findSearchMatch(fileContent, searchContent);
6365
64- expect(result).toEqual({
65- startIndex: 13, // After "const a = 1;\n"
66- endIndex: 13 + searchContent.length,
67- });
66+ expect(result).toEqual({
67+ startIndex: 13, // After "const a = 1;\n"
68+ endIndex: 13 + searchContent.length,
69+ strategyName: "exactMatch",
6870 });
71+ });
6972
70- it("should find exact match with whitespace preserved", () => {
71- const fileContent = `function test() {
73+ it("should find exact match with whitespace preserved", () => {
74+ const fileContent = `function test() {
7275 const x = 1;
7376 const y = 2;
7477 }`;
75- const searchContent = ` const x = 1;
78+ const searchContent = ` const x = 1;
7679 const y = 2;`;
7780
78- const result = findSearchMatch(fileContent, searchContent);
81+ const result = findSearchMatch(fileContent, searchContent);
7982
80- // The actual indexOf result is 18, not 17
81- expect(result).toEqual({
82- startIndex: 18,
83- endIndex: 18 + searchContent.length,
84- });
83+ // The actual indexOf result is 18, not 17
84+ expect(result).toEqual({
85+ startIndex: 18,
86+ endIndex: 18 + searchContent.length,
87+ strategyName: "exactMatch",
8588 });
8689 });
87-
88- describe("Trimmed matches", () => {
89- it("should find trimmed match when exact match fails due to leading newlines", () => {
90- const fileContent = `function hello() {
90+});
91+
92+describe("Trimmed matches", () => {
93+ it("should find trimmed match when exact match fails due to leading newlines", () => {
94+ const fileContent = `function hello() {
9195 console.log("world");
9296 }`;
93- const searchContent = `\n\nfunction hello() {
97+ const searchContent = `\n\nfunction hello() {
9498 console.log("world");
9599 }\n\n`;
96100
97- const result = findSearchMatch(fileContent, searchContent);
101+ const result = findSearchMatch(fileContent, searchContent);
98102
99- expect(result).toEqual({
100- startIndex: 0,
101- endIndex: fileContent.length, // Uses trimmed length
102- });
103+ expect(result).toEqual({
104+ startIndex: 0,
105+ endIndex: fileContent.length, // Uses trimmed length
106+ strategyName: "trimmedMatch",
103107 });
108+ });
104109
105- it("should find trimmed match when exact match fails due to trailing newlines", () => {
106- const fileContent = `const a = 1;
110+ it("should find trimmed match when exact match fails due to trailing newlines", () => {
111+ const fileContent = `const a = 1;
107112 function hello() {
108113 return "world";
109114 }
110115 const b = 2;`;
111- const searchContent = `\nfunction hello() {
116+ const searchContent = `\nfunction hello() {
112117 return "world";
113118 }\n`;
114119
115- const result = findSearchMatch(fileContent, searchContent);
120+ const result = findSearchMatch(fileContent, searchContent);
116121
117- // The function finds the exact match first (at index 12), not the trimmed match
118- expect(result).toEqual({
119- startIndex: 12,
120- endIndex: 12 + searchContent.length,
121- });
122+ // The function finds the exact match first (at index 12), not the trimmed match
123+ expect(result).toEqual({
124+ startIndex: 12,
125+ endIndex: 12 + searchContent.length,
126+ strategyName: "exactMatch",
122127 });
128+ });
123129
124- it("should find trimmed match for single line with extra whitespace", () => {
125- const fileContent = `const a = 1;
130+ it("should find trimmed match for single line with extra whitespace", () => {
131+ const fileContent = `const a = 1;
126132 const b = 2;
127133 const c = 3;`;
128- const searchContent = `\n const b = 2; \n`;
134+ const searchContent = `\n const b = 2; \n`;
129135
130- const result = findSearchMatch(fileContent, searchContent);
136+ const result = findSearchMatch(fileContent, searchContent);
131137
132- const trimmedSearchContent = searchContent.trim();
133- const expectedStart = fileContent.indexOf(trimmedSearchContent);
138+ const trimmedSearchContent = searchContent.trim();
139+ const expectedStart = fileContent.indexOf(trimmedSearchContent);
134140
135- expect(result).toEqual({
136- startIndex: expectedStart,
137- endIndex: expectedStart + trimmedSearchContent.length,
138- });
141+ expect(result).toEqual({
142+ startIndex: expectedStart,
143+ endIndex: expectedStart + trimmedSearchContent.length,
144+ strategyName: "trimmedMatch",
139145 });
140146 });
141-
142- describe("Empty search content", () => {
143- it("should match at beginning for empty search content", () => {
144- const fileContent = `function hello() {
147+});
148+
149+describe("Empty search content", () => {
150+ it("should match at beginning for empty search content", () => {
151+ const fileContent = `function hello() {
145152 console.log("world");
146153 }`;
147- const searchContent = "";
154+ const searchContent = "";
148155
149- const result = findSearchMatch(fileContent, searchContent);
156+ const result = findSearchMatch(fileContent, searchContent);
150157
151- expect(result).toEqual({
152- startIndex: 0,
153- endIndex: 0,
154- });
158+ expect(result).toEqual({
159+ startIndex: 0,
160+ endIndex: 0,
161+ strategyName: "emptySearch",
155162 });
163+ });
156164
157- it("should match at beginning for whitespace-only search content", () => {
158- const fileContent = `function hello() {
165+ it("should match at beginning for whitespace-only search content", () => {
166+ const fileContent = `function hello() {
159167 console.log("world");
160168 }`;
161- const searchContent = "\n\n \t \n";
169+ const searchContent = "\n\n \t \n";
162170
163- const result = findSearchMatch(fileContent, searchContent);
171+ const result = findSearchMatch(fileContent, searchContent);
164172
165- expect(result).toEqual({
166- startIndex: 0,
167- endIndex: 0,
168- });
173+ expect(result).toEqual({
174+ startIndex: 0,
175+ endIndex: 0,
176+ strategyName: "emptySearch",
169177 });
178+ });
170179
171- it("should match at beginning for empty file and empty search", () => {
172- const fileContent = "";
173- const searchContent = "";
180+ it("should match at beginning for empty file and empty search", () => {
181+ const fileContent = "";
182+ const searchContent = "";
174183
175- const result = findSearchMatch(fileContent, searchContent);
184+ const result = findSearchMatch(fileContent, searchContent);
176185
177- expect(result).toEqual({
178- startIndex: 0,
179- endIndex: 0,
180- });
186+ expect(result).toEqual({
187+ startIndex: 0,
188+ endIndex: 0,
189+ strategyName: "emptySearch",
181190 });
182191 });
183-
184- describe("No matches", () => {
185- it("should return null when search content is not found", () => {
186- const fileContent = `function hello() {
192+});
193+
194+describe("No matches", () => {
195+ it("should return null when search content is not found", () => {
196+ const fileContent = `function hello() {
187197 console.log("world");
188198 }`;
189- const searchContent = `function goodbye() {
199+ const searchContent = `function goodbye() {
190200 console.log("world");
191201 }`;
192202
193- const result = findSearchMatch(fileContent, searchContent);
203+ const result = findSearchMatch(fileContent, searchContent);
194204
195- expect(result).toBeNull();
196- });
205+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
206+ });
197207
198- it("should return null when trimmed search content is not found", () => {
199- const fileContent = `function hello() {
208+ it("should return only fuzzy result when trimmed search content is not found", () => {
209+ const fileContent = `function hello() {
200210 console.log("world");
201211 }`;
202- const searchContent = `\n\nfunction goodbye() {
212+ const searchContent = `\n\nfunction goodbye() {
203213 console.log("world");
204214 }\n\n`;
205215
206- const result = findSearchMatch(fileContent, searchContent);
216+ const result = findSearchMatch(fileContent, searchContent);
207217
208- expect(result).toBeNull();
209- });
218+ expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
219+ });
220+});
210221
211- it("should return null for non-existent single line", () => {
212- const fileContent = `const a = 1;
213-const b = 2;
214-const c = 3;`;
215- const searchContent = `const d = 4;`;
222+describe("Edge cases", () => {
223+ it("should handle empty file with non-empty search", () => {
224+ const fileContent = "";
225+ const searchContent = "function hello() {}";
226+
227+ const result = findSearchMatch(fileContent, searchContent);
228+
229+ expect(result).toBeNull();
230+ });
216231
217- const result = findSearchMatch(fileContent, searchContent);
232+ it("should handle very large content", () => {
233+ const repeatedLine = "const x = 1;\n";
234+ const fileContent =
235+ repeatedLine.repeat(1000) +
236+ "const target = 2;\n" +
237+ repeatedLine.repeat(1000);
238+ const searchContent = "const target = 2;";
239+
240+ const result = findSearchMatch(fileContent, searchContent);
241+
242+ const expectedStart = repeatedLine.length * 1000;
243+ expect(result).toEqual({
244+ startIndex: expectedStart,
245+ endIndex: expectedStart + searchContent.length,
246+ strategyName: "exactMatch",
247+ });
248+ });
218249
219- expect(result).toBeNull();
250+ it("should handle special characters and symbols", () => {
251+ const fileContent = `const regex = /[a-zA-Z]+/g;
252+const symbols = !@#$%^&*();
253+const unicode = "🚀 Hello 世界";`;
254+ const searchContent = `const symbols = !@#$%^&*();`;
255+
256+ const result = findSearchMatch(fileContent, searchContent);
257+
258+ const expectedStart = fileContent.indexOf(searchContent);
259+ expect(result).toEqual({
260+ startIndex: expectedStart,
261+ endIndex: expectedStart + searchContent.length,
262+ strategyName: "exactMatch",
220263 });
264+ });
221265
222- it("should return null for partial match", () => {
223- const fileContent = `function hello() {
224- console.log("world");
266+ it("should prefer exact match over trimmed match", () => {
267+ const fileContent = `function test() {
268+ const x = 1;
269+}
270+
271+function test() {
272+ const x = 1;
225273 }`;
226- const searchContent = `function hello() {
227- console.log("universe");
274+ const searchContent = `function test() {
275+ const x = 1;
228276 }`;
229277
230- const result = findSearchMatch(fileContent, searchContent);
278+ const result = findSearchMatch(fileContent, searchContent);
231279
232- expect(result).toBeNull();
280+ // Should find the first exact match, not a trimmed version
281+ expect(result).toEqual({
282+ startIndex: 0,
283+ endIndex: searchContent.length,
284+ strategyName: "exactMatch",
233285 });
234286 });
235287
236- describe("Edge cases", () => {
237- it("should handle empty file with non-empty search", () => {
238- const fileContent = "";
239- const searchContent = "function hello() {}";
288+ it("should handle multiple occurrences and return first match", () => {
289+ const fileContent = `const a = 1;
290+const b = 2;
291+const a = 1;`;
292+ const searchContent = `const a = 1;`;
240293
241- const result = findSearchMatch(fileContent, searchContent);
294+ const result = findSearchMatch(fileContent, searchContent);
242295
243- expect(result).toBeNull();
296+ expect(result).toEqual({
297+ startIndex: 0,
298+ endIndex: searchContent.length,
299+ strategyName: "exactMatch",
244300 });
301+ });
302+});
303+
304+describe("Whitespace-ignored matches", () => {
305+ it("should match code with different indentation", () => {
306+ const fileContent = `function example() {
307+ const x = 1;
308+ const y = 2;
309+ return x + y;
310+}`;
311+ const searchContent = `const x=1;
312+const y=2;
313+return x+y;`;
314+
315+ const result = findSearchMatch(fileContent, searchContent);
316+
317+ expect(result).not.toBeNull();
318+ expect(result!.startIndex).toBe(20); // After "function example() {\n"
319+ expect(result!.endIndex).toBe(72); // End of " return x + y;"
320+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
321+
322+ // Verify the matched content contains the original whitespace
323+ const matchedContent = fileContent.substring(
324+ result!.startIndex,
325+ result!.endIndex,
326+ );
327+ expect(matchedContent).toBe(`
328+ const x = 1;
329+ const y = 2;
330+ return x + y;`);
331+ });
245332
246- it("should handle very large content", () => {
247- const repeatedLine = "const x = 1;\n";
248- const fileContent =
249- repeatedLine.repeat(1000) +
250- "const target = 2;\n" +
251- repeatedLine.repeat(1000);
252- const searchContent = "const target = 2;";
333+ it("should match single line with different spacing", () => {
334+ const fileContent = `const a = 1;
335+const b = 2;
336+const c = 3;`;
337+ const searchContent = `const b=2;`;
338+
339+ const result = findSearchMatch(fileContent, searchContent);
340+
341+ expect(result).not.toBeNull();
342+ expect(result!.startIndex).toBe(12); // After "const a = 1;"
343+ expect(result!.endIndex).toBe(32); // End of "const b = 2;"
344+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
345+
346+ // Verify the matched content preserves original spacing
347+ const matchedContent = fileContent.substring(
348+ result!.startIndex,
349+ result!.endIndex,
350+ );
351+ expect(matchedContent).toBe(`
352+const b = 2;`);
353+ });
253354
254- const result = findSearchMatch(fileContent, searchContent);
355+ it("should match with tabs vs spaces", () => {
356+ const fileContent = `function test() {
357+\tif (condition) {
358+\t\treturn true;
359+\t}
360+}`;
361+ const searchContent = `if (condition) {
362+ return true;
363+}`;
255364
256- const expectedStart = repeatedLine.length * 1000;
257- expect(result).toEqual({
258- startIndex: expectedStart,
259- endIndex: expectedStart + searchContent.length,
260- });
261- });
365+ const result = findSearchMatch(fileContent, searchContent);
366+
367+ expect(result).not.toBeNull();
368+ expect(result!.startIndex).toBe(17); // After "function test() {"
369+ expect(result!.endIndex).toBe(53); // End of "\t}"
370+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
371+
372+ // Verify the matched content preserves original tabs
373+ const matchedContent = fileContent.substring(
374+ result!.startIndex,
375+ result!.endIndex,
376+ );
377+ expect(matchedContent).toBe(`
378+\tif (condition) {
379+\t\treturn true;
380+\t}`);
381+ });
262382
263- it("should handle special characters and symbols", () => {
264- const fileContent = `const regex = /[a-zA-Z]+/g;
265-const symbols = !@#$%^&*();
266-const unicode = "🚀 Hello 世界";`;
267- const searchContent = `const symbols = !@#$%^&*();`;
383+ it("should match complex whitespace patterns", () => {
384+ const fileContent = `const obj = {
385+ key1 : 'value1',
386+ key2 : 'value2',
387+ key3 : 'value3'
388+};`;
389+ const searchContent = `key1:'value1',
390+key2:'value2',
391+key3:'value3'`;
392+
393+ const result = findSearchMatch(fileContent, searchContent);
394+
395+ expect(result).not.toBeNull();
396+ expect(result!.startIndex).toBe(13); // After "const obj = {"
397+ expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
398+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
399+
400+ // Verify the matched content preserves original formatting
401+ const matchedContent = fileContent.substring(
402+ result!.startIndex,
403+ result!.endIndex,
404+ );
405+ expect(matchedContent).toBe(`
406+ key1 : 'value1',
407+ key2 : 'value2',
408+ key3 : 'value3'`);
409+ });
268410
269- const result = findSearchMatch(fileContent, searchContent);
411+ it("should handle newlines and mixed whitespace", () => {
412+ const fileContent = `function calc() {
270413
271- const expectedStart = fileContent.indexOf(searchContent);
272- expect(result).toEqual({
273- startIndex: expectedStart,
274- endIndex: expectedStart + searchContent.length,
275- });
414+
415+ let result = 0;
416+
417+ result += 5;
418+
419+
420+ return result;
421+}`;
422+ const searchContent = `let result=0;result+=5;return result;`;
423+
424+ const result = findSearchMatch(fileContent, searchContent);
425+
426+ expect(result).not.toBeNull();
427+ expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
428+ expect(result!.endIndex).toBe(78); // End of " return result;"
429+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
430+
431+ // Verify the matched content includes all original whitespace
432+ const matchedContent = fileContent.substring(
433+ result!.startIndex,
434+ result!.endIndex,
435+ );
436+ expect(matchedContent).toBe(`
437+
438+
439+ let result = 0;
440+
441+ result += 5;
442+
443+
444+ return result;`);
445+ });
446+
447+ it("should prefer exact match over whitespace-ignored match", () => {
448+ const fileContent = `const x=1;
449+const x = 1;`;
450+ const searchContent = `const x=1;`;
451+
452+ const result = findSearchMatch(fileContent, searchContent);
453+
454+ // Should find the exact match first (at index 0), not the whitespace-ignored match
455+ expect(result).toEqual({
456+ startIndex: 0,
457+ endIndex: 10,
458+ strategyName: "exactMatch",
276459 });
460+ });
277461
278- it("should prefer exact match over trimmed match", () => {
279- const fileContent = `function test() {
280- const x = 1;
281-}
462+ it("should handle empty content after whitespace removal", () => {
463+ const fileContent = `function test() {
464+ return 1;
465+}`;
466+ const searchContent = `\n\n \t \n`;
467+
468+ const result = findSearchMatch(fileContent, searchContent);
469+
470+ // Should match at beginning for empty/whitespace-only content
471+ expect(result).toEqual({
472+ startIndex: 0,
473+ endIndex: 0,
474+ strategyName: "emptySearch",
475+ });
476+ });
282477
283-function test() {
284- const x = 1;
478+ it("should handle complex code blocks with different formatting", () => {
479+ const fileContent = `class Example {
480+ constructor(name) {
481+ this.name = name;
482+ this.value = 0;
483+ }
484+
485+ getValue() {
486+ return this.value;
487+ }
285488 }`;
286- const searchContent = `function test() {
287- const x = 1;
489+ const searchContent = `constructor(name){
490+this.name=name;
491+this.value=0;
288492 }`;
289493
290- const result = findSearchMatch(fileContent, searchContent);
494+ const result = findSearchMatch(fileContent, searchContent);
495+
496+ expect(result).not.toBeNull();
497+ expect(result!.startIndex).toBe(15); // After "class Example {"
498+ expect(result!.endIndex).toBe(95); // End of " }"
499+ expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
500+
501+ // Verify the matched content preserves original formatting
502+ const matchedContent = fileContent.substring(
503+ result!.startIndex,
504+ result!.endIndex,
505+ );
506+ expect(matchedContent).toBe(`
507+ constructor(name) {
508+ this.name = name;
509+ this.value = 0;
510+ }`);
511+ });
291512
292- // Should find the first exact match, not a trimmed version
293- expect(result).toEqual({
294- startIndex: 0,
295- endIndex: searchContent.length,
296- });
297- });
513+ it("should return null when no close match exists", () => {
514+ const fileContent = `function hello() {
515+ console.log("world");
516+}`;
517+ const searchContent = `this has nothing to do with the other option`;
298518
299- it("should handle multiple occurrences and return first match", () => {
300- const fileContent = `const a = 1;
301-const b = 2;
302-const a = 1;`;
303- const searchContent = `const a = 1;`;
519+ const result = findSearchMatch(fileContent, searchContent);
304520
305- const result = findSearchMatch(fileContent, searchContent);
521+ expect(result).toBeNull();
522+ });
306523
307- expect(result).toEqual({
308- startIndex: 0,
309- endIndex: searchContent.length,
310- });
524+ it("should handle multiple potential matches and return first", () => {
525+ const fileContent = `const a=1;
526+const a = 1;
527+const a = 1;`;
528+ const searchContent = `const a=1;`;
529+
530+ const result = findSearchMatch(fileContent, searchContent);
531+
532+ // Should find the first exact match
533+ expect(result).toEqual({
534+ startIndex: 0,
535+ endIndex: 10,
536+ strategyName: "exactMatch",
311537 });
312538 });
313-
314- describe("Real-world scenarios", () => {
315- it("should match typical function replacement", () => {
316- const fileContent = `class Calculator {
539+});
540+
541+describe("Real-world scenarios", () => {
542+ it("should match typical function replacement", () => {
543+ const fileContent = `class Calculator {
317544 constructor() {
318545 this.result = 0;
319546 }
@@ -328,41 +555,43 @@
328555 return this;
329556 }
330557 }`;
331- const searchContent = ` reset() {
558+ const searchContent = ` reset() {
332559 this.result = 0;
333560 return this;
334561 }`;
335562
336- const result = findSearchMatch(fileContent, searchContent);
563+ const result = findSearchMatch(fileContent, searchContent);
337564
338- const expectedStart = fileContent.indexOf(searchContent);
339- expect(result).toEqual({
340- startIndex: expectedStart,
341- endIndex: expectedStart + searchContent.length,
342- });
565+ const expectedStart = fileContent.indexOf(searchContent);
566+ expect(result).toEqual({
567+ startIndex: expectedStart,
568+ endIndex: expectedStart + searchContent.length,
569+ strategyName: "exactMatch",
343570 });
571+ });
344572
345- it("should match import statement", () => {
346- const fileContent = `import React from 'react';
573+ it("should match import statement", () => {
574+ const fileContent = `import React from 'react';
347575 import { useState, useEffect } from 'react';
348576 import './App.css';
349577
350578 function App() {
351579 return <div>Hello World</div>;
352580 }`;
353- const searchContent = `import { useState, useEffect } from 'react';`;
354-
355- const result = findSearchMatch(fileContent, searchContent);
356-
357- const expectedStart = fileContent.indexOf(searchContent);
358- expect(result).toEqual({
359- startIndex: expectedStart,
360- endIndex: expectedStart + searchContent.length,
361- });
581+ const searchContent = `import { useState, useEffect } from 'react';`;
582+
583+ const result = findSearchMatch(fileContent, searchContent);
584+
585+ const expectedStart = fileContent.indexOf(searchContent);
586+ expect(result).toEqual({
587+ startIndex: expectedStart,
588+ endIndex: expectedStart + searchContent.length,
589+ strategyName: "exactMatch",
362590 });
591+ });
363592
364- it("should match comment block", () => {
365- const fileContent = `/**
593+ it("should match comment block", () => {
594+ const fileContent = `/**
366595 * This is a comment
367596 * that spans multiple lines
368597 */
@@ -370,16 +599,169 @@
370599 // Single line comment
371600 return true;
372601 }`;
373- const searchContent = `/**
602+ const searchContent = `/**
374603 * This is a comment
375604 * that spans multiple lines
376605 */`;
377606
378- const result = findSearchMatch(fileContent, searchContent);
607+ const result = findSearchMatch(fileContent, searchContent);
608+
609+ expect(result).toEqual({
610+ startIndex: 0,
611+ endIndex: searchContent.length,
612+ strategyName: "exactMatch",
613+ });
614+ });
615+
616+ describe("Jaro-Winkler fuzzy matching", () => {
617+ describe("Basic fuzzy matching", () => {
618+ it("should find fuzzy match for similar strings", () => {
619+ const fileContent = `function calculateSum(a, b) {
620+ return a + b;
621+}`;
622+ const searchContent = `function calculateSum(x, y) {
623+ return x + y;
624+}`;
625+
626+ const result = findSearchMatch(fileContent, searchContent);
627+
628+ expect(result).not.toBeNull();
629+ });
630+
631+ it("should find fuzzy match with minor typos", () => {
632+ const fileContent = `const message = "Hello World";`;
633+ const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
634+
635+ const result = findSearchMatch(fileContent, searchContent);
636+
637+ expect(result).not.toBeNull();
638+ expect(result?.startIndex).toBe(0);
639+ });
640+
641+ it("should find fuzzy match with different variable names", () => {
642+ const fileContent = `let userAge = 25;
643+let userName = "John";`;
644+ const searchContent = `let age = 25;
645+let name = "John";`;
646+
647+ const result = findSearchMatch(fileContent, searchContent);
648+
649+ expect(result).not.toBeNull();
650+ });
651+
652+ it("should find fuzzy match for similar function signature", () => {
653+ const fileContent = `function processUserData(userData) {
654+ validateInput(userData);
655+ return formatOutput(userData);
656+}`;
657+ const searchContent = `function processData(data) {
658+ validateInput(data);
659+ return formatOutput(data);
660+}`;
661+
662+ const result = findSearchMatch(fileContent, searchContent);
663+
664+ expect(result).not.toBeNull();
665+ });
666+ });
667+
668+ describe("Multi-line fuzzy matching", () => {
669+ it("should find fuzzy match for multi-line blocks", () => {
670+ const fileContent = `class Calculator {
671+ constructor() {
672+ this.result = 0;
673+ }
674+
675+ add(value) {
676+ this.result += value;
677+ return this;
678+ }
679+}`;
680+ const searchContent = `class Calculator {
681+ constructor() {
682+ this.value = 0;
683+ }
684+
685+ add(num) {
686+ this.value += num;
687+ return this;
688+ }
689+}`;
690+
691+ const result = findSearchMatch(fileContent, searchContent);
692+
693+ expect(result).not.toBeNull();
694+ });
695+
696+ it("should find fuzzy match for partial blocks", () => {
697+ const fileContent = `function processData(input) {
698+ const validated = validateInput(input);
699+ const processed = transformData(validated);
700+ const result = formatOutput(processed);
701+ return result;
702+}`;
703+ const searchContent = `const validated = validateInput(input);
704+ const processed = transformData(validated);`;
705+
706+ const result = findSearchMatch(fileContent, searchContent);
707+
708+ expect(result).not.toBeNull();
709+ });
710+ });
711+
712+ describe("Edge cases with fuzzy matching", () => {
713+ it("should handle empty search content with fuzzy matching enabled", () => {
714+ const fileContent = `function test() {}`;
715+ const searchContent = "";
716+
717+ const result = findSearchMatch(fileContent, searchContent);
718+
719+ expect(result).toEqual({
720+ startIndex: 0,
721+ endIndex: 0,
722+ strategyName: "emptySearch",
723+ });
724+ });
725+
726+ it("should handle empty file content with fuzzy matching enabled", () => {
727+ const fileContent = "";
728+ const searchContent = "function test() {}";
729+
730+ const result = findSearchMatch(fileContent, searchContent);
731+
732+ expect(result).toBeNull();
733+ });
734+
735+ it("should prefer exact match over fuzzy match", () => {
736+ const fileContent = `function test() { return true; }
737+function test() { return false; }`;
738+ const searchContent = `function test() { return true; }`;
739+
740+ const result = findSearchMatch(fileContent, searchContent);
741+
742+ expect(result).not.toBeNull();
743+ expect(result?.startIndex).toBe(0);
744+ });
745+
746+ it("should handle very short strings", () => {
747+ const fileContent = `a b c`;
748+ const searchContent = `a c`;
749+
750+ const result = findSearchMatch(fileContent, searchContent);
751+
752+ // Should not match due to low similarity
753+ expect(result).toBeNull();
754+ });
755+
756+ it("should handle special characters in fuzzy matching", () => {
757+ const fileContent = `const regex = /[a-zA-Z]+/g;
758+const symbols = !@#$%^&*();`;
759+ const searchContent = `const regex = /[a-zA-Z0-9]+/g;
760+const symbols = !@#$%^&*();`;
761+
762+ const result = findSearchMatch(fileContent, searchContent);
379763
380- expect(result).toEqual({
381- startIndex: 0,
382- endIndex: searchContent.length,
764+ expect(result).not.toBeNull();
383765 });
384766 });
385767 });
modified core/edit/searchAndReplace/findSearchMatch.ts +285 −23
@@ -1,54 +1,316 @@
11 /**
2- * Represents a match result with start and end character positions
2+ * Represents a basic match result with start and end character positions
33 */
4-export interface SearchMatchResult {
4+interface BasicMatchResult {
55 /** The starting character index of the match in the file content */
66 startIndex: number;
77 /** The ending character index of the match in the file content */
88 endIndex: number;
99 }
1010
11+/**
12+ * Represents a match result with start and end character positions
13+ */
14+export interface SearchMatchResult extends BasicMatchResult {
15+ /** The name of the strategy that successfully matched */
16+ strategyName: string;
17+}
18+
19+/**
20+ * Strategy function type for finding matches
21+ */
22+type MatchStrategy = (
23+ fileContent: string,
24+ searchContent: string,
25+) => BasicMatchResult | null;
26+
27+/**
28+ * Exact string matching strategy
29+ */
30+function exactMatch(
31+ fileContent: string,
32+ searchContent: string,
33+): BasicMatchResult | null {
34+ const exactIndex = fileContent.indexOf(searchContent);
35+ if (exactIndex !== -1) {
36+ return {
37+ startIndex: exactIndex,
38+ endIndex: exactIndex + searchContent.length,
39+ };
40+ }
41+ return null;
42+}
43+
44+/**
45+ * Trimmed content matching strategy
46+ */
47+function trimmedMatch(
48+ fileContent: string,
49+ searchContent: string,
50+): BasicMatchResult | null {
51+ const trimmedSearchContent = searchContent.trim();
52+ const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
53+ if (trimmedIndex !== -1) {
54+ return {
55+ startIndex: trimmedIndex,
56+ endIndex: trimmedIndex + trimmedSearchContent.length,
57+ };
58+ }
59+ return null;
60+}
61+
62+/**
63+ * Whitespace-ignored matching strategy
64+ * Removes all whitespace from both content and search, then finds the match
65+ */
66+function whitespaceIgnoredMatch(
67+ fileContent: string,
68+ searchContent: string,
69+): BasicMatchResult | null {
70+ // Remove all whitespace (spaces, tabs, newlines, etc.)
71+ const strippedFileContent = fileContent.replace(/\s/g, "");
72+ const strippedSearchContent = searchContent.replace(/\s/g, "");
73+
74+ if (strippedSearchContent === "") {
75+ return null; // Empty search after stripping whitespace
76+ }
77+
78+ const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
79+ if (strippedIndex === -1) {
80+ return null;
81+ }
82+
83+ // Map the stripped position back to the original file content
84+ let originalStartIndex = 0;
85+ let strippedCharCount = 0;
86+
87+ // Find the original position by counting non-whitespace characters
88+ for (let i = 0; i < fileContent.length; i++) {
89+ if (strippedCharCount === strippedIndex) {
90+ originalStartIndex = i;
91+ break;
92+ }
93+ if (!/\s/.test(fileContent[i])) {
94+ strippedCharCount++;
95+ }
96+ }
97+
98+ // Find the end position by counting the length of the search content
99+ let originalEndIndex = originalStartIndex;
100+ let matchedChars = 0;
101+
102+ for (
103+ let i = originalStartIndex;
104+ i < fileContent.length && matchedChars < strippedSearchContent.length;
105+ i++
106+ ) {
107+ if (!/\s/.test(fileContent[i])) {
108+ matchedChars++;
109+ }
110+ originalEndIndex = i + 1;
111+ }
112+
113+ return {
114+ startIndex: originalStartIndex,
115+ endIndex: originalEndIndex,
116+ };
117+}
118+
119+/**
120+ * Calculate the Jaro similarity between two strings
121+ */
122+function jaroSimilarity(s1: string, s2: string): number {
123+ if (s1 === s2) return 1.0;
124+ if (s1.length === 0 || s2.length === 0) return 0.0;
125+
126+ const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
127+ if (matchDistance < 0) return 0.0;
128+
129+ const s1Matches = new Array(s1.length).fill(false);
130+ const s2Matches = new Array(s2.length).fill(false);
131+
132+ let matches = 0;
133+ let transpositions = 0;
134+
135+ // Find matches
136+ for (let i = 0; i < s1.length; i++) {
137+ const start = Math.max(0, i - matchDistance);
138+ const end = Math.min(i + matchDistance + 1, s2.length);
139+
140+ for (let j = start; j < end; j++) {
141+ if (s2Matches[j] || s1[i] !== s2[j]) continue;
142+ s1Matches[i] = true;
143+ s2Matches[j] = true;
144+ matches++;
145+ break;
146+ }
147+ }
148+
149+ if (matches === 0) return 0.0;
150+
151+ // Count transpositions
152+ let k = 0;
153+ for (let i = 0; i < s1.length; i++) {
154+ if (!s1Matches[i]) continue;
155+ while (!s2Matches[k]) k++;
156+ if (s1[i] !== s2[k]) transpositions++;
157+ k++;
158+ }
159+
160+ return (
161+ (matches / s1.length +
162+ matches / s2.length +
163+ (matches - transpositions / 2) / matches) /
164+ 3.0
165+ );
166+}
167+
168+/**
169+ * Calculate the Jaro-Winkler similarity between two strings
170+ */
171+function jaroWinklerSimilarity(
172+ s1: string,
173+ s2: string,
174+ prefixScale = 0.1,
175+): number {
176+ const jaroSim = jaroSimilarity(s1, s2);
177+
178+ if (jaroSim < 0.7) return jaroSim;
179+
180+ // Calculate common prefix length (up to 4 characters)
181+ let prefixLength = 0;
182+ const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
183+
184+ for (let i = 0; i < maxPrefix; i++) {
185+ if (s1[i] === s2[i]) {
186+ prefixLength++;
187+ } else {
188+ break;
189+ }
190+ }
191+
192+ return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
193+}
194+
195+/**
196+ * Find the best fuzzy match for search content in file content using Jaro-Winkler
197+ */
198+function findFuzzyMatch(
199+ fileContent: string,
200+ searchContent: string,
201+ threshold: number = 0.9,
202+): BasicMatchResult | null {
203+ const searchLines = searchContent.split("\n");
204+ const fileLines = fileContent.split("\n");
205+
206+ let bestMatch: BasicMatchResult | null = null;
207+ let bestSimilarity = 0;
208+
209+ // Try matching the search content as a whole block
210+ const searchBlock = searchContent.trim();
211+ if (searchBlock.length > 5) {
212+ // Require minimum length for meaningful matches
213+ // Use sliding window approach for multi-line search
214+ for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
215+ const candidateLines = fileLines.slice(i, i + searchLines.length);
216+ const candidateBlock = candidateLines.join("\n").trim();
217+
218+ if (candidateBlock.length < 5) continue; // Skip very short blocks
219+
220+ const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
221+
222+ if (similarity >= threshold && similarity > bestSimilarity) {
223+ // Calculate character positions
224+ const linesBeforeMatch = fileLines.slice(0, i);
225+ const startIndex =
226+ linesBeforeMatch.join("\n").length +
227+ (linesBeforeMatch.length > 0 ? 1 : 0);
228+ const endIndex = startIndex + candidateBlock.length;
229+
230+ bestMatch = {
231+ startIndex,
232+ endIndex,
233+ };
234+ bestSimilarity = similarity;
235+ }
236+ }
237+ }
238+
239+ // Also try line-by-line matching for better granularity
240+ for (
241+ let searchLineIdx = 0;
242+ searchLineIdx < searchLines.length;
243+ searchLineIdx++
244+ ) {
245+ const searchLine = searchLines[searchLineIdx].trim();
246+ if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
247+
248+ for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
249+ const fileLine = fileLines[fileLineIdx].trim();
250+ if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
251+
252+ const similarity = jaroWinklerSimilarity(searchLine, fileLine);
253+
254+ if (similarity >= threshold && similarity > bestSimilarity) {
255+ // Calculate character positions for the line
256+ const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
257+ const startIndex =
258+ linesBeforeMatch.join("\n").length +
259+ (linesBeforeMatch.length > 0 ? 1 : 0);
260+ const endIndex = startIndex + fileLines[fileLineIdx].length;
261+
262+ bestMatch = {
263+ startIndex,
264+ endIndex,
265+ };
266+ bestSimilarity = similarity;
267+ }
268+ }
269+ }
270+
271+ return bestMatch;
272+}
273+
274+/**
275+ * Ordered list of matching strategies to try with their names
276+ */
277+const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
278+ { strategy: exactMatch, name: "exactMatch" },
279+ { strategy: trimmedMatch, name: "trimmedMatch" },
280+ { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
281+ { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
282+];
283+
11284 /**
12285 * Find the exact match position for search content in file content.
13- * Uses simple exact matching with trimmed newlines for MVP.
286+ * Uses multiple matching strategies in order of preference.
14287 *
15288 * Matching Strategy:
16289 * 1. If search content is empty, matches at the beginning of file (position 0)
17- * 2. Try exact string match first
18- * 3. Fallback to trimmed content match if exact match fails
290+ * 2. Try each matching strategy in order until one succeeds
19291 *
20292 * @param fileContent - The complete content of the file to search in
21293 * @param searchContent - The content to search for
294+ * @param config - Configuration options for matching behavior
22295 * @returns Match result with character positions, or null if no match found
23296 */
24297 export function findSearchMatch(
25298 fileContent: string,
26299 searchContent: string,
27300 ): SearchMatchResult | null {
28- // Strip leading/trailing newlines for basic matching strategy
29301 const trimmedSearchContent = searchContent.trim();
30302
31303 if (trimmedSearchContent === "") {
32304 // Empty search content matches the beginning of the file
33- return { startIndex: 0, endIndex: 0 };
34- }
35-
36- // Try exact match first
37- const exactIndex = fileContent.indexOf(searchContent);
38- if (exactIndex !== -1) {
39- return {
40- startIndex: exactIndex,
41- endIndex: exactIndex + searchContent.length,
42- };
305+ return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
43306 }
44307
45- // Fallback: try trimmed content match
46- const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
47- if (trimmedIndex !== -1) {
48- return {
49- startIndex: trimmedIndex,
50- endIndex: trimmedIndex + trimmedSearchContent.length,
51- };
308+ // Try each matching strategy in order
309+ for (const { strategy, name } of matchingStrategies) {
310+ const result = strategy(fileContent, searchContent);
311+ if (result !== null) {
312+ return { ...result, strategyName: name };
313+ }
52314 }
53315
54316 return null;
modified core/tools/definitions/searchAndReplaceInFile.ts +1 −1
@@ -22,7 +22,7 @@
2222 function: {
2323 name: BuiltInToolNames.SearchAndReplaceInFile,
2424 description:
25- "Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
25+ "Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
2626 parameters: {
2727 type: "object",
2828 required: ["filepath", "diff"],
modified gui/src/util/clientTools/searchReplaceImpl.test.ts +17 −1
@@ -36,7 +36,13 @@
3636 // Create mock extras
3737 mockExtras = {
3838 ideMessenger: mockIdeMessenger,
39- getState: vi.fn(),
39+ getState: vi.fn<any>(() => ({
40+ config: {
41+ config: {
42+ allowAnonymousTelemetry: false,
43+ },
44+ },
45+ })),
4046 dispatch: vi.fn(),
4147 };
4248 });
@@ -99,6 +105,7 @@
99105 mockFindSearchMatch.mockReturnValue({
100106 startIndex,
101107 endIndex,
108+ strategyName: "exactMatch",
102109 });
103110 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
104111
@@ -173,10 +180,12 @@
173180 .mockReturnValueOnce({
174181 startIndex: firstStartIndex,
175182 endIndex: firstEndIndex,
183+ strategyName: "exactMatch",
176184 })
177185 .mockReturnValueOnce({
178186 startIndex: secondStartIndex,
179187 endIndex: secondEndIndex,
188+ strategyName: "exactMatch",
180189 });
181190
182191 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
@@ -239,6 +248,7 @@
239248 mockFindSearchMatch.mockReturnValue({
240249 startIndex: 10, // Position of "remove this line"
241250 endIndex: 26, // End of "remove this line"
251+ strategyName: "exactMatch",
242252 });
243253 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
244254
@@ -278,6 +288,7 @@
278288 mockFindSearchMatch.mockReturnValue({
279289 startIndex: 6,
280290 endIndex: 11,
291+ strategyName: "exactMatch",
281292 });
282293 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
283294
@@ -344,6 +355,7 @@
344355 .mockReturnValueOnce({
345356 startIndex: 0,
346357 endIndex: 13,
358+ strategyName: "exactMatch",
347359 })
348360 .mockReturnValueOnce(null); // Second search fails
349361
@@ -393,6 +405,7 @@
393405 mockFindSearchMatch.mockReturnValue({
394406 startIndex: 0,
395407 endIndex: 7,
408+ strategyName: "exactMatch",
396409 });
397410 mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed"));
398411
@@ -423,6 +436,7 @@
423436 mockFindSearchMatch.mockReturnValue({
424437 startIndex: 0, // Empty search matches at beginning
425438 endIndex: 0,
439+ strategyName: "exactMatch",
426440 });
427441 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
428442
@@ -457,6 +471,7 @@
457471 mockFindSearchMatch.mockReturnValue({
458472 startIndex: 0,
459473 endIndex: originalContent.length,
474+ strategyName: "exactMatch",
460475 });
461476 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
462477
@@ -492,6 +507,7 @@
492507 mockFindSearchMatch.mockReturnValue({
493508 startIndex: 0,
494509 endIndex: 4,
510+ strategyName: "exactMatch",
495511 });
496512 mockIdeMessenger.request.mockResolvedValue({ status: "success" });
497513
modified gui/src/util/clientTools/searchReplaceImpl.ts +14 −0
@@ -1,6 +1,7 @@
11 import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
22 import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
33 import { resolveRelativePathInDir } from "core/util/ideUtils";
4+import posthog from "posthog-js";
45 import { v4 as uuid } from "uuid";
56 import { ClientToolImpl } from "./callClientTool";
67
@@ -11,6 +12,9 @@
1112 ) => {
1213 const { filepath, diff } = args;
1314
15+ const state = extras.getState();
16+ const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
17+
1418 const streamId = uuid();
1519
1620 // Resolve the file path
@@ -42,6 +46,16 @@
4246
4347 // Find the search content in the current state of the file
4448 const match = findSearchMatch(currentContent, searchContent || "");
49+
50+ // Because we don't have access to use hooks, we check `allowAnonymousTelemetry`
51+ // directly rather than using `CustomPostHogProvider`
52+ if (allowAnonymousTelemetry) {
53+ // Capture telemetry for tool calls
54+ posthog.capture("find_replace_match_result", {
55+ matchStrategy: match?.strategyName ?? "noMatch",
56+ });
57+ }
58+
4559 if (!match) {
4660 throw new Error(
4761 `Search content not found in block ${i + 1}:\n${searchContent}`,