How to make VSCode indent an if statement without brackets?

Viewed 545

I'd like for VSCode to indent automatically indent when I create a newline in the following case:

if(statement)
    func();

The default functionality does the following when hitting newline:

if(statement)
func();

This is a longstanding issue in VSCode: https://github.com/microsoft/vscode/issues/43244

I'd appreciate any kind of hack/extension that can accomplish this behavior. There are other instances of indentation getting mangled in the github issue link, but I only really care about this simple case.

1 Answers

Figured out how to do this without installing an extension. There may be a better way that can be done in settings.json but I couldn't find it. You can modify a languages configuration directly from the source, which for me was C:\Program Files\Microsoft VS Code\resources\app\extensions\cpp\language-configuration.json. There is a guide for these files settings. I added the following to my c++ language configuration:

"onEnterRules": [
        {
            "beforeText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
            "action": {
                "indent": "indent"
            }
        },
        {
            "beforeText": "(?=)",
            "previousLineText": "^\\s*(?:if|while)\\(.*\\)\\s*$",
            "action": {
                "indent": "outdent"
            }
        }
    ]

This works, but unfortunately the official c++ vscode extension C/C++ for Visual Studio Code breaks it for some reason.

Below was my initial method of doing this, which breaks too many things to be useful.

"indentationRules": {
        "increaseIndentPattern": "^\\s*if\\(.*\\)\\s*$",
        "decreaseIndentPattern": "(?!)"
    }

The field decreaseIndentPattern must be set (here the regex will never capture anything), otherwise it ignores the indentationRules field (I guess they never tested whether just one would be set?) Note that these edits need to be done with administrative privleges, and I found VSCode pretty convenient for making them. Also these changes do not take effect until VSCode is closed.

So as it turns out I've run into the same issues mentioned in this PR: https://github.com/microsoft/vscode/pull/115454. This fix breaks too much other vscode indentation behavior, such as deindenting after the first properly indented line in if statements.

Related