Trim trailing spaces in Xcode

Starting from Xcode 4.4 whitespaces will be trimmed automatically by default, unless the line is all whitespace. You can also activate Including whitespace-only lines to fix this, which is not active by default.

Go to Xcode > Preferences > Text Editing > While editing

Xcode preferences screenshot


I'm using the Google Toolbox For Mac Xcode Plugin, it adds a "Correct whitespace on save" parameter that trim trailing whitespace on save. I missed that a lot from emacs.


I find using the new Automatically trim trailing whitespace -> Including whitespace-only lines as suggested by @MartinStolz works well while editing but I sometimes need to do Cmd + a -> Ctrl + i and save the file multiple times with the file in focus when I'm not editing.

In case you want to clean a whole project (excluding .md files) without using scripts, you can also do a Find & Replace -> Regular Expression. Since this technique removes trailing space and tabs for documentation/comments as well, you can also try a negative lookahead for blacklisted characters to filter out single-line comments.

Find all trailing whitespace:

[\t ]+$

Find trailing whitespace without touching single-line comments:

^(?!.*\\\\)[\t ]+$

Replace:

<nothing>

So linting can also be done without swiftlint autocorrect or similar third party solutions.


You can create a script and bind it to a keyboard shortcut:

  • Select Scripts Menu > Edit User Scripts...
  • Press the + button and select New Shell Script
  • Give it a name like "Strip Trailing Spaces", and give it a shortcut like ⌃⇧R.
  • Set Input to "Selection" and Output to "Replace Selection"

Then enter the following script:

#!/usr/bin/perl

while (<>) {
    s/\s+$//;
    print "$_\n";
}