ClangFormat automatically formats code according to a given set of code formatting rules.
Xcode 8 removed the ability to add third-party plugins, but added editor extensions. There's at least one plugin available to add this functionality, but Xcode 8 is still in beta and we haven't tested that extension yet, so proceed with caution.
The easiest way to use ClangFormat is to install the Xcode plugin. This can be installed through Alcatraz.
This plugin adds a Clang Format submenu under Edit, from which you can automatically format the current file, files selected in the sidebar, and so on. It also offers multiple formatting options, including the LLVM, Google, and Mozilla formatting standards.
To use the plugin:
- Drop our
.clang-formatfile (which defines our formatting rules) into the project directory, so that it's alongside the
- Back in Xcode, under Edit > Clang Format, choose File. This tells the plugin to use that
- Optionally choose Edit > Clang Format > Enable Format on Save. With this enabled, the plugin will automatically format the current file whenever you hit Cmd+S (which isn't necessary in Xcode, but it's muscle memory for a lot of people). Without this option enabled, you'll need to manually choose one of the Format items under Edit > Clang Format to take advantage of this automatic formatting.
.clang-format file is based on the LLVM coding standard, with some tweaks. This could probably use further customization, but it's a good start.
- ClangFormat won't fix everything. In particular, it won't add a newline in some conditions (above
#pragmaand categories, in particular), and it will happily adjust the indenting on a single-line
ifstatement without wrapping it in braces. As such, it's as good idea to use this in conjunction with Objective-Clean. Think of it as a helper that will catch most of the things that Objective-Clean will complain about.
- Remember: Like Objective-Clean, this only covers a subset of our code standards. You are still responsible for following any standards not covered.