Skip to content

gapmiss/obsidian-plugin-skill / .agents/skills/obsidian

obsidian

Verified

Comprehensive guidelines for Obsidian.md plugin development including ESLint rules from eslint-plugin-obsidianmd v0.6.0, TypeScript best practices, memory management, API usage (requestUrl vs fetch), UI/UX standards, popout window compatibility, community.obsidian.md submission process, and Scorecard optimization. Use when working with Obsidian plugins, main.ts files, manifest.json, Plugin class, MarkdownView, TFile, vault operations, or any Obsidian API development.

reference/file-operations.md

View on GitHub
# File & Vault Operations

Proper file operations are critical for safe and efficient Obsidian plugin development.

## Table of Contents
- [View Access](#view-access)
- [Editor vs Vault API](#editor-vs-vault-api)
- [Atomic File Operations](#atomic-file-operations)
- [File Management](#file-management)
- [Path Handling](#path-handling)

---

## View Access

### Use getActiveViewOfType() for View Access
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
const view = this.app.workspace.activeLeaf?.view;
```

✅ **CORRECT**:
```typescript
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
  // Work with view
}
```

Rationale: Use `getActiveViewOfType()` instead of directly accessing `workspace.activeLeaf` for safer view access.

---

## Editor vs Vault API

### Prefer Editor API over Vault.modify()
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
// For active file edits
const activeFile = this.app.workspace.getActiveFile();
await this.app.vault.modify(activeFile, newContent);
```

✅ **CORRECT**:
```typescript
// Use Editor API for active file
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
  const editor = view.editor;
  editor.setValue(newContent);
  // Or use editor methods to preserve cursor
  editor.replaceRange(text, from, to);
}
```

Rationale: Use Editor API for active file edits to preserve cursor position and selection. Use `Vault.modify()` only for non-active files.

---

## Atomic File Operations

### Use Vault.process() for Background Modifications
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
// Direct modification can conflict with other plugins
const content = await this.app.vault.read(file);
const modified = content.replace(/old/g, 'new');
await this.app.vault.modify(file, modified);
```

✅ **CORRECT**:
```typescript
// Vault.process() prevents conflicts
await this.app.vault.process(file, (data) => {
  return data.replace(/old/g, 'new');
});
```

Rationale: Use `Vault.process()` for background file modifications—it prevents conflicts with other plugins through atomic operations.

---

### Use FileManager.processFrontMatter() for YAML
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
const content = await this.app.vault.read(file);
const updated = content.replace(/tags:.*/, 'tags: [new-tag]');
await this.app.vault.modify(file, updated);
```

✅ **CORRECT**:
```typescript
await this.app.fileManager.processFrontMatter(file, (frontmatter) => {
  frontmatter.tags = ['new-tag'];
  frontmatter.modified = new Date().toISOString();
});
```

Rationale: Use `FileManager.processFrontMatter()` for YAML modifications to ensure atomic operations and consistent formatting.

---

## File Management

### Prefer Vault API over Adapter API
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
// Adapter API bypasses Obsidian's safety mechanisms
const content = await this.app.vault.adapter.read(file.path);
await this.app.vault.adapter.write(file.path, newContent);
```

✅ **CORRECT**:
```typescript
// Vault API provides safety and serialization
const content = await this.app.vault.read(file);
await this.app.vault.modify(file, newContent);
```

Rationale: Prefer the Vault API over the Adapter API for better performance and safety through serialized operations.

---

### Prefer FileManager for Deletion
Rule: `obsidianmd/prefer-file-manager-trash-file`

❌ **INCORRECT**:
```typescript
await this.app.vault.trash(file, system);
await this.app.vault.delete(file, isFolder);   // gone for good, whatever `force` is (reported since v0.6.0)
```

✅ **CORRECT**:
```typescript
await this.app.fileManager.trashFile(file);
```

Rationale: `fileManager.trashFile()` handles additional cleanup like backlinks and follows the user's "Deleted files" setting (needs `minAppVersion` 1.6.6). Since v0.6.0 the rule also reports `vault.delete(file, force)` with a non-literal `force`, and branches that differ only in `force` — `force` only lets `delete()` remove a non-empty folder; it doesn't make the deletion recoverable. `delete()` gets no suggestion.

---

### Avoid Full Vault Iteration
Rule: `obsidianmd/vault/iterate`

❌ **INCORRECT**:
```typescript
// Iterating all files to find one (reported by vault/iterate)
const target = this.app.vault.getFiles().find(f => f.path === targetPath);

// Same problem, but not linted — getMarkdownFiles().find() is out of the rule's scope
const note = this.app.vault.getMarkdownFiles().find(f => f.path === targetPath);
```

✅ **CORRECT**:
```typescript
// Direct lookup
const target = this.app.vault.getAbstractFileByPath(targetPath);

// Or, when you need a TFile (Obsidian 1.5.7+) — returns null if missing or a folder
const file = this.app.vault.getFileByPath(targetPath);
```

Rationale: Use direct lookup methods instead of iterating all files for better performance. v0.5.0 offers an editor suggestion to `getFileByPath()` when your `minAppVersion` allows it. Note it returns `null` where `.find()` returned `undefined`.

---

## Path Handling

### Use normalizePath() for User-Defined Paths
Rule: Official guidelines

❌ **INCORRECT**:
```typescript
const file = this.app.vault.getAbstractFileByPath(userPath);
```

✅ **CORRECT**:
```typescript
import { normalizePath } from 'obsidian';

const normalizedPath = normalizePath(userPath);
const file = this.app.vault.getAbstractFileByPath(normalizedPath);
```

Rationale: Apply `normalizePath()` to user-defined paths to ensure cross-platform compatibility (handles backslashes, etc.).

---

### Don't Hardcode Config Directory
Rule: `obsidianmd/hardcoded-config-path`

❌ **INCORRECT**:
```typescript
const configPath = '.obsidian/plugins/my-plugin/';
const pluginDir = vault.adapter.basePath + '/.obsidian/plugins/my-plugin';
```

✅ **CORRECT**:
```typescript
// Access the configured directory
const configDir = this.app.vault.configDir;  // Might not be '.obsidian'
const pluginDir = `${configDir}/plugins/${this.manifest.id}`;

// Or better yet, use the data APIs:
await this.loadData();
await this.saveData(data);
```

Rationale: Obsidian's configuration directory isn't necessarily `.obsidian` - it can be configured by the user. Access it via `Vault#configDir`.
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall