Skip to content

Claude Code

The Complete Cheat Sheet

Full docs: docs.anthropic.com/en/docs/claude-code — complete documentation index

Keyboard Shortcuts

Essential

KeyAction
EnterSend message / submit
EscInterrupt / stop generation
Esc EscOpen rewind menu (go back in conversation or code)
Ctrl+CCancel current operation (hard stop)
Ctrl+DExit Claude Code
Shift+TabCycle modes: Normal → acceptEdits → Plan
?Show available keyboard shortcuts
KeyAction
Ctrl+RSearch command history
Ctrl+TToggle task list
Ctrl+OToggle verbose transcript
Ctrl+GOpen external editor (write long prompts)
Ctrl+VPaste image (screenshots, diagrams)
Alt+P / Option+PSwitch model
Alt+T / Option+TToggle extended thinking
Alt+MToggle permission modes

Editing (Bash-style)

KeyAction
Ctrl+A / Ctrl+EStart / end of line
Opt+F / Opt+BWord forward / back
Ctrl+WDelete previous word
Ctrl+KDelete to end of line
Ctrl+UDelete entire line
Ctrl+YPaste deleted text (Alt+Y to cycle)
Ctrl+JNewline (control sequence alternative)
\ + EnterNew line (without sending)

Background Tasks

KeyAction
Ctrl+BSend running task to background
Ctrl+FKill all background agents (press twice confirm)

Tip: Run /terminal-setup to enable Shift+Enter for multi-line input in iTerm2 & VS Code. Run /keybindings to customize all shortcuts.


Slash Commands

Session Control

CommandAction
/clearReset conversation history (fresh start)
/compact [hint]Compress context to save tokens. Optional hint for what to keep.
/rewindGo back in conversation AND/OR code changes
/export [file]Export conversation to file or clipboard
/copyCopy last response to clipboard
/costShow session cost & token usage
/usageShow plan usage & rate limits
/contextToken consumption visualization
/statsVisualize daily usage and streaks
/rename [name]Rename current session
/resume [session]Resume conversation by ID or name

Configuration

CommandAction
/configOpen settings panel
/modelSwitch between Sonnet / Opus / Haiku
/permissionsView & update tool permissions
/keybindingsOpen keyboard shortcuts config file
/vimToggle vim mode for input
/terminal-setupSetup Shift+Enter for multi-line input
/themeChange color theme
/statusOpen Settings (Status tab)
/statuslineSet up status line UI
/hooksOpen interactive hooks manager

Development

CommandAction
/initCreate CLAUDE.md for your project — do this first!
/memoryView & edit CLAUDE.md project memory
/reviewCode review analysis
/doctorEnvironment diagnostics & health check
/agentsManage sub-agents
/mcpManage MCP servers
/planEnter plan mode from prompt
/debug [description]Troubleshoot current session
/add-dirAdd working directory during session
/todosList current TODO items

Advanced

CommandAction
/insightsGenerate HTML usage report
/pr_commentsView GitHub PR feedback
/install-github-appSetup automated PR reviews
/tasksPersistent task list management
/teleportTransfer session between web ↔ local
/desktopHand off CLI session to Desktop app

CLI Launch Flags

Starting Sessions

FlagAction
claudeStart interactive session
claude "query"Start with an initial prompt
claude -p "query"Print mode — answer & exit (for scripting)
claude -cContinue last conversation
claude -r "name"Resume specific session by name or ID
claude -w nameStart in isolated git worktree

Model & Behavior

FlagAction
--model sonnetUse Sonnet (fast, cheap)
--model opusUse Opus (smartest)
--fallback-modelAutomatic fallback model
--agent my-agentUse a specific sub-agent
--permission-mode planStart in plan mode
--max-turns NLimit conversation turns
--max-budget-usd NSet max spend limit
--teammate-modeAgent team display mode

Context & Directories

