# Editor API

Look up the current public creation options, instance methods, and incremental events.

Type signatures are extracted from the current MSFE public exports. Initial configuration applies only at mount time; use instance methods for subsequent state changes.

## Creation function

### createMsfeEditor

Validates and acquires the source before mounting, rolling back every partial installation on failure.
@param options - Editor mount and extension configuration.
@returns Independent disposable editor.

```ts
function createMsfeEditor(options: MsfeEditorOptions): MsfeEditor
```

## Creation options

Provide a browser mount element as `parent`. Set `markdown`, `extensions`, `mode`, and host callbacks as needed.

### MsfeEditorOptions

Browser editor creation options; the host owns storage and file decoding.

```ts
export interface MsfeEditorOptions {
    readonly parent: HTMLElement;
    readonly markdown?: string;
    readonly documentId?: string;
    readonly mode?: MsfeMode;
    readonly readOnly?: boolean;
    readonly theme?: "light" | "dark";
    readonly extensions?: readonly AnyExtension[];
    readonly icons?: MsfeIconFactory;
    readonly codeLanguages?: readonly CodeLanguage[];
    readonly searchPanel?: ComponentViewRenderer<SearchPanelProps>;
    readonly componentHost?: MsfeComponentHost;
    readonly label?: string;
    readonly onChange?: (event: MsfeChangeEvent) => void;
    readonly onError?: (error: unknown) => void;
}
```

**parent** — Host element into which one CodeMirror view is mounted.

**markdown** — Decoded initial Markdown.

**documentId** — Optional host document key; defaults to a fresh id.

**mode** — Initial presentation, defaulting to source.

**readOnly** — Explicit source/live readonly setting.

**theme** — Initial editor color theme.

**extensions** — Validated feature descriptors, scoped to this instance.

**icons** — Shared design icon renderer for folding and search controls.

**codeLanguages** — Exact lazy fence-language catalog; omitted or unknown names remain plain text.

**searchPanel** — Optional search UI, mounted under the existing framework/provider host.

**componentHost** — Framework portal store supplied by an adapter; the consumer owns its disposal.

**label** — Accessible name of the editable region.

**onChange** — Optional incremental source change listener.

**onError** — Reports errors from host listeners and CodeMirror plugins.

## Editor instance

`commands` runs commands, `can()` checks applicability, and `chain()` combines operations into one dispatch. If a command is unavailable, inspect its return value and `lastCommandResult`.

### MsfeEditor

Framework-neutral experimental MSFE public surface.

```ts
export interface MsfeEditor {
    readonly history: MsfeHistory;
    readonly scope: TaskScope;
    readonly documentScope: TaskScope;
    captureAnchor(range: MsfeSourceRange, policy?: RangePolicy): SourceAnchor;
    querySource(name: string, range?: MsfeSourceRange): SourceQuery;
    isActive(name: string, attrs?: Readonly<Record<string, unknown>>): boolean;
    getAttributes(name: string): Readonly<Record<string, unknown>> | null;
    getState<T>(slot: StateSlot<T>): T;
    subscribeState<T>(subscription: StateSubscription<T>): () => void;
    readonly commands: SingleCommands;
    readonly lastCommandResult: MsfeResult | undefined;
    readonly storage: Readonly<Record<string, unknown>>;
    readonly element: HTMLElement;
    readonly state: EditorState;
    readonly documentId: string;
    readonly revision: number;
    readonly mode: MsfeMode;
    readonly work: Readonly<MsfeWorkCounters>;
    getMarkdown(): string;
    captureTarget(): MsfeTarget;
    run(command: MsfeCommand, target?: MsfeTarget): MsfeResult;
    chain(target?: MsfeTarget): MsfeCommandChain;
    chain(commands: readonly MsfeCommand[], target?: MsfeTarget): MsfeResult;
    can(): CanCommands;
    can(command: MsfeCommand, target?: MsfeTarget): boolean;
    applyChanges(change: MsfeExternalChange): MsfeResult;
    replaceDocument(markdown: string, documentId: string): MsfeResult;
    setMode(mode: MsfeMode): void;
    setReadOnly(readOnly: boolean): void;
    setTheme(theme: "light" | "dark"): void;
    setSelection(selection: EditorSelection): void;
    updateViewState(update: MsfeViewStateUpdate): MsfeResult;
    scrollTo(position: number): void;
    focus(): void;
    undo(): boolean;
    redo(): boolean;
    onChange(listener: (event: MsfeChangeEvent) => void): () => void;
    destroy(): void;
}
```

