Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control clang-format indentation of chained method calls?

I want the results to look like this:

auto foo = FooBuilder()
    .WithSomething()
    .WithSomethingElse()
    .Build();

but instead clang-format formats it like this:

auto foo = FooBuilder()
               .WithSomething()
               .WithSomethingElse()
               .Build();

I want the chained calls to be indented relative to the beginning of the preceding line, not relative to the FooBuilder() call. I don't see anything in the clang-format options that control this. Setting ContinuationIndentWidth does not help. Any ideas?

like image 530
Franz Amador Avatar asked Sep 29 '16 21:09

Franz Amador


People also ask

How do I change my 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.

Where does clang-format look for clang-format?

Standalone Tool. 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.

Where do I put the clang file?

clang-format file, we need to place it in the project folder or in any parent folder of the file you want to format. clang-format.exe searches for the config file automatically starting with the folder where the file you want to format is located, all the way to the topmost directory.


1 Answers

Unfortunately, this appears to be not possible. The only option I have found that affects this at all is ContinuationIndentWidth, which, as you said, doesn't do what you want.

What I personally would do is use the following regex to find chained method calls that have been broken up:

\)\s+\.

It will match a closing parenthesis, 1 or more whitespace characters (but not 0), and a period. You probably don't have too many instances of this, so you could just fix them manually, and then disable clang-format for those lines so it leaves it alone in the future:

// clang-format off

auto friggin_cool_object = SuperCoolBuilder().do_what_i_want()
    .figure()
    .out()
    .the()
    .params()
    .too();

// clang-format on
like image 178
Lysol Avatar answered Oct 12 '22 23:10

Lysol