Search code examples
c++clang-format

Per-file (ideally per-section) clang-format style override


I would like to mark part of a file with something like:

// clang-format -style="{ SomeSetting: NewValue }"

...

// clang-format -style="{ SomeSetting: OldValue }"

that would override the global settings in the root .clang-format file. If not possible, specific formatting a single file would also do as I could work around by isolating the section that requires the specific formatting in its own file. I have a git pre-commit hook that does the formatting on staged files as well as IDE plugins that run clang-format on their own, but I don't want to have to mark specific files and specific settings in either of these places.

The best I can do now is to format the file with the custom settings, put // clang-format off, // clang-format on guards around the section and revert the settings back, which is not sustainable in the long term. Is there a better solution?


Solution

  • What you want is currently (clang 13) not possible, but is certainly a nice feature to add to clang-format.

    (Update: Still not possible in clang 20)

    Current documentation on Clang-Format Style Options states nothing about entering style options in code. As you said, the closest we can get is using // clang-format off and // clang-format on hints.