| 1 | import { Position } from "shiki"; |
| 2 | import { DiffLine } from "../.."; |
| 3 | import { myersDiff } from "../../diff/myers"; |
| 4 | |
| 5 | /** |
| 6 | * Given a diff of two editable regions, get the offset position at the last new line inside the editable region. |
| 7 | * @param diffLines Result of myersDiff. |
| 8 | * @param lineContentAtCursorPos Content of the line at cursor position. |
| 9 | * @param lineOffsetAtCursorPos Offset of the line at cursor position compared to the start of the editable region. |
| 10 | * @returns Offset position at last new line inside the editable region. |
| 11 | */ |
| 12 | export function getOffsetPositionAtLastNewLine( |
| 13 | diffLines: DiffLine[], |
| 14 | lineContentAtCursorPos: string, |
| 15 | lineOffsetAtCursorPos: number, |
| 16 | ): { |
| 17 | line: number; |
| 18 | character: number; |
| 19 | } { |
| 20 | let lastNewLineContent = ""; |
| 21 | let lineOffset = -1; |
| 22 | let currentResultLine = 0; |
| 23 | let hasChanges = false; |
| 24 | |
| 25 | // Build the string while tracking line numbers in the result |
| 26 | diffLines.reduce((acc, curr, i) => { |
| 27 | // Add the current line to our result |
| 28 | acc += curr.line; |
| 29 | |
| 30 | // Add newline if not the last line |
| 31 | if (i < diffLines.length - 1) { |
| 32 | acc += "\n"; |
| 33 | } |
| 34 | |
| 35 | // If this is a "new" or "same" line, it will be part of the result |
| 36 | if (curr.type === "new" || curr.type === "same") { |
| 37 | if (curr.type === "new") { |
| 38 | // If it's a new line, update our tracking |
| 39 | lastNewLineContent = curr.line; |
| 40 | lineOffset = currentResultLine; |
| 41 | hasChanges = true; |
| 42 | } |
| 43 | // Increment our position in the result |
| 44 | currentResultLine++; |
| 45 | } |
| 46 | |
| 47 | return acc; |
| 48 | }, ""); |
| 49 | |
| 50 | // If nothing has changed, return the original position |
| 51 | if (!hasChanges) { |
| 52 | lineOffset = lineOffsetAtCursorPos; |
| 53 | lastNewLineContent = lineContentAtCursorPos; |
| 54 | } |
| 55 | // Calculate the character position for the end of the last relevant line |
| 56 | const endOfCharPos = lastNewLineContent.length; |
| 57 | return { |
| 58 | line: lineOffset, |
| 59 | character: endOfCharPos, |
| 60 | }; |
| 61 | } |
| 62 | |
| 63 | export function getRenderableDiffWithGutterAnnotations( |
| 64 | diffLines: DiffLine[], |
| 65 | lineContentAtCursorPos: string, |
| 66 | lineOffsetAtCursorPos: number, |
| 67 | ): { |
| 68 | offset: { |
| 69 | line: number; |
| 70 | character: number; |
| 71 | }; |
| 72 | } { |
| 73 | let lastNewLineContent = ""; |
| 74 | let lineOffset = -1; |
| 75 | let currentResultLine = 0; |
| 76 | let hasChanges = false; |
| 77 | |
| 78 | // Build the string while tracking line numbers in the result |
| 79 | diffLines.reduce((acc, curr, i) => { |
| 80 | // Add the current line to our result |
| 81 | acc += curr.line; |
| 82 | |
| 83 | // Add newline if not the last line |
| 84 | if (i < diffLines.length - 1) { |
| 85 | acc += "\n"; |
| 86 | } |
| 87 | |
| 88 | // If this is a "new" or "same" line, it will be part of the result |
| 89 | if (curr.type === "new" || curr.type === "same") { |
| 90 | if (curr.type === "new") { |
| 91 | // If it's a new line, update our tracking |
| 92 | lastNewLineContent = curr.line; |
| 93 | lineOffset = currentResultLine; |
| 94 | hasChanges = true; |
| 95 | } |
| 96 | // Increment our position in the result |
| 97 | currentResultLine++; |
| 98 | } |
| 99 | |
| 100 | return acc; |
| 101 | }, ""); |
| 102 | |
| 103 | // If nothing has changed, return the original position |
| 104 | if (!hasChanges) { |
| 105 | lineOffset = lineOffsetAtCursorPos; |
| 106 | lastNewLineContent = lineContentAtCursorPos; |
| 107 | } |
| 108 | // Calculate the character position for the end of the last relevant line |
| 109 | const endOfCharPos = lastNewLineContent.length; |
| 110 | return { |
| 111 | offset: { |
| 112 | line: lineOffset, |
| 113 | character: endOfCharPos, |
| 114 | }, |
| 115 | }; |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Check if the diff is indeed a FIM. |
| 120 | * @param oldEditRange Original string content. |
| 121 | * @param newEditRange New string content. |
| 122 | * @param cursorPosition The position of the cursor in the old string. |
| 123 | * @returns boolean indicating if the change is purely additive (FIM) |
| 124 | * @returns string of FIM text content. |
| 125 | */ |
| 126 | export function checkFim( |
| 127 | oldEditRange: string, |
| 128 | newEditRange: string, |
| 129 | cursorPosition: { line: number; character: number }, |
| 130 | ): |
| 131 | | { |
| 132 | isFim: true; |
| 133 | fimText: string; |
| 134 | } |
| 135 | | { |
| 136 | isFim: false; |
| 137 | fimText: null; |
| 138 | } { |
| 139 | // console.log("oldEditRange", oldEditRange); |
| 140 | // console.log("newEditRange", newEditRange); |
| 141 | // Find the common prefix. |
| 142 | let prefixLength = 0; |
| 143 | while ( |
| 144 | prefixLength < oldEditRange.length && |
| 145 | prefixLength < newEditRange.length && |
| 146 | oldEditRange[prefixLength] === newEditRange[prefixLength] |
| 147 | ) { |
| 148 | prefixLength++; |
| 149 | } |
| 150 | |
| 151 | // Find the common suffix |
| 152 | let oldSuffixPos = oldEditRange.length - 1; |
| 153 | let newSuffixPos = newEditRange.length - 1; |
| 154 | |
| 155 | while ( |
| 156 | oldSuffixPos >= prefixLength && |
| 157 | newSuffixPos >= prefixLength && |
| 158 | oldEditRange[oldSuffixPos] === newEditRange[newSuffixPos] |
| 159 | ) { |
| 160 | oldSuffixPos--; |
| 161 | newSuffixPos--; |
| 162 | } |
| 163 | |
| 164 | // The old text is purely preserved if: |
| 165 | // 1. The prefix ends before or at the cursor. |
| 166 | // 2. The suffix starts after or at the cursor. |
| 167 | // 3. There's no gap between prefix and suffix in the old text. |
| 168 | |
| 169 | const suffixStartInOld = oldSuffixPos + 1; |
| 170 | const suffixStartInNew = newSuffixPos + 1; |
| 171 | |
| 172 | // Convert cursor position to an offset in the string. |
| 173 | // For simplicity, we need to calculate the cursor's position in the string. |
| 174 | // This requires knowledge of line endings in the oldEditRange. |
| 175 | // const lines = oldEditRange.substring(0, prefixLength).split("\n"); |
| 176 | // const lines = oldEditRange.split("\n"); |
| 177 | // const cursorOffset = |
| 178 | // lines.length > 1 |
| 179 | // ? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) + |
| 180 | // cursorPosition.character |
| 181 | // : cursorPosition.character; |
| 182 | const oldEditLines = oldEditRange.split("\n"); |
| 183 | const cursorOffset = |
| 184 | oldEditLines |
| 185 | .slice(0, cursorPosition.line) |
| 186 | .reduce((sum, line) => sum + line.length + 1, 0) + |
| 187 | cursorPosition.character; |
| 188 | |
| 189 | // Check if the cursor is positioned between the prefix and suffix. |
| 190 | const cursorBetweenPrefixAndSuffix = |
| 191 | prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld; |
| 192 | |
| 193 | // Check if the old text is completely preserved (no deletion). |
| 194 | const noTextDeleted = suffixStartInOld - prefixLength <= 0; |
| 195 | |
| 196 | const isFim = cursorBetweenPrefixAndSuffix && noTextDeleted; |
| 197 | |
| 198 | if (isFim) { |
| 199 | // Extract the content between prefix and suffix in the new string. |
| 200 | const fimText = newEditRange.substring(prefixLength, suffixStartInNew); |
| 201 | return { isFim, fimText }; |
| 202 | } else { |
| 203 | return { isFim, fimText: null }; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | export function calculateFinalCursorPosition( |
| 208 | currCursorPos: Position, |
| 209 | editableRegionStartLine: number, |
| 210 | oldEditRangeSlice: string, |
| 211 | newEditRangeSlice: string, |
| 212 | ) { |
| 213 | if (newEditRangeSlice === "") { |
| 214 | return currCursorPos; |
| 215 | } |
| 216 | // How far away is the current line from the start of the editable region? |
| 217 | const lineOffsetAtCursorPos = currCursorPos.line - editableRegionStartLine; |
| 218 | |
| 219 | // How long is the line at the current cursor position? |
| 220 | const lineContentAtCursorPos = |
| 221 | newEditRangeSlice.split("\n")[lineOffsetAtCursorPos]; |
| 222 | |
| 223 | const diffLines = myersDiff(oldEditRangeSlice, newEditRangeSlice); |
| 224 | |
| 225 | const offset = getOffsetPositionAtLastNewLine( |
| 226 | diffLines, |
| 227 | lineContentAtCursorPos, |
| 228 | lineOffsetAtCursorPos, |
| 229 | ); |
| 230 | |
| 231 | // Calculate the actual line number in the editor by adding the startPos offset |
| 232 | // to the line number from the diff calculation. |
| 233 | const finalCursorPos: Position = { |
| 234 | line: editableRegionStartLine + offset.line, |
| 235 | character: offset.character, |
| 236 | }; |
| 237 | |
| 238 | return finalCursorPos; |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * Applies a completion to file content by replacing lines starting from a specific line number |
| 243 | * |
| 244 | * @param fileContent The original file content |
| 245 | * @param completion The completion text to apply |
| 246 | * @param startLineNumber The line number (0-based) where replacement should start |
| 247 | * @param linesToReplace Optional number of lines to replace; if not provided, will replace the same number of lines as in the completion |
| 248 | * @returns The file content with the completion applied |
| 249 | */ |
| 250 | export function applyCompletionToFile( |
| 251 | fileContent: string, |
| 252 | completion: string, |
| 253 | startLineNumber: number, |
| 254 | linesToReplace?: number, |
| 255 | ): string { |
| 256 | const lines = fileContent.split("\n"); |
| 257 | const completionLines = completion.split("\n"); |
| 258 | |
| 259 | // Determine how many lines to replace |
| 260 | const numLinesToReplace = |
| 261 | linesToReplace !== undefined ? linesToReplace : completionLines.length; |
| 262 | |
| 263 | // Replace the lines |
| 264 | const newLines = [ |
| 265 | ...lines.slice(0, startLineNumber), |
| 266 | ...completionLines, |
| 267 | ...lines.slice(startLineNumber + numLinesToReplace), |
| 268 | ]; |
| 269 | |
| 270 | return newLines.join("\n"); |
| 271 | } |
| 272 | |
| 273 | export interface DiffGroup { |
| 274 | startLine: number; |
| 275 | endLine: number; |
| 276 | lines: DiffLine[]; |
| 277 | type?: string; // Optional classification of the group |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * Group diff lines into meaningful sections based on changes |
| 282 | * @param diffLines The diff lines to group |
| 283 | * @param offset Optional line offset to apply to the resulting line numbers |
| 284 | * @param maxGroupSize Optional maximum group size constraint (Mode 2) |
| 285 | * @returns Array of DiffGroup objects representing the changes |
| 286 | */ |
| 287 | export function groupDiffLines( |
| 288 | diffLines: DiffLine[], |
| 289 | offset: number = 0, |
| 290 | maxGroupSize?: number, |
| 291 | ): DiffGroup[] { |
| 292 | const groups: DiffGroup[] = []; |
| 293 | const changedAreas = findChangedAreas(diffLines); |
| 294 | |
| 295 | for (const area of changedAreas) { |
| 296 | if (maxGroupSize === undefined) { |
| 297 | // Mode 1: Flexible group size. |
| 298 | groups.push( |
| 299 | processFlexibleSizeGroup(diffLines, area.start, area.end, offset), |
| 300 | ); |
| 301 | } else { |
| 302 | // Mode 2: Limited group size. |
| 303 | groups.push( |
| 304 | processLimitedSizeGroup( |
| 305 | diffLines, |
| 306 | area.start, |
| 307 | area.end, |
| 308 | maxGroupSize, |
| 309 | offset, |
| 310 | ), |
| 311 | ); |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | return groups; |
| 316 | } |
| 317 | |
| 318 | /** |
| 319 | * Find areas of change in the diff lines. |
| 320 | */ |
| 321 | function findChangedAreas( |
| 322 | diffLines: DiffLine[], |
| 323 | ): { start: number; end: number }[] { |
| 324 | const changedAreas: { start: number; end: number }[] = []; |
| 325 | let changedAreaStart = -1; |
| 326 | |
| 327 | for (let i = 0; i < diffLines.length; i++) { |
| 328 | if (diffLines[i].type !== "same" && changedAreaStart === -1) { |
| 329 | changedAreaStart = i; |
| 330 | } else if (diffLines[i].type === "same" && changedAreaStart !== -1) { |
| 331 | // We've found the end of a changed area. |
| 332 | changedAreas.push({ start: changedAreaStart, end: i - 1 }); |
| 333 | changedAreaStart = -1; |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | // Handle the last changed area if it extends to the end. |
| 338 | if (changedAreaStart !== -1) { |
| 339 | changedAreas.push({ start: changedAreaStart, end: diffLines.length - 1 }); |
| 340 | } |
| 341 | |
| 342 | return changedAreas; |
| 343 | } |
| 344 | |
| 345 | /** |
| 346 | * Count the number of lines in the old content (excluding "new" lines). |
| 347 | */ |
| 348 | function countOldContentLines( |
| 349 | diffLines: DiffLine[], |
| 350 | startIdx: number, |
| 351 | endIdx: number, |
| 352 | ): number { |
| 353 | let count = 0; |
| 354 | for (let i = startIdx; i <= endIdx; i++) { |
| 355 | if (diffLines[i].type !== "new") { |
| 356 | count++; |
| 357 | } |
| 358 | } |
| 359 | return count; |
| 360 | } |
| 361 | |
| 362 | /** |
| 363 | * Process a changed area with a limited group size. |
| 364 | */ |
| 365 | function processLimitedSizeGroup( |
| 366 | diffLines: DiffLine[], |
| 367 | start: number, |
| 368 | end: number, |
| 369 | maxGroupSize: number, |
| 370 | offset: number, |
| 371 | ): DiffGroup { |
| 372 | // Calculate the starting line in old content. |
| 373 | let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1); |
| 374 | |
| 375 | // Track how many lines we have left in our group size budget. |
| 376 | let remainingGroupSize = maxGroupSize; |
| 377 | let currentLine = start; |
| 378 | const lines: DiffLine[] = []; |
| 379 | |
| 380 | // Process lines until we hit our size limit or reach the end. |
| 381 | while (currentLine <= end && remainingGroupSize > 0) { |
| 382 | // Add current line to results if we haven't seen it yet. |
| 383 | if ( |
| 384 | lines.length === 0 || |
| 385 | (lines.length > 0 && |
| 386 | lines[lines.length - 1].line !== diffLines[currentLine].line) |
| 387 | ) { |
| 388 | lines.push(diffLines[currentLine]); |
| 389 | } |
| 390 | |
| 391 | if (diffLines[currentLine].type === "old") { |
| 392 | currentLine++; |
| 393 | } else if (diffLines[currentLine].type === "same") { |
| 394 | remainingGroupSize--; |
| 395 | currentLine++; |
| 396 | } else if (diffLines[currentLine].type === "new") { |
| 397 | remainingGroupSize--; |
| 398 | currentLine++; |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | // Adjust for the last increment. |
| 403 | currentLine--; |
| 404 | |
| 405 | // Calculate the end line in old content. |
| 406 | let oldContentLineEnd = |
| 407 | oldContentLineStart + |
| 408 | countOldContentLines(diffLines, start, currentLine) - |
| 409 | 1; |
| 410 | |
| 411 | return { |
| 412 | startLine: oldContentLineStart + offset, |
| 413 | endLine: oldContentLineEnd + offset, |
| 414 | lines, |
| 415 | }; |
| 416 | } |
| 417 | |
| 418 | /** |
| 419 | * Process a changed area with flexible sizing. |
| 420 | */ |
| 421 | function processFlexibleSizeGroup( |
| 422 | diffLines: DiffLine[], |
| 423 | start: number, |
| 424 | end: number, |
| 425 | offset: number, |
| 426 | ): DiffGroup { |
| 427 | // Calculate the starting line in old content. |
| 428 | let oldContentLineStart = countOldContentLines(diffLines, 0, start - 1); |
| 429 | |
| 430 | // Calculate the end line in old content. |
| 431 | let oldContentLineEnd = |
| 432 | oldContentLineStart + countOldContentLines(diffLines, start, end) - 1; |
| 433 | |
| 434 | return { |
| 435 | startLine: oldContentLineStart + offset, |
| 436 | endLine: oldContentLineEnd + offset, |
| 437 | lines: diffLines.slice(start, end + 1), |
| 438 | }; |
| 439 | } |