Clang-Format

Source code formatter

clang-format is a source code formatter – it changes source files according to a config file.

In NeoMutt we use it to:

  • Place {}s in the right place
  • Adjust the whitespace: indent and around operators
  • Sort the #includes (see the weighting strategy)
  • Align a pointer * to the variable, not the type
  • … and much more

Unlike many similar tools, it really understands the code it’s transforming. It uses clang to create an AST for the code.

NeoMutt’s config file ships with the code.

The config file looks like this:

Language: Cpp

TabWidth:          8
UseTab:            Never
IndentWidth:       2
ColumnLimit:       80
BreakBeforeBraces: Allman

Clang has documentation for all of the options.

Running it is as simple as:

clang-format -i source.c
  • As part of the release process, clang-format is run on all the ‘c’ source.
  • The header files are tidied by hand to preserve the whitespace layout.
  • Some small parts of the code are protected from change with these comment blocks
// clang-format off
code here will not be formatted
// clang-format on

To run clang-format on all the code that you’ve changed, before committing, you could run:

git diff HEAD --name-only -- '*.c' | xargs --no-run-if-empty clang-format -i

Search by Algolia