Replace Operation

Replace content in a range with new content.

Overview

The replace operation combines delete and insert in a single operation. Can be decomposed into delete + insert for transaction grouping.

Interface

interface ReplaceOperation extends Operation {
  type: 'replace';
  path: Path;
  length: number; // Length of content to replace
  content: string | Node; // New content
  deletedContent?: any; // Store deleted content for undo
}

Usage

function replaceSelection(editor: Editor, selection: Selection, newText: string) {
  const operation: ReplaceOperation = {
    type: 'replace',
    path: selection.start,
    length: selection.length,
    content: newText,
    deletedContent: editor.getContent(selection)
  };
  
  editor.applyOperation(operation);
}

// Replace can be decomposed into delete + insert
function replaceAsTransaction(editor: Editor, selection: Selection, newText: string) {
  const tx = editor.beginTransaction();
  
  tx.add({
    type: 'deleteContent',
    path: selection.start,
    length: selection.length
  });
  
  tx.add({
    type: 'insertText',
    path: selection.start,
    text: newText
  });
  
  tx.commit();
}