The command line tool clang-format allows to apply a configurable format to c++ sources. While being supported officially by Visual Studio and Visual Studio Code, Xcode on macOS has no official support.
As far as I know, existing 3rd party Xcode extensions are either broken with the latest Xcode versions or ship with their own (and outdated) versions of clang-format. To get consistent results, the same clang-format version needs to be used everywhere.
I was looking for a way to use an up-to-date version of clang-format (installed and updated using homebrew)
My solution is to use the macOS built-in Automator. It can send the currently selected text through a shell script:
- Install clang-format (version >= 14) using homebrew.
- Open Automator.app
- Create a new "quick action"
- Copy/paste the following script and replace the [CONFIG_FILE_PATH] placeholder with the correct path to your clang-format config file.
# requires clang-format v14 or better! /opt/homebrew/bin/clang-format --style=file:[CONFIG_FILE_PATH]/.clang-format
- Configure the Automator action:
- Save the "Quick Action" with a descriptive name.
- It now shows up in the "Services" context menu of selected text in the target applications.
- Open System Preferences and navigate to Keyboard/Shortcuts.
- Under the "Text" category, the chosen name should show up and a keyboard shortcut can be assigned.
Now in Xcode (or any other C++ source editor), a piece of code can be selected and the keyboard shortcut will process it using clang-format. Usually, I do a select-all/format combo to format entire files.
When working with large legacy codebases I like to have the option (using manual selection) to format just the new code to avoid getting those huge and confusing reformat git diffs.