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