Trim trailing spaces in Xcode - xcode

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.

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

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.

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
Install via homebrew-cask:
brew cask install swimat
Download the App directly:
https://github.com/Jintin/Swimat/releases/download/v1.3.5/Swimat.zip
Clone extension branch and archive to Mac App.
Usage
Once installed, you can run Swimat in Xcode via Editor -> Swimat -> Format.

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:
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.
Post build scripts
Similar to above, but running after the build
finished (including code signing etc).
Useful for additional packaging,
validity checking etc.
Pre/Post SCM Commit scripts.
To check project integrity.
Pre/Post File Save Script.
To check/alter a file before saving. E.g. run cody beautifiers
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.

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!

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

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.

Related

Disable code completion inside quotes in Sublime Text 3

Is there any way to disable Sublime Text 3 firing code completion, when cursor is inside single or double quotes:
This seems to be pointless behaviour and is a little bit annoying.
I'm using newest stable (3065) Sublime Text 3, with PHP Completions Kit plugin, if that matters.
So it turns out that your PHP Completions Kit plugin is probably to blame. I forked the code on Github if you'd like to follow along.
You can populate the auto-complete dropdown in Sublime by creating a JSON-formatted .sublime-completions file. Essentially, it's a long list of snippets with associated triggers, the names of which show up in the dropdown and are matched by a fuzzy search method based on what you type. The completions are all scoped so they only come up in the desired parts of your code: for example, you wouldn't want standard function names coming up when you're trying to define a class, etc.
Back to the plugin. For several of the completion files, the scope was built up using negative selectors: starting with source.php (the base scope for all PHP code), and subtracting unwanted scopes. Once analyzed by Sublime, the completions would show up anywhere except where they were explicitly denied. An example, from function.sublime-completions:
"scope": "source.php - variable.other - meta.function.arguments - support.class - entity.other.inherited-class - meta.use - meta.catch - comment.block.documentation.phpdoc"
So those were all the places the author didn't want these completions to show up. Unfortunately, in these several files, s/he forgot to include the string scope, so completions appeared when you were typing strings, clearly undesired behavior. Fortunately, the fix is easy: go through all the completions files, check the scopes for negative selectors, and add - string to the end of them. Now, they'll still work exactly the same as before, except the completions won't show up in any kind of string.
Like I said at the top, I forked the project here, and have made the necessary corrections. I've also submitted a pull request, so we'll see if/when that gets accepted into the main code base. In the mean time, feel free to clone my repo into your Packages directory:
Click on Preferences -> Browse Packages... to open up your Packages directory. Go to that directory via the command line, then run
git clone https://github.com/MattDMo/sublime-phpck.git "PHP Completions Kit"
This will clone the repo into a folder named PHP Completions Kit, overriding the one installed by Package Control. Keep an eye on the plugin's Package Control page, and when you see the Modified field change from 2014-09-05 (it's in the tooltip if you mouse over the text 3 weeks ago) to sometime more recent, check the repo to see if it was my pull request that got merged and a new version released, and then you can feel free to delete the new folder in Packages and just stick with the Package Control version, as I won't be keeping my repo up-to-date on any new modifications to the package.
Update
My pull request has been merged, and Package Control has been updated.

Can I use Xcode as an IDE for Perl scripts?

