Slash Commands

Table of Contents

1. Introduction

Slash commands are user-invoked prompt templates stored as Markdown files. Type / in Claude Code to see available commands and invoke them on demand.

1.1. How Slash Commands Work

  1. Discovery: Claude Code finds all *.md files in .claude/commands/
  2. Menu display: Commands appear in the / menu with their descriptions
  3. Invocation: User types /command-name (optionally with arguments)
  4. Expansion: Command content replaces the slash command in conversation
  5. Execution: Claude processes the expanded prompt

1.2. File Structure

  • Location: .claude/commands/*.md (project) or ~/.claude/commands/*.md (user)
  • Format: Markdown with optional YAML frontmatter
  • Naming: Filename becomes command name (explain.md/explain)

1.3. Frontmatter Options

---
description: Brief description shown in command menu
argument-hint: "what to pass as argument"
allowed-tools:
  - Read
  - Grep
  - Write
model: "opus"  # Override default model
---

1.4. Arguments and Input

Use {{{ input }}} or $ARGUMENTS for user-provided text:

User's question: {{{ input }}}

When invoked as /explain how this works, {{{ input }}} becomes "how this works".

2. Documentation Commands

Commands for explaining, documenting, and understanding code.

2.1. Explain Code

Generate detailed code explanations with architectural context.

---
description: Explain code with detailed analysis
argument-hint: "[optional focus area]"
allowed-tools:
  - Read
  - Grep
  - Glob
---

# Code Explanation Request

Please analyze the code in my current context and provide a comprehensive explanation.

## Analysis Structure

1. **Purpose**: What does this code do at a high level?
2. **Architecture**: How is it organized and structured?
3. **Key Concepts**: Important patterns, algorithms, or techniques used
4. **Dependencies**: External libraries or modules used
5. **Data Flow**: How data moves through the system
6. **Edge Cases**: How does it handle special conditions?
7. **Potential Issues**: Any concerns, bugs, or improvement opportunities

## Focus Area

{{{ input }}}

## Output Format

- Use clear headings for each section
- Reference specific code with file paths and line numbers (e.g., `file.ts:42`)
- Provide concrete examples where helpful
- Use code snippets to illustrate points
- Highlight key insights or non-obvious behavior

2.2. Generate Documentation

Create comprehensive documentation for functions, classes, or modules.

---
description: Generate comprehensive documentation
allowed-tools:
  - Read
  - Grep
  - Write
---

# Documentation Generator

Generate detailed documentation for the current code.

## Documentation Requirements

### Function/Method Documentation
- **Purpose**: Clear description of what it does
- **Parameters**: Each parameter with type and description
- **Return Value**: Type and meaning
- **Exceptions**: What errors can be thrown
- **Examples**: Practical usage examples
- **Notes**: Side effects, performance, thread safety

### Class/Module Documentation
- **Overview**: Responsibility and purpose
- **Public API**: All public methods/functions
- **Usage Examples**: Common use cases
- **Dependencies**: Required imports or modules
- **Design Patterns**: Patterns used (if any)

### File/Package Documentation
- **Overview**: What this file/package provides
- **Exports**: What's exposed to other modules
- **Internal Structure**: Major components
- **Examples**: How to use the package

## Format Guidelines

- Use the appropriate documentation format for the language:
  - **JavaScript/TypeScript**: JSDoc
  - **Python**: Docstrings (Google or NumPy style)
  - **Java**: Javadoc
  - **C/C++**: Doxygen
  - **Go**: Go doc comments
  - **Rust**: Rustdoc
  - **Markdown**: For READMEs and guides

## Additional Context

{{{ input }}}

3. Development Commands

Commands for code review, testing, and development workflows.

3.1. Code Review

Systematic code review with actionable feedback.

---
description: Comprehensive code review
argument-hint: "[focus: security|performance|style]"
allowed-tools:
  - Read
  - Grep
  - Glob
---

# Code Review Request

Perform a thorough code review of the current code or specified files.

## Review Checklist

### Correctness
- [ ] Does it work as intended?
- [ ] Are there logic errors or bugs?
- [ ] Are edge cases handled properly?
- [ ] Is error handling appropriate?

### Security
- [ ] Any security vulnerabilities?
- [ ] Input validation present?
- [ ] No injection risks (SQL, XSS, command injection)?
- [ ] Secrets/credentials properly handled?
- [ ] Authentication/authorization correct?

### Performance
- [ ] Any obvious performance bottlenecks?
- [ ] Unnecessary loops or redundant operations?
- [ ] Appropriate data structures used?
- [ ] Database queries optimized?
- [ ] Memory leaks or excessive allocations?

### Maintainability
- [ ] Code is readable and clear?
- [ ] Proper naming conventions?
- [ ] Functions/methods are appropriately sized?
- [ ] Duplication minimized (DRY principle)?
- [ ] Comments explain "why", not "what"?

### Testing
- [ ] Adequate test coverage?
- [ ] Tests are meaningful and not brittle?
- [ ] Edge cases tested?
- [ ] Integration tests if needed?

### Best Practices
- [ ] Follows language/framework conventions?
- [ ] Proper error handling?
- [ ] Resources properly cleaned up?
- [ ] Thread-safe if concurrent?
- [ ] Accessibility considerations (if UI)?

## Focus Area

{{{ input }}}

## Output Format

For each issue found:
1. **Severity**: Critical / Important / Minor / Suggestion
2. **Location**: File and line number
3. **Issue**: What's wrong or could be improved
4. **Recommendation**: Specific, actionable fix
5. **Example**: Code snippet showing the improvement (if helpful)

Prioritize critical and important issues. Be constructive and specific.

3.2. Add Tests

Generate comprehensive test cases for code.

---
description: Generate comprehensive test cases
allowed-tools:
  - Read
  - Write
  - Grep
  - Glob
---

# Test Generation

Generate comprehensive tests for the current code.

## Test Types

### Unit Tests
- Test individual functions/methods in isolation
- Mock external dependencies
- Cover happy paths and edge cases
- Fast and deterministic

### Integration Tests
- Test component interactions
- Use real dependencies where practical
- Test realistic scenarios
- May be slower but more comprehensive

### Edge Cases
- Boundary conditions (empty, null, zero, max values)
- Error conditions
- Unexpected input
- Concurrent access (if applicable)

## Test Framework

Use the appropriate testing framework for the language:
- **JavaScript/TypeScript**: Jest, Mocha, Vitest
- **Python**: pytest, unittest
- **Java**: JUnit, TestNG
- **Go**: testing package
- **Rust**: built-in test framework
- **Ruby**: RSpec, Minitest

## Test Structure

Follow the Arrange-Act-Assert (AAA) pattern:

```
describe('feature', () => {
  it('should do something specific', () => {
    // Arrange: Set up test data and dependencies
    const input = ...;

    // Act: Execute the code under test
    const result = functionUnderTest(input);

    // Assert: Verify the results
    expect(result).toBe(expected);
  });
});
```

## Test Requirements

- **Descriptive names**: Test names clearly state what is being tested
- **Independence**: Each test runs independently
- **Repeatability**: Tests produce same results every time
- **Comprehensive**: Cover happy paths, edge cases, and errors
- **Fixtures**: Create sample data where needed
- **Cleanup**: Properly tear down after tests

## Additional Context

{{{ input }}}

3.3. Refactor Code

Suggest and implement refactorings to improve code quality.

---
description: Refactor code for better quality
argument-hint: "[specific concern or 'general']"
allowed-tools:
  - Read
  - Write
  - Grep
  - Glob
---

# Code Refactoring

Analyze code and propose refactorings to improve quality, maintainability, and performance.

## Refactoring Goals

### Code Clarity
- Improve naming (variables, functions, classes)
- Extract complex expressions into named variables
- Break down large functions into smaller, focused ones
- Remove dead code
- Reduce nesting depth

### Design Improvement
- Extract repeated code into functions
- Apply design patterns where appropriate
- Improve separation of concerns
- Reduce coupling, increase cohesion
- Simplify complex conditionals

### Performance
- Optimize algorithms (reduce complexity)
- Eliminate unnecessary computations
- Improve data structure choices
- Reduce memory allocations
- Cache expensive operations

## Refactoring Process

1. **Identify Issues**: What needs improvement?
2. **Propose Changes**: Specific refactorings to apply
3. **Show Before/After**: Code snippets demonstrating the change
4. **Explain Benefits**: Why this improves the code
5. **Preserve Behavior**: Ensure functionality stays the same

## Safety

- Refactor incrementally (small steps)
- Ensure tests pass after each refactoring
- Don't change behavior (unless that's the goal)
- Preserve edge case handling

## Focus

{{{ input }}}

If no specific focus provided, perform a general refactoring review.

4. Git Commands

Commands for git workflows and commit message generation.

4.1. Generate Commit Message

Create conventional commit messages from staged changes.

---
description: Generate conventional commit message
allowed-tools:
  - Bash(git:*)
  - Write
---

# Commit Message Generator

Generate a commit message from staged changes following conventional commits format.

## Workflow

1. **Check for staged changes**: `git diff --staged --stat`
2. **If no staged changes**: Stop and ask user to stage changes first with `git add`
3. **If staged changes exist**:
   - Run `git diff --staged` to review the actual changes
   - Run `git diff --staged --name-only` to get list of files
   - Analyze the changes and generate a commit message in /tmp folder
4. **Write commit message**: Create a temporary file with the generated message and advise user to `git commit -t /tmp/commit-message.txt`
5. **User finalizes**: User reviews, edits if needed, saves and closes to commit

## Commit Process

```bash
# Check for staged changes
git diff --staged --stat
```

## Conventional Commits Format

```
<type>(<scope>): <subject>

<body>

<footer>
```

### Types
- **feat**: New feature
- **fix**: Bug fix
- **docs**: Documentation only
- **style**: Formatting changes
- **refactor**: Code restructuring
- **perf**: Performance improvement
- **test**: Adding/updating tests
- **build**: Build system or dependencies
- **ci**: CI configuration
- **chore**: Maintenance tasks

### Rules
- Subject: imperative mood, no capitalize, no period, max 50 chars
- Body: explain "why", wrap at 72 chars
- Footer: `BREAKING CHANGE:` or `Closes #123`

## Examples

```
feat(auth): add OAuth2 support

Implement OAuth2 flow for third-party authentication.
Supports Google, GitHub, and Microsoft providers.

Closes #234
```

```
fix(parser): handle empty input edge case
```

```
refactor(tools): modularize server into tool modules

Split monolithic server.py into separate modules:
- basic.py, buffers.py, files.py, projects.py
- org_roam.py, lsp.py, vcs.py
```

## Implementation Steps

1. Run `git diff --staged --stat` to check if there are staged changes
2. If output is empty, inform user: "No staged changes found. Please stage your changes first with `git add <files>`"
3. If changes exist:
   - Run `git diff --staged` to see the full diff
   - Analyze changes and generate commit message
   - Write the message to `/tmp/commit-message.txt`
   - Ask user to run `git commit -t /tmp/commit-message.txt` to open the editor with the pre-filled message
4. User reviews the message in their editor, makes any edits, then saves and closes to commit

## Notes

- Do NOT add Claude Code attribution footer
- Generate clean, standard commit messages only
- The editor workflow allows user to review and modify before finalizing
- If user closes editor without saving, commit is aborted

4.2. Review PR Changes

Review changes in a pull request or branch.

---
description: Review pull request changes
argument-hint: "[PR number or branch name]"
allowed-tools:
  - Bash(git:*)
  - Bash(gh:*)
  - Read
  - Grep
---

# Pull Request Review

Review changes in a pull request or git branch.

## Process

1. **Get PR info**: Use =gh pr view= or git commands to see changes
2. **Review commits**: Check commit messages and history
3. **Analyze changes**: Review the actual code changes
4. **Check tests**: Verify tests are included and passing
5. **Provide feedback**: Constructive, specific comments

## What to Review

### Code Quality
- Follows project conventions
- Properly structured and organized
- No obvious bugs or issues

### Testing
- Tests included for new features
- Tests cover edge cases
- Existing tests still pass

### Documentation
- Public APIs documented
- README updated if needed
- Comments explain complex logic

### Commits
- Meaningful commit messages
- Logical commit structure
- Each commit is coherent

### Breaking Changes
- Identified and documented
- Migration guide provided
- Versioning updated

## PR Information

{{{ input }}}

If a PR number is provided, fetch it with =gh pr view <number>=.
If a branch name is provided, compare with =git diff main...<branch>=.

5. Emacs Integration Commands

Commands that leverage Emacs MCP server for context-aware assistance.

5.1. Emacs Context Helper

Ask questions with automatic Emacs context gathering.

---
description: Ask about code with Emacs context
argument-hint: "your question"
allowed-tools:
  - mcp__emacs__get_current_context
  - mcp__emacs__lsp_*
  - mcp__emacs__*
---

# Emacs Context-Aware Assistant

You are helping a user working in Emacs. Gather their current context to provide the best assistance.

## Instructions

### 1. Gather Context

Use =mcp__emacs__get_current_context= to get:
- Current buffer name and file path
- Cursor position (line and column)
- Full buffer content
- Major mode (language/file type)
- Project information
- Modified status

### 2. Analyze Context

Review the gathered information to understand:
- What file/code they're working in
- What code is at or near the cursor position
- The surrounding context and structure
- The language and project type

### 3. Use LSP if Needed

If LSP is active and relevant:
- =mcp__emacs__lsp_hover= - Get symbol documentation
- =mcp__emacs__lsp_diagnostics= - Check for errors/warnings
- =mcp__emacs__lsp_definition= - Find symbol definitions
- =mcp__emacs__lsp_references= - Find symbol usages

### 4. Process Request

Provide helpful assistance based on the context:
- Explain code or concepts at cursor position
- Suggest improvements specific to the code
- Identify and explain issues
- Answer questions with full context awareness
- Reference exact line numbers and code snippets

### 5. Be Specific

When responding:
- Reference specific line numbers (e.g., "line 42")
- Quote relevant code snippets
- Mention the file path
- Use function/class names from the code
- Provide context-appropriate suggestions

## User's Question

{{{ input }}}

---

**Important**: Always call =mcp__emacs__get_current_context= first before responding. This ensures your answer is relevant to what the user is actually working on.

5.2. Emacs LSP Fix

Fix code issues using LSP code actions.

---
description: Fix code issues using LSP
argument-hint: "[optional: specific issue]"
allowed-tools:
  - mcp__emacs__get_current_context
  - mcp__emacs__lsp_diagnostics
  - mcp__emacs__lsp_code_actions
  - mcp__emacs__lsp_execute_code_action
---

# Emacs LSP Code Fix

Use LSP to identify and fix code issues in the current buffer.

## Process

### 1. Get Current Context

Call =mcp__emacs__get_current_context= to know:
- What file we're working with
- Cursor position
- Current code

### 2. Check Diagnostics

Call =mcp__emacs__lsp_diagnostics= to find:
- Errors (type errors, syntax errors)
- Warnings (unused variables, deprecated APIs)
- Suggestions (style improvements)

### 3. Get Code Actions

For each issue, call =mcp__emacs__lsp_code_actions= at the issue location to see:
- Quick fixes available
- Refactoring options
- Import additions
- Other automatic fixes

### 4. Execute Fixes

Either:
- Suggest which code action to apply
- Execute code action with =mcp__emacs__lsp_execute_code_action=
- Provide manual fix if no code action available

### 5. Verify

After applying fixes:
- Check if diagnostics are resolved
- Ensure code still works correctly
- Format if needed (=mcp__emacs__lsp_format=)

## Focus

{{{ input }}}

If no specific issue mentioned, review all diagnostics and suggest fixes.

6. Org-Mode Commands

Commands for working with Org-mode files.

6.1. Org-Roam Capture

Create org-roam notes with automatic linking and knowledge graph integration.

---
description: Create org-roam note
argument-hint: "note title and content"
allowed-tools:
- mcp__emacs__org_roam_create_note
---

# Org-Roam Capture

Create a new org-roam note using the MCP tool.

## Templates

| Key | Type       | Location                  | Tags         |
|-----|------------|---------------------------|--------------|
| d   | default    | ~/org-roam/               | -            |
| p   | permanent  | ~/org-roam/permanent/     | :permanent:  |
| l   | literature | ~/org-roam/literature/    | :literature: |
| c   | concept    | ~/org-roam/concepts/      | :concept:    |
| r   | reference  | ~/org-roam/reference/     | :reference:  |

## Template Structures

**permanent**: Source → Content → Links
**literature**: Source (Author/Title/Year) → Summary → Key Points → Quotes → Related
**concept**: Definition → Examples → Related Concepts
**reference**: Free-form sections with code blocks

## Workflow

1. Parse user input to determine note type and title
2. Call `mcp__emacs__org_roam_create_note` with:
   - `title`: extracted from input
   - `template_key`: d/p/l/c/r
   - `content`: generated body content
3. User finalizes in Emacs with `C-c C-c` (or `C-c C-k` to abort)

## User Input

{{{ input }}}

## Example

Input: "Create a concept note about idempotence"

```
mcp__emacs__org_roam_create_note(
  title="Idempotence",
  template_key="c",
  content="* Definition\n\nAn operation that produces the same result regardless of how many times it's executed.\n\n* Examples\n\n- HTTP GET requests\n- Setting a value: x = 5\n- DELETE requests\n\n* Related Concepts\n\n[[REST API Design]]\n[[Functional Programming]]"
)
```

7. Additional Commands

7.1. Find and Replace

Find and replace text across files.

---
description: Find and replace across files
argument-hint: "find/replace pattern [in scope]"
allowed-tools:
  - Grep
  - Read
  - Edit
  - Glob
---

# Find and Replace

Find text or patterns and replace them across files.

## Instructions

1. **Parse request**: Extract find pattern, replace text, and scope
2. **Search**: Use Grep to find all occurrences
3. **Review**: Show what will be changed
4. **Confirm**: Ask user to confirm before making changes
5. **Replace**: Use Edit tool to replace in each file
6. **Report**: Summarize changes made

## Pattern

{{{ input }}}

Expected format: "find pattern / replace text [in scope]"

Examples:
- "oldFunction / newFunction in *.ts"
- "TODO: fix this / DONE: fixed"
- "var foo / const foo in src/**/*.js"

