Elffuss BraidHub

kikocis/continue public

f433400a74a4 · 10.1 KiBRawPermalink
1/**
2 * Represents a basic match result with start and end character positions
3 */
4interface BasicMatchResult {
5 /** The starting character index of the match in the file content */
6 startIndex: number;
7 /** The ending character index of the match in the file content */
8 endIndex: number;
9}
10
11/**
12 * Represents a match result with start and end character positions
13 */
14export 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 */
22type MatchStrategy = (
23 fileContent: string,
24 searchContent: string,
25) => BasicMatchResult | null;
26
27/**
28 * Exact string matching strategy
29 */
30function 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 * Finds content where the search content (when trimmed) matches content in the file,
47 * and returns the span that includes the file content's whitespace
48 */
49function trimmedMatch(
50 fileContent: string,
51 searchContent: string,
52): BasicMatchResult | null {
53 const trimmedSearchContent = searchContent.trim();
54
55 // Don't apply if search content has no leading/trailing whitespace to trim
56 if (trimmedSearchContent === searchContent) {
57 return null;
58 }
59
60 // Don't match if trimmed content is empty
61 if (trimmedSearchContent === "") {
62 return null;
63 }
64
65 // Look for the trimmed content in the file
66 const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
67 if (trimmedContentIndex === -1) {
68 return null;
69 }
70
71 // Find the boundaries that include surrounding whitespace (but not newlines)
72 // Look backwards for horizontal whitespace (spaces and tabs)
73 let startIndex = trimmedContentIndex;
74 while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
75 startIndex--;
76 }
77
78 // Look forwards for horizontal whitespace (spaces and tabs)
79 let endIndex = trimmedContentIndex + trimmedSearchContent.length;
80 while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
81 endIndex++;
82 }
83
84 return {
85 startIndex,
86 endIndex,
87 };
88}
89
90/**
91 * Whitespace-ignored matching strategy
92 * Removes all whitespace from both content and search, then finds the match
93 */
94function whitespaceIgnoredMatch(
95 fileContent: string,
96 searchContent: string,
97): BasicMatchResult | null {
98 // Remove all whitespace (spaces, tabs, newlines, etc.)
99 const strippedFileContent = fileContent.replace(/\s/g, "");
100 const strippedSearchContent = searchContent.replace(/\s/g, "");
101
102 if (strippedSearchContent === "") {
103 return null; // Empty search after stripping whitespace
104 }
105
106 const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
107 if (strippedIndex === -1) {
108 return null;
109 }
110
111 // Map the stripped position back to the original file content
112 let originalStartIndex = 0;
113 let strippedCharCount = 0;
114
115 // Find the original position by counting non-whitespace characters
116 for (let i = 0; i < fileContent.length; i++) {
117 if (strippedCharCount === strippedIndex) {
118 originalStartIndex = i;
119 break;
120 }
121 if (!/\s/.test(fileContent[i])) {
122 strippedCharCount++;
123 }
124 }
125
126 // Find the end position by counting the length of the search content
127 let originalEndIndex = originalStartIndex;
128 let matchedChars = 0;
129
130 for (
131 let i = originalStartIndex;
132 i < fileContent.length && matchedChars < strippedSearchContent.length;
133 i++
134 ) {
135 if (!/\s/.test(fileContent[i])) {
136 matchedChars++;
137 }
138 originalEndIndex = i + 1;
139 }
140
141 return {
142 startIndex: originalStartIndex,
143 endIndex: originalEndIndex,
144 };
145}
146
147/**
148 * Calculate the Jaro similarity between two strings
149 */
150function jaroSimilarity(s1: string, s2: string): number {
151 if (s1 === s2) return 1.0;
152 if (s1.length === 0 || s2.length === 0) return 0.0;
153
154 const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
155 if (matchDistance < 0) return 0.0;
156
157 const s1Matches = new Array(s1.length).fill(false);
158 const s2Matches = new Array(s2.length).fill(false);
159
160 let matches = 0;
161 let transpositions = 0;
162
163 // Find matches
164 for (let i = 0; i < s1.length; i++) {
165 const start = Math.max(0, i - matchDistance);
166 const end = Math.min(i + matchDistance + 1, s2.length);
167
168 for (let j = start; j < end; j++) {
169 if (s2Matches[j] || s1[i] !== s2[j]) continue;
170 s1Matches[i] = true;
171 s2Matches[j] = true;
172 matches++;
173 break;
174 }
175 }
176
177 if (matches === 0) return 0.0;
178
179 // Count transpositions
180 let k = 0;
181 for (let i = 0; i < s1.length; i++) {
182 if (!s1Matches[i]) continue;
183 while (!s2Matches[k]) k++;
184 if (s1[i] !== s2[k]) transpositions++;
185 k++;
186 }
187
188 return (
189 (matches / s1.length +
190 matches / s2.length +
191 (matches - transpositions / 2) / matches) /
192 3.0
193 );
194}
195
196/**
197 * Calculate the Jaro-Winkler similarity between two strings
198 */
199function jaroWinklerSimilarity(
200 s1: string,
201 s2: string,
202 prefixScale = 0.1,
203): number {
204 const jaroSim = jaroSimilarity(s1, s2);
205
206 if (jaroSim < 0.7) return jaroSim;
207
208 // Calculate common prefix length (up to 4 characters)
209 let prefixLength = 0;
210 const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
211
212 for (let i = 0; i < maxPrefix; i++) {
213 if (s1[i] === s2[i]) {
214 prefixLength++;
215 } else {
216 break;
217 }
218 }
219
220 return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
221}
222
223/**
224 * Find the best fuzzy match for search content in file content using Jaro-Winkler
225 */
226function findFuzzyMatch(
227 fileContent: string,
228 searchContent: string,
229 threshold: number = 0.9,
230): BasicMatchResult | null {
231 const searchLines = searchContent.split("\n");
232 const fileLines = fileContent.split("\n");
233
234 let bestMatch: BasicMatchResult | null = null;
235 let bestSimilarity = 0;
236
237 // Try matching the search content as a whole block
238 const searchBlock = searchContent.trim();
239 if (searchBlock.length > 5) {
240 // Require minimum length for meaningful matches
241 // Use sliding window approach for multi-line search
242 for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
243 const candidateLines = fileLines.slice(i, i + searchLines.length);
244 const candidateBlock = candidateLines.join("\n").trim();
245
246 if (candidateBlock.length < 5) continue; // Skip very short blocks
247
248 const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
249
250 if (similarity >= threshold && similarity > bestSimilarity) {
251 // Calculate character positions
252 const linesBeforeMatch = fileLines.slice(0, i);
253 const startIndex =
254 linesBeforeMatch.join("\n").length +
255 (linesBeforeMatch.length > 0 ? 1 : 0);
256 const endIndex = startIndex + candidateBlock.length;
257
258 bestMatch = {
259 startIndex,
260 endIndex,
261 };
262 bestSimilarity = similarity;
263 }
264 }
265 }
266
267 // Also try line-by-line matching for better granularity
268 for (
269 let searchLineIdx = 0;
270 searchLineIdx < searchLines.length;
271 searchLineIdx++
272 ) {
273 const searchLine = searchLines[searchLineIdx].trim();
274 if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
275
276 for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
277 const fileLine = fileLines[fileLineIdx].trim();
278 if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
279
280 const similarity = jaroWinklerSimilarity(searchLine, fileLine);
281
282 if (similarity >= threshold && similarity > bestSimilarity) {
283 // Calculate character positions for the line
284 const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
285 const startIndex =
286 linesBeforeMatch.join("\n").length +
287 (linesBeforeMatch.length > 0 ? 1 : 0);
288 const endIndex = startIndex + fileLines[fileLineIdx].length;
289
290 bestMatch = {
291 startIndex,
292 endIndex,
293 };
294 bestSimilarity = similarity;
295 }
296 }
297 }
298
299 return bestMatch;
300}
301
302/**
303 * Ordered list of matching strategies to try with their names
304 */
305const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
306 { strategy: exactMatch, name: "exactMatch" },
307 { strategy: trimmedMatch, name: "trimmedMatch" },
308 { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
309 { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
310];
311
312/**
313 * Find the exact match position for search content in file content.
314 * Uses multiple matching strategies in order of preference.
315 *
316 * Matching Strategy:
317 * 1. If search content is empty, matches at the beginning of file (position 0)
318 * 2. Try each matching strategy in order until one succeeds
319 *
320 * @param fileContent - The complete content of the file to search in
321 * @param searchContent - The content to search for
322 * @param config - Configuration options for matching behavior
323 * @returns Match result with character positions, or null if no match found
324 */
325export function findSearchMatch(
326 fileContent: string,
327 searchContent: string,
328): SearchMatchResult | null {
329 // Handle truly empty search content
330 if (searchContent === "") {
331 return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
332 }
333
334 // Handle whitespace-only search content that trims to empty
335 const trimmedSearchContent = searchContent.trim();
336 if (trimmedSearchContent === "") {
337 // Check if the whitespace-only search content has an exact match first
338 const exactIndex = fileContent.indexOf(searchContent);
339 if (exactIndex !== -1) {
340 return {
341 startIndex: exactIndex,
342 endIndex: exactIndex + searchContent.length,
343 strategyName: "exactMatch",
344 };
345 }
346 // If no exact match for whitespace-only content, treat as empty search
347 return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
348 }
349
350 // Try each matching strategy in order
351 for (const { strategy, name } of matchingStrategies) {
352 const result = strategy(fileContent, searchContent);
353 if (result !== null) {
354 return { ...result, strategyName: name };
355 }
356 }
357
358 return null;
359}