Plugin Helpers
@mnaoumov/obsidian-lib provides some helpers to simplify your own Obsidian plugin.
- Sample Plugin Extended - sample with different technologies included.
- create-obsidian-plugin - creates a plugin from scratch.
The links below contains the full documentation. Here in the docs we mention only the most important ones.
The core File Explorer has two spots that stand for the vault root: the vault name at the top of the left sidebar, and the empty area below the file list. FileExplorerRootMenuComponent hands your handler the context menu of either spot just before it is shown, and tells you which spot it was.
import { FileExplorerRootMenuComponent, FileExplorerRootMenuSpot} from '@mnaoumov/obsidian-lib/components/file-explorer-root-menu-component';import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase { protected override async onloadImpl(): Promise<void> { await super.onloadImpl(); this.addChild(new FileExplorerRootMenuComponent({ app: this.app, handler: ({ menu, spot }) => { menu.addItem((item) => item.setTitle(spot === FileExplorerRootMenuSpot.VaultName ? 'From the vault name' : 'From the empty area')); } })); }}- On the empty area, the menu is the root folder menu Obsidian opens there, after every
file-menuhandler has run. - On the vault name, the menu is the one Obsidian opens there itself (
Show in system explorer,Copy pathon desktop), so no second menu appears. A menu that is still empty after every handler is not shown. shouldPresentRootAsFolder: truepresents the root as an ordinary folder while its menu is built, so Obsidian and other plugins add the items they add to any folder. The items that must not act on the root (rename, delete, move, make a copy, search in folder) are removed again, and on the vault name the root folder menu replaces Obsidian’s vault menu.- Any number of these components, in any number of plugins, share one installation per app: one prototype patch and one listener, so every handler sees the same menu once.
PluginBase is a base class for plugins, that has some additional useful features to standard Obsidian Plugin class.
import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase {}The most important methods to override:
onloadImpl()- your load logic. Add child components here withaddChild(); the universal components, such aspluginNoticeComponentandconsoleDebugComponent, are already available.getPluginApis(),getPluginDependencies(),getPluginConflicts()- declare the APIs the plugin publishes and the plugins it needs or conflicts with. See Cross-plugin APIs.createTranslationsMap()- supply the plugin’s own translations, each language as an object or as a loader that is called only when that language is shown. See Translations.
Three are public Obsidian methods that PluginBase already implements, so you rarely override them: onload(), onExternalSettingsChange() and onunload(). Settings are loaded and saved by the plugin’s settings component, whose onLoadSettings() and onSaveSettings() hooks you override there; see the PluginSettingsComponentBase section below.
Async cleanup across a reload
Section titled “Async cleanup across a reload”Obsidian’s onunload is synchronous, and nothing awaits the work it starts. When a plugin is disabled and enabled again, reloaded, or updated while enabled, Obsidian unloads the old instance and immediately loads the new one. So teardown that finishes asynchronously, such as closing an IndexedDB connection, may still be running when the new instance opens the same database.
registerAsyncCleanup() solves that inside the ordinary lifecycle. The cleanup starts when the plugin’s feature surface unloads. The next instance of the same plugin waits for it before it loads, and so does the feature surface when the dependency gate opens again. The wait is bounded by getAsyncCleanupTimeoutInMilliseconds(), 10 seconds by default; after that the plugin loads anyway, logs a warning and shows a notice saying so. A wait longer than getAsyncCleanupNoticeDelayInMilliseconds(), 500 milliseconds by default, shows a notice that the load is paused until the previous unload finishes, hidden again when it does; a shorter wait shows nothing. A cleanup that throws is printed and never stops the next load.
import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase { protected override async onloadImpl(): Promise<void> { const database = await openDatabase(); this.registerAsyncCleanup(async () => { await waitForPendingTransactions(database); database.close(); }); }}The pending cleanups are kept in the realm-wide shared state under the plugin id, so the wait works even when the old and new instances bundle different versions of this library. Outside PluginBase, registerPluginAsyncCleanup({ component, pluginId, cleanup }) and didPluginAsyncCleanupsSettle({ pluginId }) from @mnaoumov/obsidian-lib/plugin/plugin-async-cleanup are the two halves. An app restart needs neither, since the whole renderer goes away.
this.pluginNoticeComponent shows notices prefixed with the plugin name and tied to the plugin lifecycle. Prefer it over constructing an Obsidian Notice directly. It is a protected member of PluginBase, so reach it from inside your plugin class, or pass it to the components that need it.
import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase { protected override onloadImpl(): void { this.pluginNoticeComponent.showNotice('Something happened'); }}showNotice(message, options?) accepts these options:
isPermanent(defaultfalse) — the notice stays until it is replaced, the plugin reloads, or the user dismisses it. There is at most one permanent notice per plugin.isReusable(defaulttrue) — the notice occupies the single per-plugin reusable slot, so the next reusable notice hides it. Passfalsefor a standalone notice that no later notice hides (multiple standalone notices coexist); standalone notices are still hidden together on unload.requiresCloseConfirmation(defaultfalse) — a hard-to-close notice: it never dismisses on a stray click and instead shows a close (X) button whose click opens a confirmation modal, dismissing the notice only if confirmed. It is shown with an infinite duration and is standalone (impliesisReusable: false).onHide— a callback invoked the first time the notice is hidden, whether by the user closing it, by a later reusable notice replacing it, by its duration elapsing, or on unload.
The implication rules are enforced — a contradictory combination throws:
- A permanent notice must be reusable, so
isPermanent: truetogether withisReusable: falsethrows. - A hard-to-close notice is standalone, so
requiresCloseConfirmation: truetogether withisReusable: truethrows.
import { PluginSettingsComponentBase } from '@mnaoumov/obsidian-lib/components/plugin-settings-component';
export class FooPluginSettings { public invalidCharacterAction: 'Remove' | 'Replace' = 'Remove'; public replacementCharacter = '_';}
export class FooPluginSettingsComponent extends PluginSettingsComponentBase<FooPluginSettings> {}The default settings are a default-constructed instance of the settings class, passed to the component’s constructor as pluginSettingsClass.
The most important methods in the execution order:
registerValidators()onLoadRecord()onSavingRecord()
The data.json size limit
Section titled “The data.json size limit”PluginDataHandler, the dataHandler a settings component reads and writes through, refuses a data.json larger than DEFAULT_PLUGIN_DATA_MAX_SIZE_IN_BYTES (16 MiB). Obsidian sets no limit of its own. It reads and parses the whole file on every startup, and it swallows a failed read or write. So the guard runs before Obsidian is called:
- Load. The handler reads the file’s size through
app.vault.adapter.statbeforePlugin.loadDatareads it. An oversized file throwsPluginDataSizeLimitExceededErrorand is never read, so the plugin fails to load. The file stays as it is and is never replaced with defaults. - Save. The handler serializes the data the way Obsidian writes it (
JSON.stringify(data, undefined, 2)) and counts the UTF-8 bytes, so indentation and multi-byte text count. An oversized save throws before anything is written.saveToFile()then puts the in-memory settings back to the last saved ones, so the file and memory still agree, and rethrows the error. A value that JSON cannot serialize, such as a cyclic object, also throws instead of being dropped silently.
The error names the plugin, the path, the size and the limit (pluginId, pluginName, path, sizeInBytes, maxSizeInBytes, operation). Change the limit per plugin:
import { PluginDataHandler } from '@mnaoumov/obsidian-lib/data-handler';
const dataHandler = new PluginDataHandler(plugin, { maxSizeInBytes: 1024 * 1024 });Infinity turns the guard off. The limit protects startup and is not an Obsidian Sync quota, which depends on the plan. Keep data.json for small settings. If it grows with the vault, move the growing part to the plugin data stores.
Damaged data.json and recovery copies
Section titled “Damaged data.json and recovery copies”Obsidian’s Plugin.loadData resolves undefined both when data.json is missing and when it exists but does not parse (truncated by a sync tool, a crash mid-write, a hand edit). A settings component that read the second case as “nothing stored” would save its defaults over the user’s settings. So when Obsidian answers undefined or null, PluginDataHandler reads the file itself:
- Missing, or valid JSON. The handler returns what the file holds, as before.
- Not valid JSON. The handler keeps a copy of the raw text in its
recoveryStore, shows a notice naming the plugin and the path, and throwsPluginDataParseError. The file is never touched.PluginSettingsComponentBasethen runs on the defaults in memory (a reload keeps the settings already in memory) and writes nothing until the user changes a setting. When no copy could be kept, the load fails instead, so nothing is ever saved over the only copy.
The initial load also saves the normalized settings back to data.json. When that save would drop or change a stored value (an unknown key from a newer plugin version, a legacy migration), the component keeps a copy of the original record first, and skips the save if the copy cannot be kept. A save that only adds defaults for missing keys loses nothing and keeps no copy.
The default recoveryStore is a LocalSettingsRecoveryStore: a LocalDataStore on this device, so no sync tool carries the copies anywhere, holding the newest five copies per plugin. getRecoveryCopies() lists them, newest first, and restoreRecoveryCopy(id) writes one back to data.json and reloads it, keeping the settings in use as a copy first. Pass recoveryStore: null to keep no copies.
Reset, export and import
Section titled “Reset, export and import”resetToDefaults(context?) sets every setting to its default and saves. exportToJson() returns the settings as entered, invalid values included, as the JSON data.json would hold. importFromJson(json, context?) replaces every setting with the ones in such a record, read exactly as data.json is: legacy converters and the transformer run, a setting the record lacks takes its default, and an unknown key is ignored. An invalid value is kept as entered, and the plugin uses its default until it is fixed. The import answers with the invalidPropertyNames and the unknownPropertyNames. Text that is not a JSON object throws PluginSettingsImportError and changes nothing. Before a reset or an import changes anything, the settings in use are kept as a recovery copy.
import { PluginSettingsTabBase } from '@mnaoumov/obsidian-lib/plugin/plugin-settings-tab';
export class FooPluginSettingsTab extends PluginSettingsTabBase<FooPluginSettings> {}Obsidian 1.13 renders a settings tab from the definitions it returns, so a tab describes its rows instead of building them into a container. Override getSettingDefinitionItems() and build each row with settingEx(), grouping them with settingGroupEx():
import type { SettingDefinitionItem } from 'obsidian';
import { PluginSettingsTabBase } from '@mnaoumov/obsidian-lib/plugin/plugin-settings-tab';
export class FooPluginSettingsTab extends PluginSettingsTabBase<FooPluginSettings> { protected override getSettingDefinitionItems(): SettingDefinitionItem[] { return [ this.settingGroupEx({ heading: 'Invalid characters', items: [ this.settingEx({ desc: 'How to process invalid characters in the new title.', name: 'Invalid characters action', render: (setting) => { setting.addDropdown((dropdown) => { dropdown.addOptions({ Remove: 'Remove', Replace: 'Replace' }); this.bind({ onChanged: () => { this.refreshDomState(); }, propertyName: 'invalidCharacterAction', valueComponent: dropdown }); }); } }), this.settingEx({ disabled: () => this.pluginSettingsComponent.settings.invalidCharacterAction !== 'Replace', name: 'Replacement character', render: (setting) => { setting.addText((text) => { this.bind({ propertyName: 'replacementCharacter', valueComponent: text }); }); } }) ] }) ]; }}Notes:
- The
settingarendercallback receives is a fullSettingEx, so every custom component adder (addNumber(),addMultipleText(),addCodeHighlighter(), …) andbind()work exactly as they do in an imperative tab. getSettingDefinitionItems()must be a pure builder. Obsidian calls it when the tab is registered — at plugin load, long before the tab is opened — to index the settings for search. Put anything with a side effect inside arendercallback, which runs only when the row is actually rendered.disabledandvisibleaccept a function, re-evaluated on every render and on everyrefreshDomState(). PreferrefreshDomState()when only those predicates change: it toggles the rendered DOM in place. Userefresh()only when the structure changes, i.e. rows are added or removed.- Native
controldefinitions are supported too —getControlValue()/setControlValue()are wired to the settings component — butrender+bind()is the richer path: it carries validation messages, the reset-when-empty behavior, placeholders for default values, and the value converters. - A tab that has not migrated keeps working: leave
getSettingDefinitionItems()alone and overridedisplayLegacy(), which Obsidian falls back to when the definitions are empty. settingsManagementEx()builds a ready-made row with three buttons: Reset to defaults and Import from clipboard, each after a confirmation, and Export to clipboard. Add it to the definitions, usually last. An imperative tab callsrenderSettingsManagement(setting)instead. Where the clipboard refuses a write, the JSON is shown for copying by hand. Where it refuses a read, as it can on mobile, the user pastes the JSON into a prompt. While this device keeps recovery copies ofdata.json, the row gains a fourth button,Recovery copies (<n>), and a plugin with none gains nothing. It opens a list of the copies, each with its date, why it was kept and a preview of its text. A copy that is valid JSON can be restored, after a confirmation saying the settings in use are kept as a copy first. A copy of a file that did not parse cannot be restored as it is, so its button copies the text to the clipboard instead, for a repair by hand and an import.
The most important methods in the execution order:
getSettingDefinitionItems()(ordisplayLegacy()for the imperative fallback)settingGroupEx()/settingEx()bind()
app.vault.adapter.rmdir(path, recursive) does not honor recursive: false, and the two adapters get it wrong in opposite directions:
CapacitorAdapter(mobile) does not accept the argument at all - it always removes recursively, so a non-recursive call silently deletes the folder and everything under it.FileSystemAdapter(desktop) forwards it tofs.promises.rm(path, { recursive }), which throwsERR_FS_EISDIRfor any directory whenrecursiveisfalse- so the non-recursive call never succeeds, not even on an empty folder.
RmdirGuardComponent gives both platforms the same, correct behavior while it is loaded: a folder that still has children is refused with an error carrying code: 'ENOTEMPTY' and nothing is deleted, and an empty folder is removed. Calls that already pass recursive: true, and calls whose target is not a folder, are passed through untouched.
Emptiness is decided from the adapter, not from the vault file tree - the tree omits dot-prefixed and otherwise hidden entries, so a folder holding only hidden files reads as empty there and the guard would wave through exactly the deletion it exists to prevent.
It is deliberately opt-in. app.vault.adapter is shared by the whole app, so a library that installed this patch on its own would change rmdir semantics for every other plugin, including the ones that never asked for it. A plugin that deletes folders opts in for itself:
import { RmdirGuardComponent } from '@mnaoumov/obsidian-lib/components/rmdir-guard-component';import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase { protected override onloadImpl(): void { this.addChild(new RmdirGuardComponent(this.app)); }}Check error.code === 'ENOTEMPTY' rather than instanceof - every plugin bundles its own copy of the library, so the error may cross a copy boundary.
SyntaxHighlightingComponent registers your own syntax highlighting languages and unregisters them when it is unloaded. Add it as a child of your plugin: const syntaxHighlightingComponent = this.addChild(new SyntaxHighlightingComponent());, as in the example below.
Obsidian highlights code through two independent registries, so there are two methods:
registerPrismLanguage({ grammar, language })- registers a Prism language, which highlights code in reading view and in every<pre><code>the library renders, including theSettingEx.addCodeHighlighter()field.registerCodeBlockLanguage({ editorMode, language, prismGrammar })- additionally registers a CodeMirror 5 mode, which is what highlights a fenced code block inside the editor.editorModeis the mode name or MIME type the fence is highlighted as, e.g.text/typescript. OmitprismGrammarwhen the fence is replaced in reading view, e.g. rendered as a button.
grammar / prismGrammar accepts three forms:
- a
Grammarobject - the grammar itself. - a
string- the name of an already registered language to alias, e.g.'typescript'. - a factory
({ prism, requirePrismLanguage }) => Grammar- builds the grammar from the loaded Prism module, so you never need to callloadPrism()yourself. UserequirePrismLanguage('javascript')to nest an existing language’s grammar into your own.
A missing language always throws - both when aliasing a language that is not registered and from requirePrismLanguage() - so a typo fails loudly instead of silently leaving your code without highlighting.
import { SyntaxHighlightingComponent } from '@mnaoumov/obsidian-lib/components/syntax-highlighting-component';import { PluginBase } from '@mnaoumov/obsidian-lib/plugin/plugin';
export class FooPlugin extends PluginBase { protected override async onloadImpl(): Promise<void> { const syntaxHighlightingComponent = this.addChild(new SyntaxHighlightingComponent()); await syntaxHighlightingComponent.registerCodeBlockLanguage({ editorMode: 'text/typescript', language: 'my-language', prismGrammar: 'typescript' }); }}Opening a sidebar view
Section titled “Opening a sidebar view”A “show my view” command usually wants one leaf of its view type: the existing one, wherever the user dragged it, or a new sidebar leaf. Obsidian’s own Workspace.ensureSideLeaf already does all of it, so this library adds no helper for it. Read from Obsidian 1.15.1, it takes the first leaf of the type when one exists, wherever it is, and creates one in the requested sidebar only when none does. It loads a deferred view, applies state when you pass it, reveals the leaf (expanding a collapsed sidebar, reveal defaults to true) and focuses it when active is set. The core plugins open the file explorer, search, backlinks, outline and tags this way.
const MY_VIEW_TYPE = 'my-plugin-view';
async function openMyView(): Promise<void> { await app.workspace.ensureSideLeaf(MY_VIEW_TYPE, 'right', { active: true });}Avoid the older recipe that detaches every leaf of the type and then opens a new one. It throws away the user’s placement of the view and its state.
Working with plugin settings
Section titled “Working with plugin settings”Most of the times, it’s enough to use this.pluginSettingsComponent.settings (pluginSettingsComponent is a protected member of PluginBase) which is just an alias to this.pluginSettingsComponent.settingsState.effectiveValues.
For more advanced scenarios, you can use this.pluginSettingsComponent.settingsState with the following properties:
inputValues- values as been set, even if they don’t pass validation.effectiveValues- set values, if they pass validation, or default value, otherwise.validationMessages- contains validation messages for each setting properties that don’t pass validation.