9
votes

Is there a way to get clang-format to correctly format a CMake file?

I have a .clang-format file with Language: Cpp and BasedOnStyle: Google. No other language is specified.

Ideally, I would like to customize the style, however the biggest problem right now is, that clang-format indents many lines. The longer the file, the more levels of indentation I get.

Questions:

  1. Is there a way to get clang-format to recognize a CMakeLists.txt as a different language than Cpp?
  2. Does clang-format have the capabilities for me to add rules for the CMake language?
  3. Does an alternative to clang-format exist in this context?

Example

Input

cmake_minimum_required (VERSION 3.2)
project(HELLO)

add_executable (helloDemo demo.cxx demo_b.cxx)
add_executable (goodByeDemo goodbye.cxx goodbye_b.cxx)

Actual Output

cmake_minimum_required(VERSION 3.2) project(HELLO)

    add_executable(helloDemo demo.cxx demo_b.cxx)
        add_executable(goodByeDemo goodbye.cxx goodbye_b.cxx)

Expected output: Same as input. Or maybe no space between command and parenthesis.

1
Probably not. It'll parse the file as a cpp file. The indentation is probably because it expects that statements will be divided by semicolons, so it probably interprets everything as a big long line and it indents it to show you that is a continued statement. You can try setting the switch AlignAfterOpenBracket to false. I'm not sure this is the one influencing the indenting but you'll still have problems with ifs and fors, because they don't follow a C like syntax. clang.llvm.org/docs/ClangFormatStyleOptions.htmlCristian Bidea
So, clang-format v. 8.0.1 will do stuff to a CMakeLists.txt file. It seems slightly smart, in that it will take a comment and remove the space after the #. Is there any way to control what's done with these files?All the Rage

1 Answers

4
votes
  1. A related question: Is there any utility that can reformat a cmake file

  2. Clang-format cannot do this, but an alternative exists now: https://github.com/cheshirekow/cmake_format

Example -- Bad input:

cmake_minimum_required(VERSION 3.2) project(HELLO)

    add_executable(helloDemo demo.cxx demo_b.cxx)
        add_executable(goodByeDemo goodbye.cxx goodbye_b.cxx)

Command:

pip install --user cmake_format  # Or sudo to install system-wide
cmake-format -i CMakeLists.txt

Resulting output:

cmake_minimum_required(VERSION 3.2)
project(HELLO)

add_executable(helloDemo demo.cxx demo_b.cxx)
add_executable(goodByeDemo goodbye.cxx goodbye_b.cxx)