Update 27th February 2017: It's taken me a while to say this, but unfortunately due to changes with plugin support, this no longer works in Xcode since version 8.0. I've kept this article up though for posterity and the small minority of you using Xcode 7.x.
I recently started chipping in to a Swift project that used 2 space indents. For those of you who don't work with Swift or are new to it, most Swift developers use Xcode and leave their indentation settings to Xcode's default: 4 spaces. I didn't want to inflict 2 space indentation on all of my projects, or to keep changing this setting back and forth. Therefore, the backspace button became my best friend for this particular project, but it was still a pain.
Completely by chance, I found a solution to this problem that meant I could stick to this project's convention while not faffing around with either backspaces or constantly changing my Xcode settings. It's a small dotfile called .editorconfig
.
So let's jump right in - in the above example, create a file in the project root called .editorconfig
that looks like this:
[*{.swift,.h,.m}]
indent_style = space
indent_size = 2
Now Xcode doesn't take advantage of .editorconfig
files out of the box: for this you need the EditorConfig plugin, which is also available via Alcatraz (my recommended way of installing plugins for Xcode). Once the plugin is installed, restart Xcode, open your project and your indentation settings are now applied!
There is more to EditorConfig than just per-project settings. I admit I don't usually open up non iOS code files with Xcode: for this, I prefer to use Atom or TextMate for the job. However, suppose I take a project where I'm using my beloved 4 space indentation, wouldn't it be great if I can open up a file written in a Ruby DSL (such as a Podfile, Fastfile, etc.) and Xcode automatically uses 2 space indentation for these files, as is universally conventional in Ruby? Well, this is entirely possible with EditorConfig:
[*]
indent_style = space
[*{.swift,.h,.m}]
indent_size = 4
[{Podfile,Fastfile,Matchfile}]
indent_size = 2
Finally, Xcode is far from the only IDE or text editor that can take advantage of .editorconfig
. There are plugins for a wide variety of editors including Atom, TextMate, Sublime and even Notepad++! Some plugins support more of EditorConfig's features than others, but all are open source so you can chip in.
I hope you found this brief primer on EditorConfig useful - it certainly is something I'll add to all of my projects from now on. You can find out much more about EditorConfig from the official website: http://editorconfig.org.