Skip to content

API 参考

核心模块

App

主应用实例,通过 this.app 访问。

typescript
// 获取当前活动文件
const file = app.workspace.getActiveFile();

// 获取仓库信息
const vault = app.vault;

// 获取工作区
const workspace = app.workspace;

// 获取元数据缓存
const metadataCache = app.metadataCache;

Plugin

插件基类。

typescript
class MyPlugin extends Plugin {
  async onload() {
    // 插件入口
  }

  onunload() {
    // 清理资源
  }

  // 数据持久化
  async loadData(): Promise<T>
  async saveData(data: T): Promise<void>

  // 注册方法
  addCommand(command: Command): Command
  addRibbonIcon(icon: string, title: string, callback: (evt: MouseEvent) => any): HTMLElement
  addStatusBarItem(): HTMLElement
  addSettingTab(settingTab: PluginSettingTab): void
  registerView(type: string, viewCreator: ViewCreator): void
  registerEvent(eventRef: EventRef): void
  registerDomEvent(el: HTMLElement, type: string, callback: (evt: Event) => any): void
  registerInterval(id: number): void
}

Workspace

工作区管理。

typescript
const workspace = app.workspace;

// 获取活动视图
const view = workspace.getActiveViewOfType(MarkdownView);

// 获取活动编辑器
const editor = workspace.activeEditor?.editor;

// 打开文件
await workspace.openLinkText('note-name', '', true);

// 获取叶子
const leaf = workspace.getLeaf(false);
const leaf = workspace.getLeaf(true); // 新建标签页

// 更新视图
await leaf.setViewState({
  type: 'markdown',
  state: { file: 'path/to/file.md' }
});

// 事件
workspace.on('file-open', (file) => { });
workspace.on('active-leaf-change', (leaf) => { });
workspace.on('layout-change', () => { });

Vault

文件系统操作。

typescript
const vault = app.vault;

// 获取文件
const file = vault.getAbstractFileByPath('path/to/file.md');
const folder = vault.getAbstractFileByPath('path/to/folder');

// 列出文件
const files = vault.getFiles();
const mdFiles = vault.getMarkdownFiles();

// 读取文件
const content = await vault.read(file);
const data = await vault.readBinary(file);

// 写入文件
await vault.modify(file, 'new content');
await vault.append(file, '\nmore content');

// 创建文件
await vault.create('path/new.md', 'content');
await vault.createFolder('new-folder');

// 删除文件
await vault.trash(file, true);  // 移到回收站
await vault.delete(file);        // 永久删除

// 重命名/移动
await vault.rename(file, 'new/path.md');

// 事件
vault.on('create', (file) => { });
vault.on('modify', (file) => { });
vault.on('delete', (file) => { });
vault.on('rename', (file, oldPath) => { });

MetadataCache

元数据缓存。

typescript
const cache = app.metadataCache;

// 获取文件元数据
const metadata = cache.getFileCache(file);

// 访问 frontmatter
const frontmatter = metadata?.frontmatter;

// 访问链接
const links = metadata?.links;
const embeds = metadata?.embeds;

// 访问标题
const headings = metadata?.headings;

// 获取反向链接
const backlinks = cache.getBacklinksForFile(file);

// 解析链接
const linkInfo = cache.getFirstLinkpathDest('[[note-name]]', '');

// 事件
cache.on('changed', (file) => { });
cache.on('resolved', () => { });

Editor

编辑器操作。

typescript
const editor = workspace.activeEditor?.editor;

// 获取内容
const content = editor.getValue();
const line = editor.getLine(lineNumber);

// 设置内容
editor.setValue('new content');
editor.replaceRange('text', { line: 0, ch: 0 }, { line: 0, ch: 5 });

// 光标操作
const cursor = editor.getCursor();
const selections = editor.listSelections();
editor.setCursor({ line: 0, ch: 0 });
editor.setSelection({ line: 0, ch: 0 }, { line: 1, ch: 0 });

// 选中文本
const selected = editor.getSelection();
editor.replaceSelection('new text');

// 滚动
editor.scrollIntoView({ line: 10, ch: 0 });
editor.scrollTo(0, 100);

