obsidian

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Obsidian

Obsidian

Overview

概述

This skill provides comprehensive guidance for working with Obsidian, a powerful knowledge management and note-taking application. It covers vault structure, the Obsidian API for plugin development, URI scheme automation, markdown extensions, and integration with external tools via the Local REST API.
本技能为使用Obsidian这款强大的知识管理与笔记应用提供全面指导,内容涵盖库结构、用于插件开发的Obsidian API、URI方案自动化、Markdown扩展,以及通过Local REST API与外部工具集成的方法。

Quick Reference

快速参考

Vault Structure

库结构

text
my-vault/
├── .obsidian/              # Configuration folder
│   ├── app.json            # App settings
│   ├── appearance.json     # Theme settings
│   ├── community-plugins.json  # Installed plugins list
│   ├── core-plugins.json   # Core plugin toggles
│   ├── hotkeys.json        # Custom keybindings
│   ├── plugins/            # Plugin data folders
│   │   └── <plugin-id>/
│   │       ├── main.js     # Compiled plugin code
│   │       ├── manifest.json
│   │       └── data.json   # Plugin settings
│   └── workspace.json      # Layout state
├── Notes/                  # User notes (any structure)
├── Attachments/            # Images, PDFs, etc.
└── Templates/              # Template files
text
my-vault/
├── .obsidian/              # 配置文件夹
│   ├── app.json            # 应用设置
│   ├── appearance.json     # 主题设置
│   ├── community-plugins.json  # 已安装插件列表
│   ├── core-plugins.json   # 核心插件开关
│   ├── hotkeys.json        # 自定义快捷键
│   ├── plugins/            # 插件数据文件夹
│   │   └── <plugin-id>/
│   │       ├── main.js     # 编译后的插件代码
│   │       ├── manifest.json
│   │       └── data.json   # 插件设置
│   └── workspace.json      # 布局状态
├── Notes/                  # 用户笔记(可自定义结构)
├── Attachments/            # 图片、PDF等附件
└── Templates/              # 模板文件

Obsidian URI Scheme

Obsidian URI 方案

Native Obsidian supports
obsidian://
protocol for automation:
bash
undefined
原生Obsidian支持
obsidian://
协议以实现自动化操作:
bash
undefined

Open a vault

打开一个库

obsidian://open?vault=MyVault
obsidian://open?vault=MyVault

Open a specific file

打开指定文件

obsidian://open?vault=MyVault&file=Notes/MyNote
obsidian://open?vault=MyVault&file=Notes/MyNote

Create a new note

创建新笔记

obsidian://new?vault=MyVault&name=NewNote&content=Hello
obsidian://new?vault=MyVault&name=NewNote&content=Hello

Search the vault

搜索库内容

obsidian://search?vault=MyVault&query=keyword
obsidian://search?vault=MyVault&query=keyword

Open daily note

打开每日笔记

obsidian://daily?vault=MyVault
undefined
obsidian://daily?vault=MyVault
undefined

URI Parameters

URI 参数

ParameterDescription
vault
Vault name (required)
file
File path without
.md
extension
path
Full file path including folders
name
Note name for creation
content
Content to insert
query
Search query
heading
Navigate to heading
block
Navigate to block reference
参数说明
vault
库名称(必填)
file
不带
.md
后缀的文件路径
path
包含文件夹的完整文件路径
name
待创建笔记的名称
content
要插入的内容
query
搜索关键词
heading
跳转到指定标题
block
跳转到指定块引用

Workflow Decision Tree

工作流决策树

text
What do you need to do?
├── Automate Obsidian from external tools?
│   ├── Simple open/create operations?
│   │   └── Use: Native obsidian:// URI scheme
│   ├── Complex automation (append, prepend, commands)?
│   │   └── Use: Advanced URI plugin
│   └── Full programmatic access?
│       └── Use: Local REST API plugin
├── Build a plugin for Obsidian?
│   └── See: Plugin Development section
├── Work with vault files directly?
│   └── Use: obsidian-cli or direct file operations
├── Extend markdown syntax?
│   └── See: Markdown Extensions section
└── Query notes and metadata?
    └── Use: Local REST API or Dataview plugin