## Safety

- Show all matches before replacing
- Ask for confirmation if more than 5 files affected
- Create backup suggestion for large changes
- Support undo instructions

7.2. Benchmark Code

Benchmark and profile code performance.

---
description: Benchmark code performance
argument-hint: "[code to benchmark]"
allowed-tools:
  - Read
  - Write
  - Bash
---

# Code Benchmarking

Create and run benchmarks for code performance analysis.

## Process

1. **Identify code**: What needs benchmarking?
2. **Create benchmark**: Write benchmark code using appropriate tool:
   - JavaScript: `console.time()` or benchmark.js
   - Python: `timeit` module
   - Go: `testing.B` benchmarks
   - Rust: `criterion` crate
   - Java: JMH

3. **Run benchmark**: Execute and collect results
4. **Analyze**: Interpret performance data
5. **Suggest optimizations**: Based on results

## Benchmark Focus

{{{ input }}}

## Reporting

Include:
- Operations per second
- Average execution time
- Memory usage (if available)
- Comparison with alternatives (if applicable)
- Recommendations for optimization

8. Best Practices

8.1. Command Design

  • Single purpose: Each command should do one thing well
  • Clear description: Help users understand when to use it
  • Flexible input: Support both arguments and no arguments gracefully
  • Consistent output: Follow similar formatting across commands

8.2. Documentation

  • Explain what the command does
  • Show example usage
  • Document any special requirements
  • Note any limitations or caveats

8.3. Tool Restrictions

Use allowed-tools to limit what a command can do:

  • Improves security
  • Makes intent clear
  • Prevents accidental operations

8.4. Testing

After creating a command:

  1. Tangle the file
  2. Test with /command-name
  3. Try with and without arguments
  4. Verify it respects allowed-tools

9. Related Configuration

  • Settings - Configure permissions for tools used by commands
  • Skills - Autonomous alternatives to user-invoked commands
  • MCP Servers - External tools that commands can use

10. Resources