2.7 KiB
2.7 KiB
Obsidian API Quick Reference
This is a quick reference for commonly used Obsidian APIs. For full details, fetch the documentation URLs.
Core Classes
App
The main application interface.
app.vault- Access to the vaultapp.workspace- Access to workspaceapp.metadataCache- File metadataapp.fileManager- File operations
Vault
File system operations.
vault.getMarkdownFiles()- Get all markdown filesvault.read(file)- Read file contentsvault.modify(file, data)- Modify filevault.create(path, data)- Create new filevault.delete(file)- Delete filevault.adapter.exists(path)- Check if path exists
Workspace
UI and layout management.
workspace.getActiveViewOfType(MarkdownView)- Get active markdown viewworkspace.getActiveFile()- Get currently open fileworkspace.on(event, callback)- Listen to workspace eventsworkspace.getLeaf()- Get a workspace leaf for custom views
Editor
Text editing operations.
editor.getValue()- Get full editor contenteditor.setValue(text)- Set full editor contenteditor.getSelection()- Get selected texteditor.replaceSelection(text)- Replace selected texteditor.getCursor()- Get cursor positioneditor.getLine(n)- Get specific line
Modal
Dialog windows.
new Modal(app)- Create modalmodal.open()- Show modalmodal.close()- Hide modalmodal.contentEl- Content container elementmodal.titleEl- Title container element
Plugin Lifecycle
export default class MyPlugin extends Plugin {
async onload() {
// Initialize plugin
await this.loadSettings();
this.addCommand(...);
this.registerView(...);
this.addSettingTab(...);
}
onunload() {
// Cleanup
}
}
Common Patterns
Adding a Command
this.addCommand({
id: 'my-command',
name: 'My Command',
callback: () => {
// Do something
}
});
Editor Command
this.addCommand({
id: 'editor-command',
name: 'Editor Command',
editorCallback: (editor: Editor, view: MarkdownView) => {
const selection = editor.getSelection();
editor.replaceSelection(selection.toUpperCase());
}
});
Settings
interface MySettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MySettings = {
mySetting: 'default'
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
Events
this.registerEvent(
this.app.workspace.on('file-open', (file) => {
console.log('File opened:', file?.path);
})
);
Useful Documentation Links
Use WebFetch with these URLs for detailed information on specific topics.