text
你需要执行什么操作?
├── 从外部工具自动化Obsidian操作?
│   ├── 简单的打开/创建操作?
│   │   └── 使用:原生obsidian:// URI方案
│   ├── 复杂自动化操作(追加、前置、命令执行)?
│   │   └── 使用:Advanced URI插件
│   └── 需要完整的编程访问权限?
│       └── 使用:Local REST API插件
├── 为Obsidian开发插件?
│   └── 查看:插件开发章节
├── 直接操作库文件?
│   └── 使用:obsidian-cli或直接文件操作
├── 扩展Markdown语法?
│   └── 查看:Markdown扩展章节
└── 查询笔记及元数据?
    └── 使用:Local REST API或Dataview插件

Plugin Development

插件开发

Plugin Structure

插件结构

text
my-plugin/
├── main.ts           # Plugin entry point
├── manifest.json     # Plugin metadata
├── package.json      # npm dependencies
├── styles.css        # Optional styles
├── tsconfig.json     # TypeScript config
└── esbuild.config.mjs # Build config
text
my-plugin/
├── main.ts           # 插件入口文件
├── manifest.json     # 插件元数据
├── package.json      # npm依赖
├── styles.css        # 可选样式文件
├── tsconfig.json     # TypeScript配置
└── esbuild.config.mjs # 构建配置

manifest.json

manifest.json

json
{
  "id": "my-plugin",
  "name": "My Plugin",
  "version": "1.0.0",
  "minAppVersion": "1.0.0",
  "description": "A sample plugin for Obsidian",
  "author": "Your Name",
  "authorUrl": "https://github.com/username",
  "isDesktopOnly": false
}
json
{
  "id": "my-plugin",
  "name": "My Plugin",
  "version": "1.0.0",
  "minAppVersion": "1.0.0",
  "description": "A sample plugin for Obsidian",
  "author": "Your Name",
  "authorUrl": "https://github.com/username",
  "isDesktopOnly": false
}

Basic Plugin Template

基础插件模板

typescript
import { Plugin, Notice, MarkdownView } from 'obsidian';

export default class MyPlugin extends Plugin {
  async onload() {
    console.log('Loading plugin');

    // Register a command
    this.addCommand({
      id: 'my-command',
      name: 'My Command',
      callback: () => {
        new Notice('Hello from my plugin!');
      }
    });

    // Register editor command
    this.addCommand({
      id: 'my-editor-command',
      name: 'Insert Text',
      editorCallback: (editor, view: MarkdownView) => {
        editor.replaceSelection('Inserted text');
      }
    });

    // Register event listener
    this.registerEvent(
      this.app.workspace.on('file-open', (file) => {
        if (file) {
          console.log('Opened:', file.path);
        }
      })
    );
  }

  onunload() {
    console.log('Unloading plugin');
  }
}
typescript
import { Plugin, Notice, MarkdownView } from 'obsidian';

export default class MyPlugin extends Plugin {
  async onload() {
    console.log('Loading plugin');

    // 注册命令
    this.addCommand({
      id: 'my-command',
      name: 'My Command',
      callback: () => {
        new Notice('Hello from my plugin!');
      }
    });

    // 注册编辑器命令
    this.addCommand({
      id: 'my-editor-command',
      name: 'Insert Text',
      editorCallback: (editor, view: MarkdownView) => {
        editor.replaceSelection('Inserted text');
      }
    });

    // 注册事件监听器
    this.registerEvent(
      this.app.workspace.on('file-open', (file) => {
        if (file) {
          console.log('Opened:', file.path);
        }
      })
    );
  }

  onunload() {
    console.log('Unloading plugin');
  }
}

Core API Classes

核心API类

ClassPurposeAccess
App
Central application instance
this.app
Vault
File system operations
this.app.vault
Workspace
Pane and layout management
this.app.workspace
MetadataCache
File metadata indexing
this.app.metadataCache
FileManager
User-safe file operations
this.app.fileManager
用途访问方式
App
核心应用实例
this.app
Vault
文件系统操作
this.app.vault
Workspace
面板与布局管理
this.app.workspace
MetadataCache
文件元数据索引
this.app.metadataCache
FileManager
安全的用户文件操作
this.app.fileManager

Plugin Lifecycle

插件生命周期

typescript
// onload() - Called when plugin is enabled
async onload() {
  // Initialize UI components
  // Register event handlers
  // Set up commands
  // Load settings
}

