Trim trailing spaces in Xcode
Asked Answered
P

10

136

Is there a way to force Xcode to trim trailing whitespaces when I save file?

I'm using version 3.1.3 if that matters.

Palaeobotany answered 7/9, 2009 at 17:35 Comment(0)
H
24

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";
}
Harald answered 8/9, 2009 at 6:11 Comment(3)
Ah, yes, so simple... Thanks. Is there any way to associate this with file save?Palaeobotany
To work on an entire file (which is probably what you would want to do), set Input to "Entire Document" and Output to "Replace Document Contents." However, this leaves the cursor at the bottom of the file.Dunston
This answer is obsolete as of Xcode 4.4. See the answer by Martin Stolz.Centurial
Z
302

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

Zink answered 6/8, 2012 at 14:15 Comment(5)
This setting only trims a line's trailing whitespace after the cursor has left that line. So, it still allows you to save a file with one line of trailing whitespace, if the cursor is on that line upon save.Rabideau
Why on earth is this not the default? If you have an existing file with trailing whitespace, just mark all, cut, save, paste, save.Pothead
This needs to override the hacky script solution on this answer.Arresting
Using this + ctrl-i on all existing files takes care of trailing whitespacesSuppurative
The feature is still listed in 13.3 but it does not work, or at least does not work reliably. It's common to find trailing whitespace throughout files after editing.Typical
B
25

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.

Bursitis answered 13/4, 2010 at 9:37 Comment(9)
I'm using this plugin as well. It does what it says.Diedrediefenbaker
Would be perfect, unfortunately it does not work on Xcode 4 at the moment :(Warmongering
We now have some basic Xcode 4 support. See our new pluginSelfdenial
Where can I find the "Correct whitespace on save" parameter?Swetlana
I finally managed to get GTM working on Xcode 4.3.2, but the installation instructions from the GTM wiki seemed to be invalid. Instead of placing the .xcplugin in ~/Library/Application Support/Developer/Shared/Xcode/Plug-ins (as per Google's instructions) I had to put it in /Applications/Xcode.app/Contents/PlugIns and restart Xcode.Columbia
@KristoferSommestad Followed your instructions for the same Xcode version (build 4E2002), but couldn't find "Correct whitespace on save" anywhere in the preferences despite of the fact that "About GTM Xcode Plugin" does appear under "Xcode" in the main menu..Throughput
No, me neither Desmond. But there's an option to strip all ws in the Edit menu, iirc. And a short command for it too.Columbia
@DesmondHume unfortunately the "Correct whitespace on save" preference is only available in GTMXcodePlugin for XCode 3.x. Since XCode 4, I'm using a custom script (called by my Makefile) to remove trailing whitespacesBursitis
I installed the plugin as per the instructions on the GTM site, and it worked as soon as I restarted Xcode, using Xcode 4.3.3 on Mac OS X 10.7.Barbershop
H
24

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";
}
Harald answered 8/9, 2009 at 6:11 Comment(3)
Ah, yes, so simple... Thanks. Is there any way to associate this with file save?Palaeobotany
To work on an entire file (which is probably what you would want to do), set Input to "Entire Document" and Output to "Replace Document Contents." However, this leaves the cursor at the bottom of the file.Dunston
This answer is obsolete as of Xcode 4.4. See the answer by Martin Stolz.Centurial
A
10

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.

Alfons answered 31/3, 2021 at 21:1 Comment(0)
B
3

For Xcode 8, I installed the swimat Xcode plug-in, for formatting Swift code, which removed all trailing spaces and whitespace-only lines.

Installation Methods

  1. Install via homebrew-cask:

    brew cask install swimat
    
  2. Download the App directly:
    https://github.com/Jintin/Swimat/releases/download/v1.3.5/Swimat.zip

  3. Clone extension branch and archive to Mac App.

Usage

Once installed, you can run Swimat in Xcode via Editor -> Swimat -> Format.

Backwoods answered 15/8, 2017 at 13:19 Comment(2)
this tool dont remove blank lines.Milli
@Milli this answer is about removing trailing spaces, not blank lines.Duologue
C
1

This is not possible in Xcode 3.2

Edit:

I answered this question so briefly because there's no way to do this properly.

Of course, since it's software, you can do anything: Starting with Input Manager hacks or other ways of code injection to system wide keyboard interception, you can alter your local system to do anything anytime. You could set up an Applescript folder action (arrgh) or use a launch demon and the FSEvents facility to watch your source code files.

You can also add a couple of scripts to Xcode (user scripts in the menu, script phases in targets, custom Actions in the organizer, there's even the very unknown possibility a startup script), but all these solutions are flawed, since it involves the user or custom setup on the user's machine.

I'm not aware of a solution which simply works after checking out a project from SCM. I believe that there's need for this and similar customization scripts, so I filed a bug (radar 7203835, "Feature: more user script triggers in Xcode workflow"). I did not receive any feedback yet.

Here's the full text of the radar entry:

It would be useful to have more places to run scripts in Xcode.

Examples:

  1. Pre build scripts
    Pre build scripts could be used to build prerequisites like *.xcconfig files or config.h headers. This is not possible with a "Run Script Build phases", since dependency tracking takes place before any build phase is triggered.

  2. Post build scripts
    Similar to above, but running after the build finished (including code signing etc). Useful for additional packaging, validity checking etc.

  3. Pre/Post SCM Commit scripts.
    To check project integrity.

  4. Pre/Post File Save Script.
    To check/alter a file before saving. E.g. run cody beautifiers

  5. Custom project actions.
    I'm aware of the organizer's ability to define arbitrary actions. But this is a per user feature (not part of the project). I'd like to define actions like build or clean that show up in the build menu and that are part of a project.

Careaga answered 7/9, 2009 at 19:22 Comment(2)
Edited to answer why workarounds are unsatisfying in this caseCareaga
Thanks. While I'm in favor of doing it in the proper way, I'd settle for about any not-too-intrusive hack. Those extra whitespaces are really annoying.Palaeobotany
A
1

See here for Xcode4: http://www.wezm.net/technical/2011/08/strip-trailing-whitespace-xcode-4/

Cool, Google toolbox for Mac now adds a "trim whitespace" option for Xcode4.

http://code.google.com/p/google-toolbox-for-mac/downloads/list

Thanks you, Google!

Abut answered 9/11, 2011 at 16:32 Comment(0)
W
0

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 !!

Wyler answered 1/1, 2020 at 16:57 Comment(3)
Does this only remove trailing spaces as requested in the question?Knockknee
Right idea @H2zee, just need to use RegEx instead (check out my answer above).Alfons
@Knockknee it depends on you, whatever you want to change, you can. let me know if you have any problemWyler
I
0

One way not perfect but it's working is to use Find and Replace. Find double space and replace with nothing. And after that Command+A and Control+I.

As I said is not perfect maybe you need to fix something, but for me worked.

Indo answered 21/1, 2023 at 21:39 Comment(0)
E
0

Adding one more thing to @Martin Stolz answer, This won't work automatically for the old existing files, To have it work you will need to do an extra step which is cutting all the code in the file and paste it once again.

Easeful answered 5/12, 2023 at 15:34 Comment(3)
This should be a comment on that other answer instead of posting it as a separate answer.Enwreathe
Sometimes it’s better to add it as a separated answer to highlight it cause most of the people don’t care about comments like answersEaseful
Except an answer should actually provide an answer to the question. Your comment doesn’t stand on its own as an answer.Enwreathe

© 2022 - 2024 — McMap. All rights reserved.