19

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;
}
wovano
  • 4,543
  • 5
  • 22
  • 49
Alaya
  • 3,287
  • 4
  • 27
  • 39
  • Maybe because traditionally preprocessor directives *had* to be starting on the first column of the line? – Some programmer dude Jul 11 '15 at 08:40
  • 2
    [Relevant bug report](https://llvm.org/bugs/show_bug.cgi?id=17362). – rettichschnidi Jun 18 '16 at 23:07
  • Did you find any solution (otherwise then reparsing)? – Tom de Geus Feb 05 '20 at 08:29
  • 2
    Update as of Jan 2021 -- Based on my research, it seems that clang-format 12 plans to introduce a field called `IndentPragmas` which addresses this issue. However, in the `clang-format` binary (version 12) that I build, this option does not seem implemented. Hope this provides some updates. – aafulei Jan 19 '21 at 04:07
  • Does this answer your question? [Indenting preprocessor directives with clang-format](https://stackoverflow.com/questions/24476165/indenting-preprocessor-directives-with-clang-format) – wovano May 31 '23 at 09:52

2 Answers2

5

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
Medicine Yeh
  • 101
  • 2
  • 4
4

It's a bit even later, but clang-format is finally planning to make any workarounds unnecessary. https://reviews.llvm.org/D92753 introduces the boolean IndentPragmas switch to allow for indenting pragmas the same as its surrounding code.

Mingye Wang
  • 1,107
  • 9
  • 32