| 414 | } |
| 415 | |
| 416 | function applyChunks(input: string, chunks: Chunk[]): string { |
| 417 | const originalLines = input.split('\n') |
| 418 | const destinationLines: string[] = [] |
| 419 | let originalIndex = 0 |
| 420 | |
| 421 | for (const chunk of chunks) { |
| 422 | if (chunk.origIndex > originalLines.length) { |
| 423 | throw new Error( |
| 424 | `applyDiff: chunk.origIndex ${chunk.origIndex} > input length ${originalLines.length}`, |
| 425 | ) |
| 426 | } |
| 427 | |
| 428 | if (originalIndex > chunk.origIndex) { |
| 429 | throw new Error( |
| 430 | `applyDiff: overlapping chunk at ${chunk.origIndex} (cursor ${originalIndex})`, |
| 431 | ) |
| 432 | } |
| 433 | |
| 434 | destinationLines.push(...originalLines.slice(originalIndex, chunk.origIndex)) |
| 435 | originalIndex = chunk.origIndex |
| 436 | |
| 437 | if (chunk.insLines.length > 0) { |
| 438 | destinationLines.push(...chunk.insLines) |
| 439 | } |
| 440 | |
| 441 | originalIndex += chunk.delLines.length |
| 442 | } |
| 443 | |
| 444 | destinationLines.push(...originalLines.slice(originalIndex)) |
| 445 | return destinationLines.join('\n') |
| 446 | } |
| 447 | |
| 448 | function applyDiff( |
| 449 | input: string, |