// onunload() - Called when plugin is disabled
onunload() {
  // Cleanup is mostly automatic
  // Custom cleanup for external resources
}
typescript
// onload() - 插件启用时调用
async onload() {
  // 初始化UI组件
  // 注册事件处理器
  // 设置命令
  // 加载设置
}

// onunload() - 插件禁用时调用
onunload() {
  // 大部分清理工作自动完成
  // 针对外部资源执行自定义清理
}

Local REST API

Local REST API

The Local REST API plugin provides HTTP endpoints to interact with Obsidian programmatically.
Local REST API插件提供HTTP端点,支持以编程方式与Obsidian交互。

Installation

安装步骤

  1. Install "Local REST API" from Community Plugins
  2. Enable the plugin
  3. Configure API key in settings
  4. Default endpoint:
    https://127.0.0.1:27124
  1. 从社区插件中安装"Local REST API"
  2. 启用该插件
  3. 在设置中配置API密钥
  4. 默认端点:
    https://127.0.0.1:27124

Authentication

认证方式

bash
undefined
bash
undefined

Using API key header

使用API密钥请求头

curl -H "Authorization: Bearer YOUR_API_KEY"
https://127.0.0.1:27124/vault/
undefined
curl -H "Authorization: Bearer YOUR_API_KEY"
https://127.0.0.1:27124/vault/
undefined

Common Endpoints

常用端点

bash
undefined
bash
undefined

List all files

列出所有文件

GET /vault/
GET /vault/

Get file content

获取文件内容

GET /vault/{path-to-file}
GET /vault/{path-to-file}

Create/Update file

创建/更新文件

PUT /vault/{path-to-file} Content-Type: text/markdown Body: File content here
PUT /vault/{path-to-file} Content-Type: text/markdown Body: File content here

Delete file

删除文件

DELETE /vault/{path-to-file}
DELETE /vault/{path-to-file}

Search vault

搜索库内容

POST /search/simple/ Content-Type: application/json Body: {"query": "search term"}
POST /search/simple/ Content-Type: application/json Body: {"query": "search term"}

Execute command

执行命令

POST /commands/{command-id}
POST /commands/{command-id}

Get active file

获取当前活跃文件

GET /active/
GET /active/

Open file in Obsidian

在Obsidian中打开文件

POST /open/{path-to-file}
undefined
POST /open/{path-to-file}
undefined

Python Example

Python示例

python
import requests

class ObsidianAPI:
    def __init__(self, api_key, base_url="https://127.0.0.1:27124"):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        self.session = requests.Session()
        self.session.verify = False  # Self-signed cert

    def list_files(self, path=""):
        response = self.session.get(
            f"{self.base_url}/vault/{path}",
            headers=self.headers
        )
        return response.json()

    def read_file(self, path):
        response = self.session.get(
            f"{self.base_url}/vault/{path}",
            headers=self.headers
        )
        return response.text

    def write_file(self, path, content):
        response = self.session.put(
            f"{self.base_url}/vault/{path}",
            headers={**self.headers, "Content-Type": "text/markdown"},
            data=content.encode('utf-8')
        )
        return response.status_code == 204

    def search(self, query):
        response = self.session.post(
            f"{self.base_url}/search/simple/",
            headers=self.headers,
            json={"query": query}
        )
        return response.json()
python
import requests

class ObsidianAPI:
    def __init__(self, api_key, base_url="https://127.0.0.1:27124"):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        self.session = requests.Session()
        self.session.verify = False  # 自签名证书处理

    def list_files(self, path=""):
        response = self.session.get(
            f"{self.base_url}/vault/{path}",
            headers=self.headers
        )
        return response.json()

    def read_file(self, path):
        response = self.session.get(
            f"{self.base_url}/vault/{path}",
            headers=self.headers
        )
        return response.text

    def write_file(self, path, content):
        response = self.session.put(
            f"{self.base_url}/vault/{path}",
            headers={**self.headers, "Content-Type": "text/markdown"},
            data=content.encode('utf-8')
        )
        return response.status_code == 204

    def search(self, query):
        response = self.session.post(
            f"{self.base_url}/search/simple/",
            headers=self.headers,
            json={"query": query}
        )
        return response.json()

Markdown Extensions

Markdown扩展

Obsidian extends standard Markdown with special syntax:
Obsidian对标准Markdown进行了语法扩展:

Internal Links (Wikilinks)

