Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code Folding Based on Brackets - Not Indentation

Hello Stackoverflow community,

This is my first post here. I am using VS Code and am currently looking for a way to enable method and function folding by default like the feature available in PHPStorm. I looked around here and found some posts showing that you can fold all of the code or indentation levels as described here: https://stackoverflow.com/a/30077543/10713286 However, I am looking for a way to fold functions and methods using matching brackets as the folding method rather than indentation or use of //#region and //#endregion. Ideally, this could be the default and I could unfold the code as needed. PHPStorm does this beautifully and leaves the documentation method and function comments unfolded as an option. I am thinking this may need to be done by writing an extension. I am having trouble finding a way to do this though. I pulled the VS Code git repo and ran some grep searches to find that the folding method (for php) is set in vscode/extensions/php/package.nls.json:3. There are #region and #endregion settings in vscode/extensions/php/snippets/php.snippets.json on lines 243 and 250. The problem is that the folding is set with regex and I can't find a way to match brackets using regex alone.

This is an important feature for me because I am learning a new code base and having function/method folding really improves readability of large files. I can quickly scan for what I need and expand as needed. VS Code tries to do this, but if there are any lines intentionally outdented in a function, to make a comment more obvious for example, VS Code stops folding there rather than going to the end of the function. Any help on this issue is greatly appreciated!!

tldr; I need to find a way to fold code based on matching brackets rather than indentation in VS Code.

like image 652
Tobin deKorne Avatar asked Oct 17 '22 10:10

Tobin deKorne


People also ask

How do you collapse brackets in VSCode?

Ctrl + K , Ctrl + 0 (zero) on Windows and Linux. ⌘ + K , ⌘ + 0 (zero) on macOS.


1 Answers

VS Code has two ways of handling folding for a language:

  • Indentation based (plus basic #region support). This works out of the box for many languages but is quite simple. It only looks at indentation to determine how code should be folded

  • Syntax aware code folding. This must be implemented per language. VS Code ships with syntax aware folding for javascript, typescript, html, css, json, and markdown. Support for other languages can be provided by extensions

I am not aware of any existing extensions that implement syntax aware folding for php. If you would like implement it yourself, take a look at the folding provider api

like image 67
Matt Bierner Avatar answered Oct 21 '22 04:10

Matt Bierner