obsidian-webhooks-events
Handle Obsidian events and workspace callbacks for plugin development. Use when implementing reactive features, handling file changes, or responding to user interactions in your plugin. Trigger with phrases like "obsidian events", "obsidian callbacks", "obsidian file change", "obsidian workspace events".
What this skill does
# Obsidian Webhooks & Events
## Overview
Complete guide to Obsidian's event system: vault events (create, modify, delete, rename), workspace events (layout, leaf changes, editor state), metadataCache events, DOM events, custom EventRef patterns, and periodic tasks. Every event registration uses `this.registerEvent()` for automatic cleanup on plugin unload.
## Prerequisites
- Working Obsidian plugin with `onload()` / `onunload()` lifecycle
- Understanding of TypeScript event handler signatures
- Familiarity with Obsidian's TFile, TFolder, and WorkspaceLeaf types
## Instructions
### Step 1: Vault Events — File Lifecycle
Vault events fire when files and folders are created, modified, deleted, or renamed.
```typescript
import { Plugin, TFile, TFolder, TAbstractFile } from 'obsidian';
export default class EventPlugin extends Plugin {
async onload() {
// File created
this.registerEvent(
this.app.vault.on('create', (file: TAbstractFile) => {
if (file instanceof TFile) {
console.log('New file:', file.path);
this.onFileCreated(file);
}
if (file instanceof TFolder) {
console.log('New folder:', file.path);
}
})
);
// File content modified (fires on save and on every sync update)
this.registerEvent(
this.app.vault.on('modify', (file: TAbstractFile) => {
if (file instanceof TFile) {
this.onFileModified(file);
}
})
);
// File deleted
this.registerEvent(
this.app.vault.on('delete', (file: TAbstractFile) => {
if (file instanceof TFile) {
this.removeFromIndex(file.path);
}
})
);
// File renamed or moved (includes folder moves)
this.registerEvent(
this.app.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
if (file instanceof TFile) {
this.updatePathReferences(oldPath, file.path);
}
})
);
}
}
```
Note: `modify` fires on every keystroke during live editing in some configurations. Always debounce if your handler does non-trivial work (see `obsidian-rate-limits`).
### Step 2: Workspace Events — UI State Changes
Workspace events track what the user is looking at and how the UI layout changes.
```typescript
async onload() {
// Active file changed (user clicked a different tab/pane)
this.registerEvent(
this.app.workspace.on('active-leaf-change', (leaf) => {
if (leaf) {
const view = leaf.view;
if (view.getViewType() === 'markdown') {
const file = (view as any).file as TFile;
if (file) {
this.onActiveFileChanged(file);
}
}
}
})
);
// File opened in any pane (fires even if already active)
this.registerEvent(
this.app.workspace.on('file-open', (file: TFile | null) => {
if (file) {
this.trackRecentFile(file);
}
})
);
// Layout changed (panes split, closed, rearranged)
this.registerEvent(
this.app.workspace.on('layout-change', () => {
this.updateSidebarState();
})
);
// Editor changed (cursor moved, selection changed, content edited)
this.registerEvent(
this.app.workspace.on('editor-change', (editor, info) => {
// info is MarkdownView — gives you the file context
const cursor = editor.getCursor();
this.onCursorMoved(cursor.line, cursor.ch);
})
);
// Window/pane resized
this.registerEvent(
this.app.workspace.on('resize', () => {
this.adjustCustomViews();
})
);
// Wait for layout to be fully initialized before accessing panes
this.app.workspace.onLayoutReady(() => {
this.initializeWithCurrentState();
});
}
```
### Step 3: MetadataCache Events — Content Indexing
The metadataCache parses frontmatter, links, tags, and headings in the background. These events fire when parsing completes.
```typescript
async onload() {
// Single file's metadata changed (fires after modify, once parsing is done)
this.registerEvent(
this.app.metadataCache.on('changed', (file: TFile, data: string, cache: CachedMetadata) => {
// cache contains parsed frontmatter, links, tags, headings
const tags = cache.tags?.map(t => t.tag) ?? [];
const links = cache.links?.map(l => l.link) ?? [];
this.updateFileIndex(file.path, { tags, links });
})
);
// All files in vault have been indexed (fires once after startup)
this.registerEvent(
this.app.metadataCache.on('resolved', () => {
console.log('Metadata cache fully resolved — safe to query all files');
this.buildFullIndex();
})
);
}
private buildFullIndex() {
const files = this.app.vault.getMarkdownFiles();
for (const file of files) {
const cache = this.app.metadataCache.getFileCache(file);
if (cache) {
this.updateFileIndex(file.path, {
tags: cache.tags?.map(t => t.tag) ?? [],
links: cache.links?.map(l => l.link) ?? [],
headings: cache.headings?.map(h => h.heading) ?? [],
frontmatter: cache.frontmatter,
});
}
}
}
```
The `resolved` event is critical for plugins that build indexes — querying metadataCache before it fires returns incomplete data.
### Step 4: DOM Events with registerDomEvent
For custom UI elements, use `registerDomEvent` instead of raw `addEventListener`. Obsidian auto-removes these on plugin unload.
```typescript
async onload() {
// Register click handler on a custom element
const button = this.addStatusBarItem();
button.setText('Click me');
this.registerDomEvent(button, 'click', (evt: MouseEvent) => {
new Notice('Status bar clicked!');
});
// Listen for keyboard shortcuts on the document
this.registerDomEvent(document, 'keydown', (evt: KeyboardEvent) => {
if (evt.ctrlKey && evt.key === 'q') {
this.toggleFeature();
}
});
// Drag and drop on a custom view
const dropZone = createEl('div', { cls: 'my-drop-zone' });
this.registerDomEvent(dropZone, 'dragover', (evt: DragEvent) => {
evt.preventDefault();
dropZone.addClass('drag-active');
});
this.registerDomEvent(dropZone, 'drop', async (evt: DragEvent) => {
evt.preventDefault();
dropZone.removeClass('drag-active');
const files = evt.dataTransfer?.files;
if (files?.length) {
await this.handleDroppedFiles(files);
}
});
}
```
### Step 5: Periodic Tasks with registerInterval
Use `registerInterval` for timers — they auto-clear on unload. Never use raw `setInterval`.
```typescript
async onload() {
// Auto-save draft every 30 seconds
this.registerInterval(
window.setInterval(() => {
this.autoSaveDraft();
}, 30_000)
);
// Refresh external data every 5 minutes
this.registerInterval(
window.setInterval(() => {
this.refreshExternalData();
}, 5 * 60_000)
);
}
private draftSaving = false;
private async autoSaveDraft() {
// Overlap guard — skip if previous save is still running
if (this.draftSaving) return;
this.draftSaving = true;
try {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view?.file) {
const content = view.editor.getValue();
await this.saveDraft(view.file.path, content);
}
} finally {
this.draftSaving = false;
}
}
```
### Step 6: Custom Event Bus for Plugin-Internal Communication
For complex plugins with multiple views or components, create an internal event bus.
```typescript
import { Events } from 'obsidian';
// Create a typed event bus
class PluginEventBus extends Events {
// Type-safe event methods
onIndexUpdated(callback: (paths: string[]) => void): EventRef {
return this.on('index-updated', callback);
}
triggerIndexUpdated(paths: string[]) {
this.trigger('index-updated', paths);
}
onSettingsChanged(callback: (settings: PluginSettings) => void): EventRef {
return this.on('settings-changed', callback);
}
triggerSettingsChanged(settings: PluginSettings) {
this.trigger('settingRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.