A

Auto-Format on Edit Hook

Automatically runs Prettier (or any formatter) on every file Claude edits or writes. Ensures consistent code style without manual intervention. Supports any formatter that accepts file paths as arguments.

HookAnthropiccode reviewv1.0.0MIT
0 views0 copies

Hook Type

PostToolUse -- Fires after Claude uses the Edit or Write tool.

Description

This hook ensures every file Claude touches is automatically formatted to your project's style guide. It extracts the file path from the tool input and pipes it to Prettier. You can swap Prettier for any formatter (Black, gofmt, rustfmt, etc.).

Patterns/Rules

  • Triggers on Edit and Write tool uses (matcher: Edit|Write)
  • Reads the file_path from the tool input JSON via jq
  • Runs the formatter in-place on the edited file
  • Non-zero exit from the formatter is reported but does not block Claude

Configuration

Prettier (JavaScript/TypeScript/CSS/HTML/JSON)

{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write 2>/dev/null || true" } ] } ] } }

Black (Python)

{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "FILE=$(jq -r '.tool_input.file_path'); if [[ \"$FILE\" == *.py ]]; then black \"$FILE\" 2>/dev/null || true; fi" } ] } ] } }

ESLint + Prettier Combo

{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "FILE=$(jq -r '.tool_input.file_path'); npx eslint --fix \"$FILE\" 2>/dev/null; npx prettier --write \"$FILE\" 2>/dev/null || true" } ] } ] } }

Action

After every Edit or Write tool call, the hook:

  1. Parses the JSON tool input to extract the file path
  2. Runs the configured formatter on that file
  3. The file is silently reformatted in-place
  4. Claude's next read of the file sees the formatted version
Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates