How to Trim Trailing Whitespace on Save in VS Code
Keeping your code clean and free of unnecessary spaces is essential for maintaining readable source code and preventing clutter in your version control commits. This guide provides a quick, step-by-step walkthrough on how to configure Visual Studio Code (VS Code) to automatically remove trailing whitespace every time you save a file.
You can enable this feature in VS Code using either the graphical
Settings editor or by directly editing your settings.json
configuration file.
Method 1: Using the Settings Editor
- Open the Settings menu by using the keyboard shortcut Ctrl + , (Windows/Linux) or Cmd + , (macOS). Alternatively, go to File > Preferences > Settings (or Code > Preferences > Settings on macOS).
- In the search bar at the top of the Settings window, type:
trim trailing whitespace. - Locate the setting labeled Files: Trim Trailing Whitespace.
- Check the box next to “When enabled, will trim trailing whitespace when saving a file.”
Method 2: Editing the
settings.json File
If you prefer configuring your editor via code or want to sync your settings easily, you can add the rule directly to your configuration file:
- Open the Command Palette using Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (macOS).
- Type
Preferences: Open User Settings (JSON)and press Enter. - Add the following line to your settings object:
"files.trimTrailingWhitespace": true- Save the
settings.jsonfile.
Once enabled, VS Code will instantly clean up all trailing spaces across your entire document whenever you trigger a save command.