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
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");
Recommended by LinkedIn
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
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.
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
1dThoughtful post, thanks Fardeen
MERN Developer | NodeJS | ReactJS | NextJS | MySql | MongoDB | Redis | GraphQL | React Query
1wImpressive, Fardeen