| 1 | import * as Diff from "diff"; |
| 2 | |
| 3 | interface SingleLineCompletionResult { |
| 4 | completionText: string; |
| 5 | range?: { |
| 6 | start: number; |
| 7 | end: number; |
| 8 | }; |
| 9 | } |
| 10 | |
| 11 | interface DiffType { |
| 12 | count?: number; |
| 13 | added?: boolean; |
| 14 | removed?: boolean; |
| 15 | value: string; |
| 16 | } |
| 17 | |
| 18 | function diffPatternMatches( |
| 19 | diffs: DiffType[], |
| 20 | pattern: DiffPartType[], |
| 21 | ): boolean { |
| 22 | if (diffs.length !== pattern.length) { |
| 23 | return false; |
| 24 | } |
| 25 | |
| 26 | for (let i = 0; i < diffs.length; i++) { |
| 27 | const diff = diffs[i]; |
| 28 | const diffPartType: DiffPartType = |
| 29 | !diff.added && !diff.removed ? "=" : diff.added ? "+" : "-"; |
| 30 | |
| 31 | if (diffPartType !== pattern[i]) { |
| 32 | return false; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | return true; |
| 37 | } |
| 38 | |
| 39 | type DiffPartType = "+" | "-" | "="; |
| 40 | |
| 41 | export function processSingleLineCompletion( |
| 42 | lastLineOfCompletionText: string, |
| 43 | currentText: string, |
| 44 | cursorPosition: number, |
| 45 | ): SingleLineCompletionResult | undefined { |
| 46 | const diffs: DiffType[] = Diff.diffWords( |
| 47 | currentText, |
| 48 | lastLineOfCompletionText, |
| 49 | ); |
| 50 | |
| 51 | if (diffPatternMatches(diffs, ["+"])) { |
| 52 | // Just insert, we're already at the end of the line |
| 53 | return { |
| 54 | completionText: lastLineOfCompletionText, |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | if ( |
| 59 | diffPatternMatches(diffs, ["+", "="]) || |
| 60 | diffPatternMatches(diffs, ["+", "=", "+"]) |
| 61 | ) { |
| 62 | // The model repeated the text after the cursor to the end of the line |
| 63 | return { |
| 64 | completionText: lastLineOfCompletionText, |
| 65 | range: { |
| 66 | start: cursorPosition, |
| 67 | end: currentText.length + cursorPosition, |
| 68 | }, |
| 69 | }; |
| 70 | } |
| 71 | |
| 72 | if ( |
| 73 | diffPatternMatches(diffs, ["+", "-"]) || |
| 74 | diffPatternMatches(diffs, ["-", "+"]) |
| 75 | ) { |
| 76 | // We are midline and the model just inserted without repeating to the end of the line |
| 77 | return { |
| 78 | completionText: lastLineOfCompletionText, |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | // For any other diff pattern, just use the first added part if available |
| 83 | if (diffs[0]?.added) { |
| 84 | return { |
| 85 | completionText: diffs[0].value, |
| 86 | }; |
| 87 | } |
| 88 | |
| 89 | // Default case: treat as simple insertion |
| 90 | return { |
| 91 | completionText: lastLineOfCompletionText, |
| 92 | }; |
| 93 | } |