All files / src textDocumentEdits.ts

95.23% Statements 20/21
75% Branches 6/8
100% Functions 2/2
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38                  8x 8x 8x 8x   8x 43x 20x 23x 15x 15x 15x 15x 15x 8x 8x 8x       8x       4x 4x 4x    
import * as vscode from 'vscode';
import diff from 'fast-diff';
 
export interface DocumentEditResult {
  edit: vscode.WorkspaceEdit;
  hasChanges: boolean;
}
 
export function createTextDocumentEdit(document: vscode.TextDocument, nextContent: string): DocumentEditResult {
  const currentText = document.getText();
  const edit = new vscode.WorkspaceEdit();
  let offset = 0;
  let hasChanges = false;
 
  for (const [op, text] of diff(currentText, nextContent)) {
    if (op === diff.EQUAL) {
      offset += text.length;
    } else if (op === diff.DELETE) {
      const start = document.positionAt(offset);
      const end = document.positionAt(offset + text.length);
      edit.delete(document.uri, new vscode.Range(start, end));
      offset += text.length;
      hasChanges = true;
    } else Eif (op === diff.INSERT) {
      edit.insert(document.uri, document.positionAt(offset), text);
      hasChanges = true;
    }
  }
 
  return { edit, hasChanges };
}
 
export async function applyTextDocumentContent(document: vscode.TextDocument, nextContent: string) {
  const { edit, hasChanges } = createTextDocumentEdit(document, nextContent);
  Iif (!hasChanges) return true;
  return vscode.workspace.applyEdit(edit);
}