I am using OS X 10.9 (Mavericks) and need to work on a Perl project. I enjoy using TextMate, Atom, and BBEdit, but would like to try using Xcode instead, as it has good integration with git, a clean look, and I am already intimately familiar with the UI and syntax highlighting colour scheme.
Is it possible to use Xcode as an IDE to develop and run Perl scripts, in a way that puts it on par, or ahead of, existing text editors?
Update
I used Xcode 5 as an IDE for Perl for more than a month, and found it an excellent alternative to regular text editors like Atom and TextMate. However, like pure text editors, Xcode lacks support for debugging in Perl. I have since discovered Komodo IDE, a really nice IDE for Perl (and similar languages) that supports graphical Perl debugging, plus remote Perl debugging. I have since switched from using Xcode for Perl development to using Komodo IDE.
After some experimentation, it seems that Xcode makes for a fairly decent environment for developing Perl. Here is a screenshot of Xcode showing some Perl, project navigator, Git integration, and command-line output from a Perl script, as run by Xcode.
Xcode 5's built-in syntax highlighting works fine with Perl (.pl and .pm) files, right out of the box. But to use Xcode to write Perl more efficiently, you'll want to set up a new Xcode project:
Create a new Xcode workspace (File > New > Workspace) and select the folder you want to use for the Perl project.
Enable the Xcode navigator, so you can see the files in your project (View > Navigators > Show Navigators). Notice that Xcode does not show you a list of files in the workspace folder by default. If you're reading this, you're probably already an Xcode user, already knew that.
Manually add any files, or folders (groups, in Xcode parlance), that you want to see in the project (right-click on the Project Navigator pane and select Add files to "Project Name). Create groups to mirror your folder structure and add any files in subfolders to the groups. This can be a bit of work, depending on the size of your Perl project, but once you're set up it should not change much.
Click on your files in the Project Navigator to view the code. If you are using a Git or Subversion, Xcode will generate diffs as normal in the Xcode version editor.
To get your Perl script running when you hit Cmd-R:
Create a new scheme (Product > Scheme > New Scheme), configure Target to None and assign a name like Run Perl.
After creating the scheme, hit Edit Scheme.
In the Run perl scheme, set the Executable to /usr/bin/perl (select Other then press Shift-Cmd-G, enter /usr/bin/perl, and press Choose).
Go to the Arguments tab and ensure that your main script is the first argument. Add more arguments and environment variables as necessary.
Go to the Options tab and set Use custom working directory to your project folder. Deselect XPC services and any other options related to iOS or OS X development.
Press OK and when you press Cmd-R in Xcode, Xcode will call Perl, run your script, and show you the output.
To get Perl snippets and templates in Xcode, see How to create project templates in Xcode 4.
Extra tips:
If you are working with files that have extensions for an language that Xcode does not recognise, such as .sql files, you may be able to use the generic syntax highlighting. Go to Editor > Syntax Highlighting > Generic.

Can I use Xcode as a simple text editor?

Okay ... This may be a ridiculous question. (I'm still getting used to Mac.) I really like the auto fill-in-ahead predictive typing feature of Xcode.
Can I use it to simply edit files laying around different locations on my hard drive? I do not really want to create a project or anything (unless by PROJECT I mean simply loads several files, that are not related to each other, but that I may want to jump back and forth in editing them - I do not want to create a project from files that need to be compiled or anything).
If so, what's the best way to get started? When you open XCode, it asked a lot of wizard questions to get things set up. How would I simply get started to edit 5 or so files at a time ... where I might want to switch back and forth between them - and they are not in the same directory?
All I want to do is simply make changes and save them, make more changes and save again, repeat. Kind of like holding a lot of shell scripts that communicate with each other.
Okay ... so I know this was a silly question - but Xcode is so intimidating for newbies. Sometimes, one needs a place to just get started and I haven't found that yet.
It is possible to open the Xcode text editor on a single file from the command line.
open -a Xcode.app filename.txt
If you're going to use this a lot, you might consider making an alias in your ~/.bashrc.
alias xc="open -a Xcode.app"
As of Xcode 6, you cannot open a directory this way, as it will give you an error message stating that directories must be opened as part of a project. If you provide more than one file on the command line, Xcode appears to create a temporary project containing the files you provided. You can add files and folders to the temporary project, but there doesn't seem to be a way to save the temp project for use later.
If you want to open a file in Xcode, you can also use xed.
As the man page says:
xed -- Xcode text editor invocation tool.
You can simply call xed [file] to launch Xcode editor.
Notepad++ is the way to go. Xcode was never meant to be used as a general text editor.
EDIT: Sorry, didn't know that there wasn't a Mac port for Notepad++. Use TextWrangler instead.

Xcode 4 with opening brace on new line

It seems like the new Xcode 4 does not apply the XCCodeSenseFormattingOptions anymore. At least for me :(
Anyway, do you know how to put the opening brace to the new line for autocompletion in Xcode 4? I used to type this in terminal but it does not work for the new Xcode.
defaults write com.apple.Xcode XCCodeSenseFormattingOptions -dict BlockSeparator "\\n" PreMethodDeclSpacing ""
XCode 4 uses "code snippets" to do autocompletion, and ships with a built-in library of them: You can view the Code Snippet Library by clicking on the { } icon in the Library Pane, which is probably on the lower right-hand side of your main XCode window.
All of XCode 4's built-in code snippets put the opening brace on the same line as the statement – this is XCode 4's code snippet for an if statement, for example:
if (<#condition#>) {
<#statements#>
}
So if you wanted XCode 4 to autocomplete like so:
if (<#condition#>)
{
<#statements#>
}
...then you'd have to edit the code snippet accordingly. This, in turn, leads to two problems:
There are 44 code snippets built into XCode 4, and you'd have to edit each one separately.
XCode 4 won't allow you to edit the built-in code snippets.
These problems are more challenging than the simple defaults write command that worked in XCode 3 – but it is possible, if you're determined and you can edit property lists, to delve into the guts of XCode 4 and change these code snippets one by one.
/Developer/Library/Xcode/PrivatePlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets contains XCode 4's library of built-in code snippets. This probably goes without saying, but you should make a backup of this file before charging in and making edits – and afterwards you should make another backup, and set aside a copy of the file with your new and improved code snippets, because you'll almost certainly overwrite the contents of /Developer/Library/Xcode when you install the next release of XCode 4. (It's also possible that Apple will change the format of this file, add new code snippets, or do any number of other things that could render this answer ineffective.)
If you have Xcode 4.3 or later installed directly from the App Store, everything is inside the Xcode.app bundle. The path to SystemCodeSnippets.codesnippets is /Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets.
Anyhow, you'll find the above file contains several entries like this one:
<dict>
<key>IDECodeSnippetVersion</key>
<integer>1</integer>
<key>IDECodeSnippetCompletionPrefix</key>
<string>if</string>
<key>IDECodeSnippetContents</key>
<string>if (<#condition#>) {
<#statements#>
}</string>
<key>IDECodeSnippetIdentifier</key>
<string>D70E6D11-0297-4BAB-88AA-86D5D5CBBC5D</string>
<key>IDECodeSnippetLanguage</key>
<string>Xcode.SourceCodeLanguage.C</string>
<key>IDECodeSnippetSummary</key>
<string>Used for executing code only when a certain condition is true.</string>
<key>IDECodeSnippetTitle</key>
<string>If Statement</string>
<key>IDECodeSnippetCompletionScopes</key>
<array>
<string>CodeBlock</string>
</array>
</dict>
This is the code snippet for autocompleting an if statement. Edit the IDECodeSnippetContents to put the opening brace on a new line, save your work, and then restart XCode 4; if all goes well, you should be able to type an if statement and see the results.
You'll need to make at least half a dozen more edits to cover the most common autocompletes (for, while, etc.), and if you want to be thorough it'll take somewhere around 40 separate edits. It's a lot of work, but if you really, really want XCode 4's autocompletion to put your opening braces on a separate line, it can be done.
There’s no way to do it in Xcode 4. Please do file a bug.
Check out my modified (system wide) snippets for Xcode 4.2 here:
http://forrst.com/posts/Put_that_where_it_belongs_Xcode-PNL
It should take care of all the relevant opening curly braces for iOS development..
In Xcode 4.3.1, if you edit the following file as sudo from the terminal, as Scott Forbes described above, you can change where the opening brace appears. It would go away with new installations of Xcode, I would imagine, so I would vote that this is a bug with Apple too.
/Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/SystemCodeSnippets.codesnippets
Leslie
I used SnippetEdit for Xcode4 and it works amazingly. It basically lets you replace old snippets given by xcode with the new ones defined by yourself. See more here: https://www.macupdate.com/app/mac/43352/snippet-edit
Just make a user code snipped which overrides Apple's version. Do this by entering in the Completion Shortcut field the same name as in the default snipped. Look at this video for a howto:
http://s3.amazonaws.com/screencasts.pragmaticstudio.com/017_custom_code_snippets.mov

A way to automatically organize #imports in Xcode

I love the "Organize Imports" command in Eclipse to implicitly add and remove classes imported into a source file (as in Java or ActionScript).
Is there a command in Xcode to update the #import directives at the top of.m Objective-C files based on the classes referenced within the file?
You can do this by creating an Automator action and use that in Xcode as well as everywhere in Mac OS X. To do that, do the following:
Start Automator -> New
Choose "Quick Action" (or "Service" on older MacOS/Automator versions)
add a "run shell script" action
use sort | uniq as the script and check the "output replaces selected text" checkbox
save and give it a name (e.g. "sort & unique")
check "Output replaces selected text"
After you saved it, you can just select your imports in Xcode, right click and choose your "sort & unique" action to organize your imports.
This is not as good as the organize import actions in Eclipse or IntelliJ, because it doesn't removes unused stuff etc. but it's better than nothing.
PS: Got that from WWDC 2012 Sessions - Session 402 Working Effeciently with Xcode (starting at 6:15)
EDIT
I started using AppCode, the Objective-C IDE from JetBrains, and it has features like "organise imports". You should check it out: http://www.jetbrains.com/objc/.
I'm resolving this as not currently a feature of Xcode :(
I've found Cedar Shortcuts to at least be usable. It's not as good as Eclipse's import feature (it doesn't organize imports), but it can keep you from having to go to the top of a class file and typing an import statement. With this plugin you just place the cursor on the class that needs imported and press Ctrl + Option + I. Here's the github project. https://github.com/cppforlife/CedarShortcuts
I made a small Xcode plugin to sort the headers and remove duplicates of the file with a shortcut, you can check it out! - https://github.com/insanoid/CleanHeaders-Xcode
AppCode from Jetbrains can do this.
Yup. Like in Eclipse, this would be an awesome feature since developing in XCode (Cocoa Touch) does require quite a bit of class imports which are not easy to remember and Android development in Eclipse sorts this out with a simple keystroke combination that saves so much time ! Hope there is a way to do this in XCode soon !
WordService (freeware) from Devon Technologies, provides a service that can be used in any Cocoa app that can (amongst others) sort lines.
Alternatively, you can use an Xcode Extension, such as Imp
Swiftlint has an opt-in rule which if opted, will automatically sort the imports alphabetically.
Add - sorted_imports to your .swiftlint.yml file under opt_in_rules.
Run swiftlint autocorrect terminal command on project root directory (same where swiftlint.yml is stored).

Resources