FlagAction
--add-dir ../pathAdd extra directories to context
--chromeEnable browser integration
--no-chromeDisable Chrome integration
--ideAuto-connect to IDE
--verboseShow detailed logging

Session Management

FlagAction
--session-idUse specific session UUID
--fork-sessionNew session ID when resuming
--from-prResume sessions linked to GitHub PR

System Prompt

FlagAction
--system-promptCustom system prompt
--system-prompt-fileSystem prompt from file
--append-system-promptAppend to default system prompt

Permissions

FlagAction
--allowedToolsWhitelist specific tools
--disallowedToolsBlock specific tools
--tools "Bash,Edit"Restrict to only these tools

Configuration

FlagAction
--init / --init-onlyRun initialization hooks
--maintenanceRun maintenance hooks
--strict-mcp-configOnly use specified MCP servers
--disable-slash-commandsDisable all skills
--setting-sourcesComma-separated setting sources
--settingsPath to settings JSON

Output Formats (for -p mode)

FlagAction
--output-format textPlain text (default)
--output-format jsonStructured JSON
--output-format stream-jsonReal-time streaming JSON
--json-schemaValidated JSON output matching schema
--input-formatInput format for print mode

Tip: Pipe data in! git diff | claude -p "review this" or cat error.log | claude -p "explain"


The Big 5 — Claude Code Extension System

1. CLAUDE.md — Project Memory

WhatA markdown file Claude reads every session. Your project’s “brain dump” — coding style, architecture, common commands, conventions.
Where.claude/CLAUDE.md (project) or ~/.claude/CLAUDE.md (global)
CreateRun /init in your project — Claude generates it for you

2. Custom Slash Commands

WhatYour own /commands. Markdown files with prompts that YOU invoke. Like prompt templates.
Where.claude/commands/ (project) or ~/.claude/commands/ (global)
UseFilename = command name. review.md → type /project:review

3. Skills — Auto-Invoked Knowledge

WhatLike commands, but Claude decides when to use them automatically. You DON’T invoke them — Claude detects when they’re relevant.
Where.claude/skills/ with a SKILL.md inside each skill folder
UseJust work on your project — Claude picks up relevant skills from context

4. Sub-Agents — Specialized Helpers

WhatSeparate Claude instances with their own context & role. Like team members: reviewer, debugger, architect, etc.
Where.claude/agents/ (markdown files with YAML metadata)
Invoke/agents to manage, or just say “Use the reviewer agent”
CLI--agent my-agent or --agents '{json}'

5. MCP Servers — External Tool Connections

WhatConnect Claude to external tools: GitHub, Notion, databases, APIs, browsers, etc.
Setupclaude mcp add <name> <command>
Listclaude mcp list
Config--mcp-config ./mcp.json at launch

+ Plugins — Community Extensions

WhatBundles of commands, skills, hooks & more from the community
Browse/plugin to browse, install, enable, disable
Dir--plugin-dir ./my-plugins for local plugins

How they differ:

Custom Commands → YOU invoke them vs Skills → CLAUDE invokes them vs Sub-Agents → Separate AI instances vs MCP → External tool connections


Permission Modes

ModeDescription
NormalClaude asks permission for every tool use (read, write, bash, etc.)
acceptEditsClaude runs tools WITHOUT asking. Faster but less control. Good for trusted tasks.
Plan ModeClaude ONLY reads & plans. Won’t write or run anything. Review first, then switch to Normal to execute.
dontAskAuto-denies permissions unless pre-approved in settings.
bypassPermissionsSkips all permission prompts. Requires safe/sandboxed environment.

Cycle: Shift+Tab → Normal → acceptEdits → Plan → Normal…

Permission Rule Syntax

