Andrea Campi
Andrea Campi

Reputation: 456

How to get clang-format to align chained method calls

I've joined an existing project and I'm the first team member to use clang-format. The existing style mostly matches except for a couple of annoying differences. Here's one (the other one being here):

  folly::dynamic makeRequest(const string &response) {
    return folly::dynamic::object()
      ("log_type", "FOO")
      ("src_id", "42")
      ("dst_id", "666")
      ("success", true);
  }

clang-format insists on formatting it like this:

  folly::dynamic makeRequest(const string &token_response) {
    // using longer variable names to highlight using up the whole line lenght
    return folly::dynamic::object()("log_type", "FOO")(
        "src_id", somethingId)("dst_id", whateverId)("success",
                                                     sucess);
  }

In the former style I don't feel strongly for how continuation lines are indented, as long as we get one method invocation per line. Is that possible?

Upvotes: 6

Views: 1792

Answers (2)

Chris Frank
Chris Frank

Reputation: 4452

Another approach that I have used myself is to turn off clang-format for the specific block of code.

// clang-format off
return folly::dynamic::object()
    ("log_type", "FOO")
    ("src_id", "42")
    ("dst_id", "666")
    ("success", true)
    ;
// clang-format on

This might not be optimal if you have more complicated logic inside the chained method params (since you will want that logic to be formatted), but if you just have a tuple like this it can be cleaner than adding empty comments.

Both ways you are bypassing clang-format, but this way is cleaner (imo) and signifies your intentions more clearly to future developers.

Upvotes: 3

Franz Amador
Franz Amador

Reputation: 661

Not the best possible solution, but you can force line breaks by putting "//" after each line:

return folly::dynamic::object() //
  ("log_type", "FOO") //
  ("src_id", "42") //
  ("dst_id", "666") //
  ("success", true);

Upvotes: 3

Related Questions