How to make Vim indent C++11 lambdas correctly?

Posted on In QA

Vim seems not indent C++11 lambas very well. How to make Vim indent C++11 lambdas correctly?

For this following program, Vim indents it as

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main ()
{
  std::vector<std::string> strs({"one", "two"});
  std::vector<std::string> newstrs;

  std::transform(strs.begin(), strs.end(), std::back_inserter(newstrs), [](const std::string& s) -> std::string {
      if (s == "one") {
      return "1";
      } else if (s == "two") {
      return "2";
      } else {
      return s;
      }
      });

  return 0;
}

The C++ lambda is indented incorrectly by Vim. The lambda function should be indented like

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main ()
{
  std::vector<std::string> strs({"one", "two"});
  std::vector<std::string> newstrs;

  std::transform(strs.begin(), strs.end(), std::back_inserter(newstrs), [](const std::string& s) -> std::string {
    if (s == "one") {
      return "1";
    } else if (s == "two") {
      return "2";
    } else {
      return s;
    }
  });

  return 0;
}

You may add these lines to your vimrc for C/C++ to indent lambdas correctly as you listed above

setlocal cindent
" handle lambda correctly
setlocal cino=j1,(0,ws,Ws

The key is setting cino (cinoption) to be j1,(0,ws,Ws. jN is new in Vim 7.4 for “indent Java anonymous classes correctly” which improves C/C++ lambda indenting too.

Check my vimrc as an example.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *