Can you customize code folding?

There are three ways to achieve customized folding in a VSCode extension.

  1. You can define regex as folding markers in a [language-name].configuration.json file. (However, we don't have much customization with this approach)

{
  "folding": {
    "markers": {
      "start": "starting regex",
      "end": "ending regex"
    }
  }
}
  1. You can define a FoldingRangeProvider from within the extension as described in this answer. FoldingRange in vscode package supports folding customization with startLine, endLine, and foldingKind.

  2. You can use Language Server support with textDocument/foldingRange. FoldingRange in the vscode-languageserver-protocol supports folding customization with startLine, endLine, startCharacter, endCharacter, and foldingKind.

Check this for more details.


FoldingRangeProvider can be used if you are looking to contribute custom folding logic in an extension.

Be sure to set your VS Code version in engines in package.json to 1.23, the version that introduced this.

Here's how you'd use one.

export function activate(context: ExtensionContext) {
    languages.registerFoldingRangeProvider({ scheme: 'file', language: 'markdown' }, new MyFoldingRangeProvider());
}

class MyFoldingRangeProvider implements FoldingRangeProvider {
    provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): FoldingRange[] {
        return detectRanges().map(({ lineStart, lineEnd }) => new FoldingRange(lineStart, lineEnd));
    }
}