**history** — Availability of the instance's sole content history implementation.

**scope** — Editor lifetime for instance resources.

**documentScope** — Current document lifetime, replaced even when the host reuses its documentId.

**captureAnchor** — @param range - Source range to track.
@param policy - Explicit mapping choices.
@returns Cancellable mapped intent.

**querySource** — @param name - Semantic extension name.
@param range - Bounded query, default all current selections.
@returns Parse-aware source matches.

**isActive** — @param name - Semantic type.
@param attrs - Optional exact field constraints.
@returns Whether every selection has a matching owner.

**getAttributes** — @param name - Semantic type.
@returns Uniform selected fields, or null for mixed, absent or pending syntax.

**getState** — @param slot - Installed transaction state.
@returns Current immutable value.

**subscribeState** — @param subscription - Bounded selector with equality and observer.
@returns Unsubscribe callback.

**commands** — Installed typed commands; missing runtime features return not-installed.

**lastCommandResult** — Diagnostic outcome of the last executed named command/chain; can() leaves it unchanged.

**storage** — Per-extension instance storage, keyed by unique id.

**element** — Mounted editor wrapper; content DOM stays CodeMirror-owned.

**state** — Current immutable CodeMirror state.

**documentId** — Current host document identity.

**revision** — Monotonic instance revision, also advanced by explicit document replacement.

**mode** — Actual presentation, excluding deferred composition requests.

**work** — Snapshot of deterministic work counts.

**getMarkdown** — @returns Markdown with the retained file-format policy.

**captureTarget** — @returns A versioned, directed selection target.

**run** — @param command - Pure planner.
@param target - Optional captured target.
@returns Mutation result.

**chain** — @param target - Optional captured intent.
@returns New typed atomic chain.
@param commands - Atomic ordered planners.
@param target - Optional captured target.
@returns Mutation result.

**can** — @returns Typed side-effect-free command queries.
@param command - Pure planner.
@param target - Optional captured target.
@returns Applicability without dispatch.

**applyChanges** — @param change - Versioned external changes.
@returns Accepted or rejected mutation.

**replaceDocument** — @param markdown - New document source.
@param documentId - New host identity.
@returns History/selection reset result.

**setMode** — @param mode - Requested mode, deferred until composition ends.

**setReadOnly** — @param readOnly - Editing permission independent of presentation.

**setTheme** — @param theme - Color theme, preserving the view and history.

**setSelection** — @param selection - Directed source ranges.

**updateViewState** — @param update - Source-neutral effects and optional selection.
@returns Readonly-safe acceptance, or a lifecycle/invalid-update diagnostic.

**scrollTo** — @param position - Logical source position to bring into view.

**focus** — Focuses the document when requested by the host.

**undo** — @returns Whether one history event was undone.

**redo** — @returns Whether one history event was redone.

**onChange** — @param listener - Incremental change observer.
@returns Unsubscribe callback.

**destroy** — Idempotently releases view plugins, resources and listeners.

## Document changes

Events preserve incremental edits and origin information without serializing the entire document by default. Observer errors are reported through the host error callback.

### MsfeChangeEvent

An accepted source change, without an eagerly serialized document.

```ts
export interface MsfeChangeEvent {
    readonly documentId: string;
    readonly revision: number;
    readonly changes: ChangeSet;
    readonly selection: EditorSelection;
    readonly origin: string;
}
```

**documentId** — Host-visible document identity.

**revision** — Accepted source revision after this change.

**changes** — Exact mapping from preceding source to accepted source.

**selection** — Directed selection after the change.

**origin** — User, command, history or host-provided origin.

## Find methods by task

| Task | Combination | Guide |
| --- | --- | --- |
| Save | getMarkdown + onChange | [Serialized saving](/en/guide/saving) |
| External same-document edits | applyChanges + identity/revision | [External updates](/en/guide/saving) |
| Switch files | replaceDocument + fresh resources | [Lifecycle](/en/guide/lifecycle) |
| Format toolbar | can / isActive / getAttributes / subscribeState | [Toolbars](/en/customization/toolbars) |
| Compound action | chain(...).run() | [Commands](/en/guide/commands) |
| Write after a dialog | captureTarget or captureAnchor | [Captured intent](/en/guide/selection) |
| Reading preferences | defineState + updateViewState | [State](/en/guide/state) |
| Diagnose behavior | onError / lastCommandResult / work | [Diagnostics](/en/guide/debugging) |

Read the minimum necessary source in selectors and queries. Do not keep invoking disposed instances or pass their old state to another editor.