内部链接(维基链接)

markdown
[[Note Name]]                    # Link to note
[[Note Name|Display Text]]       # Link with alias
[[Note Name#Heading]]            # Link to heading
[[Note Name#^block-id]]          # Link to block
[[Note Name#^block-id|alias]]    # Block link with alias
markdown
[[Note Name]]                    # 链接到笔记
[[Note Name|Display Text]]       # 带别名的链接
[[Note Name#Heading]]            # 链接到标题
[[Note Name#^block-id]]          # 链接到块
[[Note Name#^block-id|alias]]    # 带别名的块链接

Embeds (Transclusion)

嵌入(内容引用)

markdown
![[Note Name]]                   # Embed entire note
![[Note Name#Heading]]           # Embed section
![[Note Name#^block-id]]         # Embed block
![[image.png]]                   # Embed image
![[image.png|300]]               # Embed with width
![[image.png|300x200]]           # Embed with dimensions
![[audio.mp3]]                   # Embed audio
![[video.mp4]]                   # Embed video
![[document.pdf]]                # Embed PDF
markdown
![[Note Name]]                   # 嵌入整个笔记
![[Note Name#Heading]]           # 嵌入指定章节
![[Note Name#^block-id]]         # 嵌入指定块
![[image.png]]                   # 嵌入图片
![[image.png|300]]               # 指定宽度嵌入图片
![[image.png|300x200]]           # 指定尺寸嵌入图片
![[audio.mp3]]                   # 嵌入音频
![[video.mp4]]                   # 嵌入视频
![[document.pdf]]                # 嵌入PDF

Callouts

提示框

markdown
> [!note] Title
> Content here

> [!warning] Caution
> Important warning message

> [!tip]+ Expandable (default open)
> Click to collapse

> [!info]- Collapsed (default closed)
> Click to expand
markdown
> [!note] 标题
> 内容

> [!warning] 注意
> 重要警告信息

> [!tip]+ 可展开(默认打开)
> 点击可折叠

> [!info]- 可折叠(默认关闭)
> 点击可展开

Available types:

可用类型:

note, abstract, summary, tldr, info, todo, tip, hint,

note, abstract, summary, tldr, info, todo, tip, hint,

important, success, check, done, question, help, faq,

important, success, check, done, question, help, faq,

warning, caution, attention, failure, fail, missing,

warning, caution, attention, failure, fail, missing,

danger, error, bug, example, quote, cite

danger, error, bug, example, quote, cite

undefined
undefined

Block References

块引用

markdown
This is a paragraph. ^block-id
markdown
This is a paragraph. ^block-id

Reference this block from another note:

在另一篇笔记中引用此块:

[[Note#^block-id]]
undefined
[[Note#^block-id]]
undefined

Tags

标签

markdown
#tag
#nested/tag
#tag-with-dashes
markdown
#tag
#nested/tag
#tag-with-dashes

Frontmatter (YAML)

前置元数据(YAML)

markdown
---
title: My Note
date: 2024-01-15
tags:
  - tag1
  - tag2
aliases:
  - alternate name
cssclass: custom-class
---
markdown
---
title: My Note
date: 2024-01-15
tags:
  - tag1
  - tag2
aliases:
  - alternate name
cssclass: custom-class
---

Note content starts here

笔记内容从这里开始

undefined
undefined

Comments

注释

markdown
%%This is a comment that won't render%%

%%
Multi-line
comment
%%
markdown
%%This is a comment that won't render%%

%%
多行
注释
%%

Math (LaTeX)

数学公式(LaTeX)

markdown
Inline: $E = mc^2$

Block:
$$
\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$
markdown
行内公式:$E = mc^2$

块级公式:
$$
\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$

Mermaid Diagrams

Mermaid流程图

markdown
```mermaid
graph TD
    A[Start] --> B{Decision}
    B -->|Yes| C[Action 1]
    B -->|No| D[Action 2]
```
markdown
```mermaid
graph TD
    A[开始] --> B{决策}
    B -->|是| C[操作1]
    B -->|否| D[操作2]
```

CLI Tools

CLI工具

obsidian-cli (Yakitrak)

obsidian-cli (Yakitrak)

bash
undefined
bash
undefined

Install

安装

go install github.com/Yakitrak/obsidian-cli@latest
go install github.com/Yakitrak/obsidian-cli@latest

Commands

命令

obsidian-cli open "Note Name" # Open note obsidian-cli search "query" # Fuzzy search obsidian-cli create "New Note" # Create note obsidian-cli daily # Open daily note obsidian-cli list # List notes
undefined
obsidian-cli open "Note Name" # 打开笔记 obsidian-cli search "query" # 模糊搜索 obsidian-cli create "New Note" # 创建笔记 obsidian-cli daily # 打开每日笔记 obsidian-cli list # 列出所有笔记
undefined

obsidian-cli (Python)

obsidian-cli (Python)

bash
undefined
bash
undefined

Install

安装

pip install obsidian-cli
pip install obsidian-cli

Commands

命令

obs vault list # List vaults obs vault create <name> # Create vault obs note search <query> # Search notes obs settings export # Export settings
undefined
obs vault list # 列出所有库 obs vault create <name> # 创建库 obs note search <query> # 搜索笔记 obs settings export # 导出设置
undefined

Best Practices

最佳实践

  1. Use separate dev vault: Never develop plugins in your main vault
  2. Hot reload plugin: Install for faster development iteration
  3. Use registerEvent(): Ensures proper cleanup on unload
  4. Prefer UIDs over paths: File paths can change; use unique identifiers
  5. Handle async properly: Use await for vault operations
  6. Test with Obsidian sandbox: Use BRAT plugin for beta testing
  7. Follow manifest conventions: Keep id matching folder name
  8. Version carefully: Update versions.json for compatibility
  1. 使用独立开发库:切勿在主库中开发插件
  2. 安装热重载插件:提升开发迭代速度
  3. 使用registerEvent():确保插件卸载时自动清理资源
  4. 优先使用UID而非路径:文件路径可能变更,使用唯一标识符更可靠
  5. 正确处理异步操作:对库操作使用await关键字
  6. 在Obsidian沙箱中测试:使用BRAT插件进行Beta测试
  7. 遵循manifest规范:保持插件id与文件夹名称一致
  8. 谨慎版本管理:更新versions.json以保证兼容性

Troubleshooting

故障排查

Plugin Not Loading

插件无法加载

bash
undefined
bash
undefined

Check console for errors

打开控制台查看错误

Ctrl+Shift+I (or Cmd+Option+I on Mac)
Ctrl+Shift+I(Mac上为Cmd+Option+I)

Verify manifest.json is valid JSON

验证manifest.json是有效的JSON格式

jq . manifest.json
jq . manifest.json

Check minAppVersion compatibility

检查minAppVersion兼容性

Ensure main.js exists in plugin folder

确保插件文件夹中存在main.js文件

undefined
undefined

URI Not Working

URI无法正常工作

bash
undefined
bash
undefined

URL encode special characters

对特殊字符进行URL编码

Spaces: %20

空格:%20

Slashes: %2F

斜杠:%2F

Ampersands: %26

和号:%26

Test with simple vault name first

先使用简单库名称测试

obsidian://open?vault=test
undefined
obsidian://open?vault=test
undefined

REST API Connection Failed

REST API连接失败

bash
undefined
bash
undefined

Verify plugin is enabled

确认插件已启用

Check API key is correct

检查API密钥是否正确

Confirm HTTPS and self-signed cert handling

处理HTTPS自签名证书问题

Default port: 27124

默认端口:27124

undefined
undefined

Resources

资源

References

参考文档

  • references/uri-scheme.md
    - Complete URI scheme documentation
  • references/plugin-development.md
    - Plugin development guide
  • references/vault-structure.md
    - Vault and config structure
  • references/markdown-extensions.md
    - Obsidian markdown syntax
  • references/api-reference.md
    - TypeScript API reference
  • references/uri-scheme.md
    - 完整的URI方案文档
  • references/plugin-development.md
    - 插件开发指南
  • references/vault-structure.md
    - 库与配置结构说明
  • references/markdown-extensions.md
    - Obsidian Markdown语法扩展
  • references/api-reference.md
    - TypeScript API参考

Scripts

脚本

  • scripts/obsidian-vault.sh
    - Vault management utilities
  • scripts/obsidian-api.py
    - Local REST API Python client
  • scripts/obsidian-vault.sh
    - 库管理工具脚本
  • scripts/obsidian-api.py
    - Local REST API Python客户端

External Documentation

外部文档