Search code examples
c++visual-studio-codeautoformat

Forbid an alignment of consecutive comments in VSCode auto formating for C++


VSCode auto formatting in C++ programs produces this code by aligning consecutive comments:

    if (true) { // if begin
                // if inner part
        int x = 3;

        int a = 1; // some inner calculations
    }              // if end
                   // some outer calculations
    int b = 1;

How can I forbid comment alignment to get the code bellow?

    if (true) { // if begin
        // if inner part
        int x = 3;
        int a = 1; // some inner calculations
    }// if end
    // some outer calculations
    int b = 1;

I can only prevent it by adding empty lines.


Solution

  • The Microsoft C/C++ extension for VS Code uses clang-format by default as the formatting tool. clang-tidy is a static analysis tool, and is also good to use in its own right, but it's not the tool that answers this question.

    clang-format style options: https://clang.llvm.org/docs/ClangFormatStyleOptions.html

    The option you want is AlignTrailingComments, you'll set it to false. If you just want to change some parameters, but otherwise be based on a style, dump that style using something like clang-format -style=LLVM --dump-config > .clang-format in the root of your project. That command assumes a POSIX or close-enough shell (bash, fish, zsh, etc.). It might work in Windows as well, I've just never tried it there.

    After dumping the config, keep the first two lines (Language, and uncomment BasedOnStyle) and then you can delete any option you don't want to change. Keep the options you want to change, change them, save, quit, etc. Change VS Code to look for the file style first by default (which I believe is the default), and you should be good to go.

    Here's a bare bones example of a .clang-format file as described above:

    ---
    Language:        Cpp
    BasedOnStyle:  LLVM
    AlignTrailingComments: true