Elffuss BraidHub

kikocis/continue public

main · 10.9 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 (NOT inclusive - e.g. like slice)*/
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 */
47function 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 */
66function 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 = -1;
85 let strippedCharCount = 0;
86
87 // Find the original start position by counting non-whitespace characters
88 for (let i = 0; i < fileContent.length; i++) {
89 if (!/\s/.test(fileContent[i])) {
90 if (strippedCharCount === strippedIndex) {
91 originalStartIndex = i;
92 break;
93 }
94 strippedCharCount++;
95 }
96 }
97
98 if (originalStartIndex === -1) {
99 return null; // Should not happen if strippedIndex was valid
100 }
101
102 // Find the end position by counting through all characters (including whitespace)
103 // that correspond to the stripped search content length
104 let originalEndIndex = originalStartIndex;
105 let matchedNonWhitespaceChars = 0;
106
107 for (let i = originalStartIndex; i < fileContent.length; i++) {
108 if (!/\s/.test(fileContent[i])) {
109 matchedNonWhitespaceChars++;
110 if (matchedNonWhitespaceChars === strippedSearchContent.length) {
111 originalEndIndex = i + 1;
112 break;
113 }
114 }
115 // Always update end index to include current position (whether whitespace or not)
116 originalEndIndex = i + 1;
117 }
118
119 return {
120 startIndex: originalStartIndex,
121 endIndex: originalEndIndex,
122 };
123}
124
125/**
126 * Calculate the Jaro similarity between two strings
127 * TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match
128 */
129function jaroSimilarity(s1: string, s2: string): number {
130 if (s1 === s2) return 1.0;
131 if (s1.length === 0 || s2.length === 0) return 0.0;
132
133 const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
134 if (matchDistance < 0) return 0.0;
135
136 const s1Matches = new Array(s1.length).fill(false);
137 const s2Matches = new Array(s2.length).fill(false);
138
139 let matches = 0;
140 let transpositions = 0;
141
142 // Find matches
143 for (let i = 0; i < s1.length; i++) {
144 const start = Math.max(0, i - matchDistance);
145 const end = Math.min(i + matchDistance + 1, s2.length);
146
147 for (let j = start; j < end; j++) {
148 if (s2Matches[j] || s1[i] !== s2[j]) continue;
149 s1Matches[i] = true;
150 s2Matches[j] = true;
151 matches++;
152 break;
153 }
154 }
155
156 if (matches === 0) return 0.0;
157
158 // Count transpositions
159 let k = 0;
160 for (let i = 0; i < s1.length; i++) {
161 if (!s1Matches[i]) continue;
162 while (!s2Matches[k]) k++;
163 if (s1[i] !== s2[k]) transpositions++;
164 k++;
165 }
166
167 return (
168 (matches / s1.length +
169 matches / s2.length +
170 (matches - transpositions / 2) / matches) /
171 3.0
172 );
173}
174
175/**
176 * Calculate the Jaro-Winkler similarity between two strings
177 */
178function jaroWinklerSimilarity(
179 s1: string,
180 s2: string,
181 prefixScale = 0.1,
182): number {
183 const jaroSim = jaroSimilarity(s1, s2);
184
185 if (jaroSim < 0.7) return jaroSim;
186
187 // Calculate common prefix length (up to 4 characters)
188 let prefixLength = 0;
189 const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
190
191 for (let i = 0; i < maxPrefix; i++) {
192 if (s1[i] === s2[i]) {
193 prefixLength++;
194 } else {
195 break;
196 }
197 }
198
199 return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
200}
201
202/**
203 * Find the best fuzzy match for search content in file content using Jaro-Winkler
204 */
205function findFuzzyMatch(
206 fileContent: string,
207 searchContent: string,
208 threshold: number = 0.9,
209): BasicMatchResult | null {
210 const searchLines = searchContent.split("\n");
211 const fileLines = fileContent.split("\n");
212
213 let bestMatch: BasicMatchResult | null = null;
214 let bestSimilarity = 0;
215
216 // Try matching the search content as a whole block
217 const searchBlock = searchContent.trim();
218 if (searchBlock.length > 5) {
219 // Require minimum length for meaningful matches
220 // Use sliding window approach for multi-line search
221 for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
222 const candidateLines = fileLines.slice(i, i + searchLines.length);
223 const candidateBlock = candidateLines.join("\n").trim();
224
225 if (candidateBlock.length < 5) continue; // Skip very short blocks
226
227 const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
228
229 if (similarity >= threshold && similarity > bestSimilarity) {
230 // Calculate character positions
231 const linesBeforeMatch = fileLines.slice(0, i);
232 const startIndex =
233 linesBeforeMatch.join("\n").length +
234 (linesBeforeMatch.length > 0 ? 1 : 0);
235 const endIndex = startIndex + candidateBlock.length;
236
237 bestMatch = {
238 startIndex,
239 endIndex,
240 };
241 bestSimilarity = similarity;
242 }
243 }
244 }
245
246 // Also try line-by-line matching for better granularity
247 for (
248 let searchLineIdx = 0;
249 searchLineIdx < searchLines.length;
250 searchLineIdx++
251 ) {
252 const searchLine = searchLines[searchLineIdx].trim();
253 if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
254
255 for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
256 const fileLine = fileLines[fileLineIdx].trim();
257 if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
258
259 const similarity = jaroWinklerSimilarity(searchLine, fileLine);
260
261 if (similarity >= threshold && similarity > bestSimilarity) {
262 // Calculate character positions for the line
263 const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
264 const startIndex =
265 linesBeforeMatch.join("\n").length +
266 (linesBeforeMatch.length > 0 ? 1 : 0);
267 const endIndex = startIndex + fileLines[fileLineIdx].length;
268
269 bestMatch = {
270 startIndex,
271 endIndex,
272 };
273 bestSimilarity = similarity;
274 }
275 }
276 }
277
278 return bestMatch;
279}
280
281/**
282 * Ordered list of matching strategies to try with their names
283 */
284const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
285 { strategy: exactMatch, name: "exactMatch" },
286 { strategy: trimmedMatch, name: "trimmedMatch" },
287 { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
288 // { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
289];
290
291/**
292 * Find the exact match position for search content in file content.
293 * Uses multiple matching strategies in order of preference.
294 *
295 * Matching Strategy:
296 * 1. If search content is empty, matches at the beginning of file (position 0)
297 * 2. Try each matching strategy in order until one succeeds
298 *
299 * @param fileContent - The complete content of the file to search in
300 * @param searchContent - The content to search for
301 * @param config - Configuration options for matching behavior
302 * @returns Match result with character positions, or null if no match found
303 */
304export function findSearchMatch(
305 fileContent: string,
306 searchContent: string,
307): SearchMatchResult | null {
308 const trimmedSearchContent = searchContent.trim();
309
310 if (trimmedSearchContent === "") {
311 // Empty search content matches the beginning of the file
312 return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
313 }
314
315 // Try each matching strategy in order
316 for (const { strategy, name } of matchingStrategies) {
317 const result = strategy(fileContent, searchContent);
318 if (result !== null) {
319 return { ...result, strategyName: name };
320 }
321 }
322
323 return null;
324}
325
326/**
327 * Find all matches for search content in file content.
328 * Uses the same matching strategies as findSearchMatch, applied iteratively.
329 *
330 * @param fileContent - The complete content of the file to search in
331 * @param searchContent - The content to search for
332 * @returns Array of match results with character positions, empty array if no matches found
333 */
334export function findSearchMatches(
335 fileContent: string,
336 searchContent: string,
337): SearchMatchResult[] {
338 const matches: SearchMatchResult[] = [];
339
340 // Special case: empty search string always matches at position 0
341 if (searchContent.trim() === "") {
342 return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }];
343 }
344
345 let remainingContent = fileContent;
346 let currentOffset = 0;
347
348 while (remainingContent.length > 0) {
349 const match = findSearchMatch(remainingContent, searchContent);
350
351 if (match === null) {
352 break;
353 }
354
355 // Adjust match positions to account for the current offset
356 const adjustedMatch: SearchMatchResult = {
357 startIndex: match.startIndex + currentOffset,
358 endIndex: match.endIndex + currentOffset,
359 strategyName: match.strategyName,
360 };
361
362 // Prevent infinite loops by ensuring we're making progress
363 // If the new match starts at or before the last match's start position, break
364 if (
365 matches.length > 0 &&
366 adjustedMatch.startIndex <= matches[matches.length - 1].startIndex
367 ) {
368 break;
369 }
370
371 matches.push(adjustedMatch);
372
373 // Update offset and truncate content after the current match
374 currentOffset = adjustedMatch.endIndex;
375 remainingContent = fileContent.slice(currentOffset);
376 }
377
378 return matches;
379}