Selection
Read, observe, capture, and restore semantic document selections.
Selection is reported as semantic blocks, offsets, marks, comment IDs, and change IDs, with no canvas coordinates.
Reading and observing#
const snapshot = editor.selection.getSnapshot();
snapshot.empty; // true for a caret, false for a range
snapshot.text; // selected text
snapshot.target; // portable ranges for comments/formatting
snapshot.selectionTarget; // explicit start/end for insert/replace
snapshot.activeMarks; // e.g. ["bold", "italic"]
snapshot.activeCommentIds;
snapshot.activeChangeIds;
useEffect(() => editor.selection.observe(setSelection), [editor]);observe() passes snapshot; subscribe() passes { snapshot }. Both return an unsubscribe function and deduplicate unchanged snapshots.
Capture and restore#
Moving focus into external UI (such as a popover input) clears the editor selection. Capture it before opening custom UI and restore it afterward:
const capture = editor.selection.capture();
// Focus moves to host UI...
const result = editor.selection.restore(capture);
if (!result.success) {
// result.reason: "not-ready" | "read-only" | "missing-target" | "stale"
}capture() returns a frozen, document-scoped snapshot, or null when there is no caret or selection. restore() restores the selection and focuses the editor, failing cleanly if the editor is unavailable, read-only, scoped to another document, or mutated since capture.
Clearing#
editor.selection.clear();Agent access#
External agents do not receive the selection automatically. Expose the get_selection tool when the model needs the user's current selection (returns the same semantic snapshot without geometry).