How could I indent C++ pragma using clang-format?

2019-04-20 09:20发布

I am using vim-autoformat, which uses clang-format as external formatter.

It seems that clang-format won't indent the C++ #pragma. For example:

#include <omp.h>
#include <cstdio>
int main()
{
#pragma omp parallel for
    for (int i = 0; i < 10; ++i)
    {
        puts("demo");
    }
    return 0;
}

I would like to have it formatted into :

#include <omp.h>
#include <cstdio>
int main()
{
    #pragma omp parallel for
    for (int i = 0; i < 10; ++i)
    {
        puts("demo");
    }
    return 0;
}

I checked clangformat, but didn't find which option I could use.

1条回答
手持菜刀,她持情操
2楼-- · 2019-04-20 09:57

It's been late but this is the solution you are looking for. It formats the pragma along with the code block.

https://github.com/MedicineYeh/p-clang-format

The main concept is replacing the string so that the formatter uses the "correct" rules on these pragmas. The motivative example is as following.

# Replace "#pragma omp" by "//#pragma omp"
sed -i 's/#pragma omp/\/\/#pragma omp/g' ./main.c
# Do format
clang-format ./main.c
# Replace "// *#pragma omp" by "#pragma omp"
sed -i 's/\/\/ *#pragma omp/#pragma omp/g' ./main.c
查看更多
登录 后发表回答