Using Clang-format in Xcode

In Xcode, we can using control+I to format the code. Usually, it performs well for Swift. But sometimes, we will get a terrible result for Objective-C or C++ code.
Unlike other IDEs, Visual Studio Code or Android Studio, Xcode provides less configuration for code formatting and doesn’t support any code formatting plugins.

In this case, we can use clang-format to format the code. clang-format is a tool to format C/C++/Obj-C code. It cannot be directly used in Xcode, but we can use Mac Automator to create a service to format the code.

Install clang-format

In MacOS, we can install it via Homebrew.

1
brew install clang-format

And then, you can check the version of clang-format by running:

1
2
clang-format --version
#=> clang-format version 18.1.8

Config clang-format

Aa a wildly used tool, clang-format provides a lot of configuration options. You can create a .clang-format file in your project root directory to configure the code formatting rules or use the default style.

I usually create a .clang-format file in my local user directory vi ~/.clang-format as a global configuration file.

The detailed configuration options you can query in official documents. You can base on a popular default style like LLVM, Google, or Chromium and override some rules to your liking.

You can create a example C/C++ file containing common code snippets and run clang-format --style=file:/Users/silas/.clang-format -i example.cpp to check the result.

Migrate to Xcode

Xcode doesn’t provide a backdoor for us to use clang-format directly. But we can use Mac Automator to create a service to format the code.

  1. Open Automator, create a new Quick Action

  1. Write a shell script with following content, sure select the Output replace text checkbox.

1
2
export PATH="/opt/homebrew/bin:$PATH"
clang-format --style=file:/Users/silas/.clang-format
  1. Bind shortcuts.

After creating the service, you can now select some code in your Xcode, and click the Menu Xcode -> Services -> clang-format to format the selected code.

Every formatting-code does above operations is a little bit tedious. So we can bind a shortcut for it.
Setting up a shortcut for it in System Preferences -> Keyboard -> Keyboard Shortcuts -> App Shortcuts.

Then come back to Xcode, select some code, and press the shortcut command-control-I you just set, you will see the code is formatted.

Clang-format Tools

clang-format-configurator