Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 812
Alaya Avatar asked Jul 11 '15 05:07

Alaya


People also ask

Does clang format work for C?

clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

How do I apply a clang file format?

You can install clang-format and git-clang-format via npm install -g clang-format . To automatically format a file according to Electron C++ code style, run clang-format -i path/to/electron/file.cc . It should work on macOS/Linux/Windows.

How do you change clang format?

clang-format supports two ways to provide custom style options: directly specify style configuration in the -style= command line option or use -style=file and put style configuration in the . clang-format or _clang-format file in the project directory.

How do I use clang format in Sublime Text?

Set the path to the clang-format binaries. You can do this from within Sublime Text by choosing Clang Format - Set Path from the command palette. Hint: the path should look something like this [path/to/clang]/clang/bin/clang-format . If clang-format is in your system path, you shouldn't need to do anything.


2 Answers

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
like image 111
Medicine Yeh Avatar answered Oct 21 '22 14:10

Medicine Yeh


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.

like image 3
Mingye Wang Avatar answered Oct 21 '22 16:10

Mingye Wang