Formatting C++ Code With clang-format

The coding style formatting is based on clang-format. Mozilla coding style is (mostly) supported by clang-format.

Options are explicitly defined in clang-format itself. If the options are changed in clang upstream, this might caused some changes in the Firefox tree.

How to run clang-format from the tree:

We provide wrappers to clang-format:

$ ./mach clang-format

will run on a local diff. Might miss some reformatting (for example, when blocks are touched).

You can find the implementation of this command on dxr.

$ ./mach clang-format -p <path>

will run on a path (directory or file).

You can find the implementation of this command on dxr.

The -s option shows the local changes instead of applying them to the working directory. For example,

$ ./mach clang-format -p dom/presentation -s

will reformat dom/presentation and show the changes.

If clang-format isn’t installed, the binaries will be downloaded from taskcluster. We are building our own clang-format binaries.

Configuration of clang-format

By default, the configuration is done in the clang-format product itself.

When we change the configuration (incorrect configuration, new feature in clang, etc), we use local overrides.

Ignore list

We maintain a list of ignored directories and files which is used by mach (not a clang-format feature itself, this is managed by mach).

We offer the capability for developers to override the global configuration.

For example, for SpiderMonkey, the clang-format configuration is overridden locally.

Ignore section of code

clang-format offers the capability to ignore reformat on some sections of code.

For that, adding the following comments will disable the reformat:

// clang-format off
my code which should not be reformated
// clang-format on

You can find an example of code not formatted.

Editor Integrations

When working on C++ code in the tree, it is ideal if you configure your code editor to format code changes automatically using clang-format.  There are integration plugins available for various code editors:

Note that when using an editor integration, you should configure your editor to use a custom clang-format binary, and use the one that ./mach clang-format installs.  This binary is located in the .mozbuild/clang-tools/clang-tidy/bin directory under your home directory.

 

Document Tags and Contributors

Contributors to this page: Ehsan, sylvestre
Last updated by: Ehsan,