Skip to content

Commander 插件高级使用案例

本文介绍 Commander 插件的进阶配置,包括复杂脚本、命令序列、API 集成和自动化工作流。

复杂代码片段

批量文件操作

javascript
const folder = app.workspace.getActiveFolder();
if (folder) {
  const children = folder.children;
  for (const child of children) {
    if (child instanceof TFile && child.extension === 'md') {
      const oldName = child.basename;
      const newName = oldName.replace(/\s+/g, '-');
      if (oldName !== newName) {
        await app.fileManager.renameFile(child, `${folder.path}/${newName}.md`);
      }
    }
  }
  new Notice(`已处理 ${children.length} 个文件`);
}

智能模板插入

javascript
const file = app.workspace.getActiveFile();
const fileName = file?.basename || 'untitled';

const templates = {
  '日记': `---
date: {{date:YYYY-MM-DD}}
tags: [日记]
---

# {{date:YYYY-MM-DD}}`,

  '会议': `---
date: {{date:YYYY-MM-DD}}
participants: []
---

# 会议记录 | {{date:YYYY-MM-DD}}

## 参会人员
## 议程
1. 
## 决策
## 待办
- [ ] `,

  '项目': `---
project:
status: 🟡 进行中
tags: [项目]
---

# 项目名称

## 目标
## 里程碑
- [ ] 
`
};

const template = templates[fileName] || templates['日记'];
const editor = app.workspace.getActiveEditor();
if (editor) {
  editor.replaceSelection(template);
  new Notice(`已插入 ${fileName} 模板`);
}

命令序列

每周回顾序列

序列:每周回顾
├─ 1. 打开本周周记
├─ 2. 收集过去 7 天日记中的任务完成情况
├─ 3. 统计完成率
└─ 4. 在周记中生成周报

项目启动序列

序列:启动新项目
├─ 1. 提示输入项目名称
├─ 2. 创建项目文件夹
├─ 3. 生成项目笔记(使用模板)
└─ 4. 创建项目日记分区

API 集成

调用外部 API

javascript
const response = await fetch('https://api.example.com/data');
const data = await response.json();

const file = app.workspace.getActiveFile();
if (file) {
  const content = await app.vault.read(file);
  const updatedContent = content + `\n\n## API 数据\n\n\`\`\`json\n${JSON.stringify(data, null, 2)}\n\`\`\``;
  await app.vault.modify(file, updatedContent);
  new Notice('已同步数据');
}

Obsidian API 高级用法

javascript
app.metadataCache.on('changed', (file, data) => {
  if (file.path.includes('Journal/Daily')) {
    const hasTodos = data.includes('- [ ]');
    if (hasTodos) {
      console.log(`日记 ${file.basename} 有待办`);
    }
  }
});

自动化脚本

每日自动归档

javascript
const moment = window.moment || require('moment');
const threshold = moment().subtract(30, 'days');
const journalFolder = 'Journal/Daily';

const files = app.vault.getFiles()
  .filter(f => f.path.startsWith(journalFolder))
  .filter(f => {
    const date = moment(f.basename, 'YYYY-MM-DD');
    return date.isBefore(threshold);
  });

if (files.length > 0) {
  for (const file of files) {
    const newPath = `Archives/Journal/${file.name}`;
    await app.fileManager.renameFile(file, newPath);
  }
  new Notice(`已归档 ${files.length} 个旧日记`);
} else {
  new Notice('没有需要归档的日记');
}

任务统计生成

javascript
const file = app.workspace.getActiveFile();
if (file) {
  const content = await app.vault.read(file);
  const total = (content.match(/- \[ \]/g) || []).length;
  const completed = (content.match(/- \[x\]/g) || []).length;
  const percentage = total > 0 ? Math.round(completed / total * 100) : 0;
  
  const stats = `\n\n---\n\n**任务统计**: ${completed}/${total} (${percentage}%)\n\n${'█'.repeat(percentage / 5)}${'░'.repeat(20 - percentage / 5)}`;
  
  await app.vault.append(file, stats);
  new Notice(`已生成任务统计: ${percentage}%`);
}

调试技巧

javascript
// 使用 console 输出到控制台
console.log('=== Commander Debug ===');
console.log('Active file:', app.workspace.getActiveFile()?.path);

// 错误处理
try {
  await app.vault.create('test.md', 'content');
} catch (error) {
  console.error('Error:', error);
  new Notice(`执行失败: ${error.message}`);
}

常见问题

Q: 片段执行后无响应?

  1. 检查 JavaScript 代码是否有语法错误
  2. 在开发者工具中查看控制台错误
  3. 尝试简化代码逐步排查

Q: 如何调试复杂脚本?

使用 console.log 输出中间变量值,在 Obsidian 的「开发者工具」→「控制台」中查看。