插件开发笔记

通过命令 id 执行命令

this.app.commands.executeCommandById('app:open-settings');

添加,修改,删除 frontmatter

const file = this.app.vault.getFileByPath("demo.md");
if(file) {
	//see https://forum.obsidian.md/t/how-to-use-app-filemanager-processfrontmatter/73467
	this.app.fileManager.processFrontMatter(file, (frontmatter: any) => {
		frontmatter['a'] = "aaaa";
		frontmatter['b'] = "bbbb";
		frontmatter['c'] = "cccc";
	})
}

读取 frontmatter

// 从缓存读取
let fm = this.app.metadataCache.getFileCache(file)?.frontmatter
console.log(fm)

// 从文件解析
import { getFrontMatterInfo, parseYaml } from 'obsidian';
const content = await this.app.vault.read(file)
const yaml = getFrontMatterInfo(content).frontmatter
const yamlObj = parseYaml(yaml)
console.log(yamlObj)

激活叶子

this.app.workspace.setActiveLeaf(leaf, { focus: true });

复制到剪切板

navigator.clipboard.writeText('');

记录叶子的光标和滚动条位置

onst state = leaf.getEphemeralState()
setTimeout(() => {
    leaf.setEphemeralState(state);
}, 42);

关闭重复标签

关闭重复标签

用默认文件打开(也可以打开文件夹)

this.app.openWithDefaultApp(FolderOrFile)

获取 .obsidian 目录

const vault = this.app.vault
const adapter = vault.adapter
const obConfigDir = adapter.path.join(adapter.basePath, vault.configDir)
console.log(obConfigDir)

获取当前激活 view 的类型

this.app.workspace.activeLeaf.view.getViewType()

获取 rootSplit

@ts-ignore
this.app.workspace.rootSplit.containerEl

当未开启番茄工作法且鼠标不在状态栏焦点时自动隐藏状态栏

/* 当未开启番茄工作法且鼠标不在状态栏焦点时隐藏状态栏 */
.status-bar:not(:hover):has(.plugin-obsidian-statusbar-pomo:empty) {
    opacity: 0;
}

notice 倒计时

let count = 10
const a=new Notice("hello "+count, 0);
while (count > 0) {
count--;
await new Promise((resolve) => setTimeout(resolve, 1000)).then(() => {a.setMessage("hello "+count);});
}
a.hide()

在当前叶子打开文件

await app.workspace.activeLeaf.openFile(app.vault.getAbstractFileByPath("demo.md"))

新窗口打开文件

await app.workspace.getLeaf('tab').openFile(app.vault.getAbstractFileByPath('demo.md'))

obsidian 插件外 require('obsidian')

  1. 先去github安装这个插件obsidian-fix-require-modules并开启插件。

  2. 如下方法调用

const ob = require('obsidian');
const markdown = ob.htmlToMarkdown(htmlContent);

htmlToMarkdown 在非 obsidian 环境可以用 turndown,貌似 obsidian 中就用的这个项目。

写文档

app.vault.adapter.write("demo.md", 'demo')