Use clang-format for formatting code fragments

Hello.
I have a large file, that contains different text and c++ code fragments.
Something like this:

different text
cpp-begin
if(a>0){b=1};
cpp-end
Text again

I need to format only c++ code between cpp-begin and cpp-end tags.

but after running

clang-format-12 -i -lines 3:3 file.cpp

i get

different text cpp - begin if (a > 0){b = 1};
cpp-end
Text again       

what is the right way of formatting only code fragments?

You could try:
https://clang.llvm.org/docs/ClangFormatStyleOptions.html#disabling-formatting-on-a-piece-of-code

I’ve already tryed this.

// clang-format on
for(const auto& element: elements){if(element > 0){element++;}}
// clang-format off
some text
more text
// clang-format on
for(const auto& element: elements){if(element > 0){element++;}}
// clang-format off
some text

and after runnig clang-format I received

// clang-format on
for(const auto& element: elements)
{
    if(element > 0)
    {
        element++;
    }
}
// clang-format off
some text
    // clang-format on                 <---------------
    for(const auto& element: elements) <---------------
{
    if(element > 0)
    {
        element++;
    }
}
// clang-format off
some text   

lines after text were shifted to the right.
I can resolve this with adding “;” before “// clang-format on”, so it will be:

;// clang-format on

but I’m searching better variant.

This seems like a bug to me, at the very least it’s surprising. Perhaps something is dropping a newline or return character.

Worth filing an issue Issues · llvm/llvm-project · GitHub to see what the maintainers think of it.

maybe I had bug in my code…
so if i change it to:

different text
cpp-begin;
if(int a>0){int b=1;};
cpp-end;
Text again   

i get

different text
cpp-begin;
if (int a > 0) {
    int b = 1;
};
cpp-end;
Text again  

so, its fine.
But if I use

different text
cpp-begin
if(int a>0){int b=1;};
cpp-end
Text again

I get

different text cpp - begin if (int a > 0)
{
    int b = 1;
};
cpp-end
Text again    

and this is not good.
Is there any way to format only code fragment, withou taking into account previous strings?