Skip to content

hookCode quality

Trim Trailing Whitespace

A Claude Code hook that removes spaces and tabs at the end of lines in each file the agent edits, keeping diffs free of invisible changes.

npx workspacetemplates add trim-trailing-whitespace --tool claude-code

Writes 1 file to .claude/

.claude/settings.jsonmerge into your file16 lines · 989 BFile
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node -e \"process.on('uncaughtException',()=>process.exit(0));let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{let j={};try{j=JSON.parse(d)||{}}catch(e){process.exit(0)}const i=j.tool_input||{};const f=String(i.file_path||'');const fs=require('fs');const rd=()=>{try{return fs.readFileSync(f,'utf8')}catch(e){return null}};const e=require('path').extname(f).toLowerCase();if(['.md','.markdown','.mdx','.diff','.patch'].includes(e))process.exit(0);const t=rd();if(t===null||t.includes(String.fromCharCode(0)))process.exit(0);const o=t.split('\\n').map(l=>{const cr=l.endsWith('\\r');let b=cr?l.slice(0,-1):l;while(b.endsWith(' ')||b.endsWith('\\t'))b=b.slice(0,-1);return cr?b+'\\r':b}).join('\\n');if(o!==t)fs.writeFileSync(f,o);process.exit(0)})\"",
            "timeout": 15
          }
        ]
      }
    ]
  }
}

What it does

Invisible trailing spaces create noisy diffs and fail some linters. After every Edit or Write this PostToolUse hook rewrites the file with those spaces and tabs removed from each line.

Windows line endings stay as they are. Markdown, diff and patch files are skipped because trailing spaces can carry meaning there, and files with null bytes are left alone.

Example

you › Add a retry loop to fetchUser in api.js.

agent › The new lines had two stray spaces. The hook strips them and the saved file shows a clean diff.

Questions

Why are Markdown files skipped?
Two trailing spaces mark a hard line break in Markdown, so removing them could change how the page renders.
Will it touch lines I did not edit?
It cleans the whole file, so old trailing spaces elsewhere in that file disappear too.
  • Block Generated File Edits

    HookCode quality

    Free
  • Block Large Writes

    HookCode quality

    Free
  • Block Vendor Edits

    HookCode quality

    Free
  • Ensure Final Newline

    HookCode quality

    Free