Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim trailing spaces in Xcode

People also ask

How do I get rid of trailing space in Xcode?

The best and easy way without using scripts, hacks and much more. Just go to Find And Replace and press alt/option + space and press space button in the replace bar and then click on replace all. It will replace the whitespaces with normal spaces and the warning/ error will be gone !!

How do you trim leading and trailing spaces in Swift?

Trim leading and trailing spaces To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.

How do I remove spaces from a string in Swift?

To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered. append(character) } } print(filtered) // "Hello, World! "

What are trailing whitespace?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.


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.


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";
}

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.