About .clang-format config: IncludeCategories

41 Views Asked by At

I use .clang-format in my project to configure my coding style. Among them, I configured my header file collation using IncludeCategories. The specific configuration rules are as follows:

IncludeCategories:
  - Regex: '^"(?!3rd|vendor).*\.(h|hpp)"$'
    Priority: 1
    # This category matches project headers, such as "module.h"

  - Regex: '^"(3rd|vendor).*\.(h|hpp)"$'
    Priority: 2
    # This category matches third-party headers, such as "3rd/module.h" or "vendor/module.hpp"

  - Regex: '^<.*\.(h|hpp)>'
    Priority: 3
    # This category matches system headers, such as <sys/netport.h>

  - Regex: '^<[^.>]+>$'
    Priority: 4
    # This category matches standard library, such as <iostream>

I configured 4 rules, always saying that I want the project header files to be ranked at the top. The header files opened by 3rd or vendor are second.

Project structure:

.
├── CMakeLists.txt
├── .clang-format
├── include
│   ├── 3rd
│   │   └── constant.h
│   ├── sub
│   │   ├── sub.h
│   │   └── xx.hpp
│   └── work.h
└── src
    ├── main.cpp
    └── work.cpp

The effect I want:

// main.cpp
#include "sub/sub.h"
#include "work.h"

#include "3rd/util.h"

#include <sys/netport.h>

#include <iostream>

int main() {
  return 0;
}

The actual result:

// main.cpp
#include "3rd/util.h"

#include <sys/netport.h>

#include <iostream>

#include "sub/sub.h" // <<-- should be at the top
#include "work.h"    // <<-- should be at the top

int main() {
  return 0;
}

How should I modify it if I want to get my effect?

1

There are 1 best solutions below

0
mr NAE On

Your IncludeCategories doesn't contain any rules for #include ".*"

So, add Regex: '".*"' with Priority: 1 after all less common Regex's

IncludeCategories:
  - Regex: '^"(?!3rd|vendor).*\.(h|hpp)"$'
    Priority: 2

  - Regex: '^"(3rd|vendor).*\.(h|hpp)"$'
    Priority: 3

  - Regex: '".*"'
    Priority: 1

  - Regex: '^<.*\.(h|hpp)>'
    Priority: 4

  - Regex: '^<[^.>]+>$'
    Priority: 5