PatternDescription
Tool(specifier)Allow a specific tool with a specifier
Bash(git:*)Allow all git commands
Bash(npm:*)Allow all npm commands
Edit(**/src/**)Allow edits in src directory
Wildcards (*)Match any value within a specifier
Evaluation orderdeny → ask → allow (deny wins over allow)

Best workflow: Start in Plan Mode to explore & understand the problem. Review Claude’s plan. Switch to Normal/acceptEdits to implement.


Hooks — Event Automation

Hook Events

HookDescription
PreToolUseRuns BEFORE Claude uses a tool — validate, block, or modify
PostToolUseRuns AFTER a tool — check results, auto-format, lint
PostToolUseFailureAfter a tool call fails
UserPromptSubmitBefore your message is processed
PermissionRequestWhen permission dialog appears
StopWhen Claude finishes its response
SessionStartWhen a session begins
SessionEndWhen a session ends
PreCompactBefore context compression
NotificationWhen Claude sends a notification
SubagentStartWhen a subagent starts
SubagentStopWhen a subagent stops
TeammateIdleAgent team teammate about to go idle
TaskCompletedWhen a task is marked as completed
ConfigChangeConfig file changes during session
WorktreeCreateWhen a worktree is created
WorktreeRemoveWhen a worktree is removed

Handler Types

TypeDescription
commandRun a shell command
httpPOST to an HTTP endpoint
promptSingle-turn Claude evaluation
agentSubagent with tools for verification

Example: Auto-run prettier after every file edit, or block writes to .env files. Configure in your settings JSON.


Input Superpowers

FeatureDescription
@ mentionType @ to reference files & folders. Claude reads them into context.
! prefixType ! to run shell commands inline. E.g., ! git status
Paste imagesCtrl+V to paste screenshots, diagrams, error images directly
Pipe inputcat file.py | claude -p "explain" — feed data directly
Multi-dirclaude --add-dir ../api ../web — work across multiple projects
Worktreesclaude -w feature — isolated git branch + Claude session

Pro tip: Use @ references instead of copy-pasting file contents. It’s smarter with context and uses fewer tokens.


Configuration

Settings Priority (highest → lowest)

LevelLocation
Enterprise/etc/claude-code/managed-settings.json
Project Local.claude/settings.local.json (your personal project settings)
Project Shared.claude/settings.json (committed to git, shared with team)
User Global~/.claude/settings.json (your defaults)

Config CLI

CommandAction
claude config listShow all settings
claude config get keyCheck a value
claude config set key valueChange a value
claude config add key valueAdd to array

Permissions example: Allow git commands without asking: add "Bash(git:*)" to your allowedTools in settings.


File Structure Map

Project Level (.claude/)

File/DirPurpose
CLAUDE.mdProject memory — conventions, architecture, commands
settings.jsonShared project settings (committed to git)
settings.local.jsonYour personal settings (gitignored)
commands/Project slash commands (*.md files)
skills/Project skills (folders with SKILL.md)
agents/Project sub-agents (*.md files)

Global Level (~/.claude/)

File/DirPurpose
CLAUDE.mdGlobal memory (applies to ALL projects)
settings.jsonGlobal settings
commands/Personal global commands
skills/Personal global skills
keybindings.jsonCustom keyboard shortcuts

Rewind & Checkpoints

Key/CommandAction
Esc EscOpen rewind menu anywhere
/rewindSame but typed as command

Rewind Options

OptionDescription
ConversationGo back in chat only. Code stays as-is.
CodeRestore files only. Conversation stays.
Full RewindRestore both conversation AND code to a point.

Note: Bash side-effects (database changes, API calls, deleted files via rm) can’t be rewound. Checkpoints only track file edits by Claude. Use Git for permanent safety.


Pro Workflow — How to Get the Best Out of Claude Code

Starting a New Project

cd project && claude/init → Edit CLAUDE.md → Code!

The Plan → Execute Pattern

Shift+Tab → Plan Mode → Describe what you want → Review Claude’s plan → Shift+Tab → Normal/Auto → Execute

Saving Money

StrategyWhy
Use /compactWhen context gets big, compress it. Saves tokens dramatically.
Use /clearBetween unrelated tasks. Don’t carry irrelevant context.
Use SonnetFor routine tasks. Save Opus for complex architecture decisions.
Use @ refsInstead of pasting code — smarter context management.

Debugging Like a Pro

StrategyWhy
Paste errorsCopy-paste the full error message. Claude parses stack traces brilliantly.
Paste screenshotsCtrl+V a screenshot of the bug. Claude sees it.
Pipe logscat error.log | claude -p "what's wrong?"
/doctorIf something feels broken, run this first.

Parallel Development

StrategyHow
Worktreesclaude -w feature-auth — isolated branch + session
Multiple dirs--add-dir ../api ../web — work across repos
BackgroundCtrl+B sends a task to background so you can start another
Agent TeamsMultiple Claude instances collaborating (experimental)

Create Custom Commands

StepAction
1. Create file.claude/commands/review.md
2. Write promptThe markdown content IS the prompt Claude will use
3. Use itType /project:review in Claude Code

Optional YAML Frontmatter

KeyPurpose
argument-hintPlaceholder text for argument input
descriptionShows in /help listing
allowed-toolsRestrict what tools the command can use
modelForce a specific model for this command

Variable: $ARGUMENTS

Use $ARGUMENTS in your markdown — it gets replaced with whatever you type after the command.

Example: /project:review src/auth.ts$ARGUMENTS = “src/auth.ts”


Remote Control — Continue Sessions From Any Device

Control your local Claude Code session from your phone, tablet, or any browser. Your session runs locally — the remote device is just a window into it.

Requirements

RequirementDetails
SubscriptionMax plan required (Pro coming soon). No API keys.
AuthRun claude/login to sign in via claude.ai
TrustRun claude in your project dir once to accept trust

Starting a Remote Session

MethodCommand / Action
New sessionclaude remote-control
From existingType /remote-control or /rc inside a session
Enable for all/config → Enable Remote Control for all sessions → true

Connecting From Another Device

MethodHow
Session URLShown in terminal — open in any browser
QR codePress spacebar to toggle QR display, scan with phone
Session listOpen claude.ai/code or Claude app — find by name (🟢 = online)

Launch Flags

FlagAction
--verboseShow detailed connection & session logs
--sandboxEnable filesystem & network isolation
--no-sandboxDisable sandboxing (default)

How It Works

  • Your local session makes outbound HTTPS only — no inbound ports opened
  • All traffic routes through Anthropic API over TLS
  • Session reconnects automatically after sleep or network drops
  • One remote connection per Claude Code instance

Remote Control vs Claude Code on the Web

FeatureRemote ControlClaude Code on the Web
Runs onYour machineAnthropic cloud infrastructure
Local tools✅ MCP, filesystem, project config❌ Cloud environment only
Best forContinue local work from anywhereStart fresh without local setup

Limitations

LimitationDetails
One session at a timeEach Claude Code instance supports one remote connection
Terminal must stay openClosing the terminal or stopping claude ends the session
Network timeout~10 min without network → session times out (restart with claude remote-control)

Tip: Use /rename before /remote-control to give the session a descriptive name — makes it easy to find across devices. Use /mobile to get the Claude app download QR code.


Quick Reference — Most Used Combos

Daily Essentials

WhatHow
Start projectcd project && claude
Continue where I left offclaude -c
Quick question, no sessionclaude -p "how do I..."
Review my changesgit diff | claude -p "review"
Explain errorcat error.log | claude -p "explain"
Check costType /cost anytime
Undo mistakeEsc Esc → rewind

Power Moves

WhatHow
Parallel sessionsclaude -w feature-a + claude -w feature-b
Custom reviewer agentCreate .claude/agents/reviewer.md
Auto-format on editPostToolUse hook → run prettier
Web sessionclaude --remote "fix the bug"
Transfer to localclaude --teleport
Budget limitclaude -p --max-budget-usd 2 "query"
Scripted automationclaude -p --output-format json "query" | jq