Skip to content

Sharing my C/C++ folding rules #23

@HolyBlackCat

Description

@HolyBlackCat

Hello! Not sure if this is the right place to do it, but I just wanted to share the C/C++ folding rules ended up using.

What is folded:

  • {...}, (...), [...]
  • block comments
  • preprocessor conditionals
  • raw strings: R"(...)"

Folding doesn't happen inside of:

  • line and block comments
  • string and character literals
  • raw strings

Known issues that I don't know how to fix:

  • Line continuation (\ at the end of line) is not handled correctly in string and character literals, line comments, and everywhere else.
  • Unbalanced brackets after #define should be ignored, but they aren't.

Config:

"cpp": [
    // Last version can be found at:  https://github.com/HolyBlackCat/vscode-settings/blob/master/settings.json
    { // `//...` (not actually folded, but forces contents to be ignored)
        "beginRegex": "(?!)",
        "endRegex": "\\/\\/.*",
    },
    { // `/*...*/`
        "begin": "/*",
        "end": "*/",
        "nested": false,
    },
    { // R"(...)" (C++ only)
        "beginRegex": "\\b(?:L|u8|u|U|)R\"([^\\s\\(\\)\\\\]{0,16})\\(",
        "endRegex": "\\)\\1\"",
        "nested": false,
        "foldLastLine": false,
    },
    { // "..." (not actually folded, but forces contents to be ignored)
        "beginRegex": "(?!)",
        "endRegex": "\"(?:[^\"\\\\]|\\\\.)*\"",
    },
    { // '...' (not actually folded, but forces contents to be ignored)
        "beginRegex": "(?!)",
        "endRegex": "'(?:[^'\\\\]|\\\\.)*'",
    },
    { // {...}
        "begin": "{",
        "end": "}",
        "foldLastLine": false,
    },
    { // (...)
        "begin": "(",
        "end": ")",
        "foldLastLine": false,
    },
    { // [...]
        "begin": "[",
        "end": "]",
        "foldLastLine": false,
    },
    { // Preprocessor conditionals
        "beginRegex": "^\\s*#\\s*if(?:(?:n)?def)?\\b", // "#if", "#ifdef", "#ifndef".
        "middleRegex": "^\\s*#\\s*el(?:se|if)\\b", // "#else", "#elif"
        "endRegex": "^\\s*#\\s*endif\\b", // "#endif"
    },
],

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions