Skip to content

codemirror/editor-mode-extension

Scopes an editor extension to one editor mode: createLivePreviewOnlyExtension keeps it in Live Preview only, and createSourceModeOnlyExtension in Source mode only. The extension is switched on and off as a whole, so its decorations, view plugins and state fields need no mode check of their own.

The mode is Obsidian’s editorLivePreviewField. Read from Obsidian 1.15.1, a Markdown editor gets the field from editorLivePreviewField.init() whenever its state is built, and a mode switch dispatches one transaction carrying a private effect that sets the field, beside the reconfigure of its dynamic extensions. So the field changes only in a transaction with effects, or with a new state.

Each call wraps the extension in a Compartment of its own, which holds the extension or nothing in every editor separately. A transaction extender reconfigures it in the same transaction that changes the mode, so no update ever renders with the wrong content. A new state cannot be read before it exists, so it starts with the content the Live Preview default calls for, and a view plugin corrects it in a microtask, which runs before the browser paints.

Outside an Obsidian Markdown editor there is no editorLivePreviewField, and the editor counts as Live Preview.

Function Description
createLivePreviewOnlyExtension Wraps an extension so it is active only while the editor is in Live Preview, and switched off in Source mode.
createSourceModeOnlyExtension Wraps an extension so it is active only while the editor is in Source mode, and switched off in Live Preview. Outside an Obsidian Markdown editor the editor counts as Live Preview, so the extension stays off there.
isLivePreview Tells whether an editor state is in Live Preview.