// 行操作
const count = editor.lineCount();
const pos = editor.posToOffset({ line: 0, ch: 0 });
const coords = editor.offsetToPos(0);

// 折叠
editor.fold(lineNumber);
editor.unfold(lineNumber);
editor.toggleFold(lineNumber);

TFile / TFolder

文件和文件夹类型。

typescript
// TFile 属性
file.path     // 完整路径
file.name     // 文件名(含扩展名)
file.basename // 文件名(不含扩展名)
file.extension // 扩展名
file.parent   // 父文件夹
file.stat     // 文件状态 { mtime, ctime, size }

// TFolder 属性
folder.path   // 完整路径
folder.name   // 文件夹名
folder.parent // 父文件夹
folder.children // 子文件/文件夹

// 类型检查
if (file instanceof TFile) { }
if (folder instanceof TFolder) { }

Commands

命令定义。

typescript
interface Command {
  id: string;
  name: string;
  icon?: string;
  editorCallback?: (editor: Editor, view: MarkdownView) => void;
  editorCheckCallback?: (checking: boolean, editor: Editor, view: MarkdownView) => boolean | void;
  callback?: () => void;
  checkCallback?: (checking: boolean) => boolean | void;
}

// 注册命令
this.addCommand({
  id: 'my-command',
  name: 'My Command',
  editorCallback: (editor, view) => {
    editor.replaceSelection('Hello!');
  }
});

Settings

设置面板。

typescript
class MySettingTab extends PluginSettingTab {
  display(): void {
    const { containerEl } = this;
    containerEl.empty();

    // 文本设置
    new Setting(containerEl)
      .setName('Name')
      .setDesc('Description')
      .addText(text => text
        .setPlaceholder('Placeholder')
        .setValue(value)
        .onChange(async (value) => { }));

    // 开关设置
    new Setting(containerEl)
      .addToggle(toggle => toggle
        .setValue(bool)
        .onChange(async (value) => { }));

    // 下拉选择
    new Setting(containerEl)
      .addDropdown(dropdown => dropdown
        .addOption('key', 'Label')
        .setValue(value)
        .onChange(async (value) => { }));

    // 滑块
    new Setting(containerEl)
      .addSlider(slider => slider
        .setLimits(0, 100, 1)
        .setValue(value)
        .setDynamicTooltip()
        .onChange(async (value) => { }));

    // 按钮
    new Setting(containerEl)
      .addButton(button => button
        .setButtonText('Click me')
        .setCta()
        .onClick(() => { }));
  }
}

Notice

通知消息。

typescript
import { Notice } from 'obsidian';

// 基本用法
new Notice('Message');

// 设置持续时间(毫秒)
new Notice('Message', 5000);

// 无限持续时间
new Notice('Message', 0);

模态框。

typescript
import { App, Modal } from 'obsidian';

class MyModal extends Modal {
  constructor(app: App) {
    super(app);
  }

  onOpen() {
    const { contentEl } = this;
    contentEl.createEl('h1', { text: 'Title' });
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}

// 打开模态框
new MyModal(this.app).open();

FuzzySuggestModal

模糊搜索模态框。

typescript
import { App, FuzzySuggestModal } from 'obsidian';

class MySuggestModal extends FuzzySuggestModal<string> {
  items: string[];

  constructor(app: App, items: string[]) {
    super(app);
    this.items = items;
  }

  getItems(): string[] {
    return this.items;
  }

  getItemText(item: string): string {
    return item;
  }

  onChooseItem(item: string, evt: MouseEvent | KeyboardEvent): void {
    console.log('Selected:', item);
  }
}

常用类型

typescript
// 文件类型
type TAbstractFile = TFile | TFolder;

// 编辑器位置
interface EditorPosition {
  line: number;
  ch: number;
}

// 编辑器范围
interface EditorRange {
  from: EditorPosition;
  to: EditorPosition;
}

// 视图状态
interface ViewState {
  type: string;
  state: Record<string, any>;
}

// 工作区叶子
class WorkspaceLeaf {
  view: View;
  tabHeaderEl: HTMLElement;

  getViewState(): ViewState;
  setViewState(viewState: ViewState): Promise<void>;
  openFile(file: TFile): Promise<void>;
}

更多资源

最后更新:2026年2月16日编辑此页反馈问题