Remove Whitespace From Code Changes

I can’t tell you how many times I’ve committed and pushed some code changes only to realize or have a colleague point out that my changes introduced trailing whitespace. This happened all too frequently until I recently adopted some tools and practices to keep my whitespace in check. Turns out it’s pretty easy to remove whitespace from code changes.

IDE Configuration

I’m a VS Code user, and a big fan of that IDE (Integrated Development Environment). If you don’t already use a particular IDE, I recommend checking it out.

Whichever IDE you use, there should be a setting or configuration to show all whitespace right in your editor. For VS Code users, here’s how to activate this feature:

  • With VS Code open, navigate to Code > Preferences > Settings (on Mac, on Windows this is File > Preferences > Settings)
VS Code Settings location (Mac)
  • In the Settings panel you should see a search bar. Here you can search for ‘Render whitespace’ and the top result should be ‘Editor: Render Whitespace’. In the dropdown menu here, select ‘all’. You could also select ‘trailing’ to see only the trailing whitespace, but my preference is to see all whitespace flagged.
Use the Render Whitespace dropdown to show all whitespace in your files when editing.

Project Settings

If your current project has a .vscode > settings.json file for handling settings specific to that project, you can optionally set a whitespace configuration there by adding the following:

{
  "editor.renderWhitespace": "all", 
}

Check The Git Diff

The moment that you’re ready to commit some work is a great time to stop and check the git diff of your work. Not only can this help you catch accidental or erroneous code changes, it’s also an easy way to see if you’ve introduced any unwanted whitespace changes.

The screenshot above is from some actual code I wrote for this site, and the red blocks each indicate whitespace changes (which I ended up removing).

the author profile picture

Ryan Neilson is a software developer from Nova Scotia, Canada, where he lives with his wife and their menagerie of pets. He has worked extensively with PHP, WordPress, JavaScript, React, SCSS and CSS. Ryan can be found professionally at News Corp, where he works as a lead software engineer.