Edit Context Api

Edit Context Api

The Edit Context API provides a robust set of tools for programmatically manipulating text with full context awareness. This API is designed for applications that require sophisticated text editing capabilities such as IDEs, code editors, document processors, and content management systems.

Key Features

  • Context-Aware Editing: Make changes to text while maintaining awareness of the surrounding content
  • Efficient Text Manipulation: Optimized algorithms for handling large documents
  • History Management: Built-in undo/redo capabilities
  • Selection Management: Robust selection model for handling cursor positions and text selections
  • Change Events: Comprehensive event system for tracking and responding to edits


Core Concepts

EditSession

The EditSession is the central object that manages a text document. It provides methods for modifying the text and accessing the document state.

interface EditSession {
  // Document content
  getText(): string;
  setText(text: string): void;
  
  // Selection management
  getSelection(): Selection;
  setSelection(selection: Selection): void;
  
  // Editing operations
  insert(position: Position, text: string): void;
  remove(range: Range): void;
  replace(range: Range, text: string): void;
  
  // History management
  undo(): void;
  redo(): void;
  
  // Event handling
  on(event: string, callback: Function): void;
  off(event: string, callback: Function): void;
}        


Position and Range

Positions and ranges are used to locate points and sections within the document.

interface Position {
  row: number;    // Zero-based line number
  column: number; // Zero-based column number
}

interface Range {
  start: Position;
  end: Position;
}        


Selection

The Selection object represents the current user selection or cursor position.

interface Selection {
  getRange(): Range;
  setRange(range: Range): void;
  
  // Convenience methods
  selectAll(): void;
  selectWordAt(position: Position): void;
  selectLine(row: number): void;
  
  isEmpty(): boolean;
  isMultiLine(): boolean;
}        


Usage Examples

Basic Text Editing

// Create a new edit session
const session = EditContext.createSession("Initial document text");

// Insert text at a specific position
session.insert({ row: 0, column: 0 }, "Hello, world!\n");

// Get the current text
const text = session.getText();
console.log(text); // "Hello, world!\nInitial document text"

// Replace a range of text
const range = {
  start: { row: 0, column: 0 },
  end: { row: 0, column: 13 }
};
session.replace(range, "Greetings!");

// Undo the last change
session.undo();        


Working with Selections

// Get the current selection
const selection = session.getSelection();

// Select an entire line
selection.selectLine(2);

// Get the selected text
const range = selection.getRange();
const selectedText = session.getText().substring(
  session.positionToIndex(range.start),
  session.positionToIndex(range.end)
);

// Replace the selection with new text
session.replace(range, "New text");        


Listening for Changes

// Listen for text changes
session.on("change", (e) => {
  console.log("Text changed:", e.data);
  console.log("New document length:", session.getText().length);
});

// Listen for selection changes
session.on("changeSelection", (e) => {
  const selection = session.getSelection();
  console.log("Selection changed:", selection.getRange());
});        

Advanced Features

Document Markers

Markers are persistent anchors in the document that maintain their relative positions as edits occur.

// Create a marker
const markerId = session.addMarker({
  range: {
    start: { row: 1, column: 5 },
    end: { row: 1, column: 10 }
  },
  type: "error",
  message: "Syntax error"
});

// Get marker information
const marker = session.getMarker(markerId);

// Remove marker
session.removeMarker(markerId);        


Custom Tokenizers

For syntax highlighting and language-specific features:

// Set a custom tokenizer
session.setTokenizer({
  getLineTokens: (line, state) => {
    // Return tokens for the given line
    return {
      tokens: [
        { type: "keyword", value: "function" },
        { type: "text", value: " " },
        { type: "identifier", value: "example" },
        // ...
      ],
      state: newState
    };
  }
});        

Document Folding

Supports code folding to hide and show sections of text:

// Create a fold
session.addFold("Fold comment", {
  start: { row: 5, column: 0 },
  end: { row: 7, column: 0 }
});

// Expand all folds
session.expandAllFolds();        


Best Practices

  1. Batch Operations: Use transaction methods to batch multiple operations for better performance:

session.startTransaction();
// Multiple edit operations
session.endTransaction();        

2. Memory Management: For large documents, consider using document chunking:

session.setChunkSize(1000); // Lines per chunk        

3. Error Handling: Always wrap edit operations in try/catch blocks

try {
  session.replace(range, newText);
} catch (err) {
  console.error("Edit operation failed:", err);
}        


Reference

For the complete API reference, please refer to the official documentation.

Himanshu Maurya

MERN Stack Developer @arramton | Frontend | Backend | Next.js | React.js | Javascript | Typescript | Tailwind CSS | Zustand | Redux | Node.js | Express.js | MongoDB | Cloudinary | Razorpay | Software Dev | Ex-iLearnings

1d

Thoughtful post, thanks Fardeen

Like
Reply
sanjay yadav

MERN Developer | NodeJS | ReactJS | NextJS | MySql | MongoDB | Redis | GraphQL | React Query

1w

Impressive, Fardeen

Like
Reply

To view or add a comment, sign in

More articles by Fardeen Qureshi

  • Picture-in-Picture API

    The Picture-in-Picture (PiP) API is a web API that allows developers to create a floating, always-on-top video window…

  • Web Cypto Api

    The Web Cypto Api is the powerful cryptographic interface built into the Modern Web Browsers that enables developers to…

  • Drag and Drop Web API

    Introduction The Drag and Drop API, introduced with HTML5, allows developers to implement native drag-and-drop…

  • Virtual Keyboard API

    Introduction As more users access websites from mobile and touchscreen devices, managing the virtual (on-screen)…

  • Abort Controller

    Modern Web Applications often perform the asynchrous operations like network requests, which may become obsolete if the…

  • Media Capture and Streams API (Media Stream)

    The Media Capture and Streams API, commonly referred to as the MediaStream API or , allows web applications to access…

  • The Ideal Detection API

    Ideal Detection Api provides the means to detect the user idle status,active,idle and locked,and to be notified of…

  • Web Share Api

    The Web Share Api is a simple Javascript API that allows the web apps to share the content (text,URLs, or files) using…

  • Page Visibility Api

    The Page Visibility API is a web standard provided by modern browsers that allows developers to determine the…

  • Screen Wake Lock Api

    The Screen Wake Lock API allows web applications to request that a device’s screen remains on, even if the user is not…

Insights from the community

Others also viewed

Explore topics