VS Code: How to Collapse/Expand Blocks of Code

Last updated on June 11, 2022 A Goodman Loading... Post a comment

If you’re using VS Code (Visual Studio Code) and your document is very long and has a lot of code blocks, you may want to fold some of them to make your viewport neater. A folded block will show only the first line of that block, like this:

This concise article shows you a couple of different ways to collapse and expand blocks of code in VS Code.

Note: The fold/unfold state will be preserved when you shut down or restart the editor

Using Your Mouse

Hover your mouse over the area between line numbers and line start and you’ll see some folding icon buttons as follows:

If the folding icon is a chevron down, it’s used to fold the associated region of code. On the other hand, a chevron right icon is for unfolding the associated region of code. A quick demo is worth more than a thousand words:

Note: If you’re using Safari, this demo video might not work nicely or not start at all. Please use Chrome, Edge, Firefox, or another web browser instead.

Using Shortcuts

If there is a reason that makes you don’t like hitting chevron icons, then you can use shortcuts to get things done. Use your mouse or trackpad to select a block of code you want to collapse/expand then:

  • If you’re using a Mac:
    • Fold: Command + Option + [
    • Unfold: Command + Option + ]
  • If you’re on a Windows computer:
    • Fold: Ctrl + Shift + [
    • Unfold: Ctrl + Shift + ]

In case you want to collapse all code blocks in the current file:

  • If you’re on a Mac:
    • Fold all: Command + K then Command + 0 (the zero number key)
    • Unfold all: Command + K, then Command + J
  • If you’re using Windows:
    • Fold all: Ctrl + K then Ctrl + 0 (the zero number key)
    • Unfold all: Ctrl + K then Ctrl + J

Conclusion

You’ve learned how to fold and unfold sections of code in VS Code. These actions are simple and quick but can keep your code more organized and improve your working experience as well as productibility. If you’d like to explore more new and interesting stuff about VS Code, take a look at the following articles:

You can also check out our Visual Studio Code topic page for more tips and tricks. Happy coding.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles