How do I collapse sections of code in Visual Studio Code?
Asked Answered
H

27

1408

How do I fold or collapse sections of code in Visual Studio Code?

Is this feature supported?

Herminiahermione answered 6/5, 2015 at 4:50 Comment(0)
C
2367

Folding has been rolled out and is now implemented since Visual Studio Code version 0.10.11. There are these keyboard shortcuts available:

  • Fold folds the innermost uncollapsed region at the cursor:

    • Ctrl + Shift + [ on Windows and Linux
    • + + [ on macOS
  • Unfold unfolds the collapsed region at the cursor:

    • Ctrl + Shift + ] on Windows and Linux
    • + + ] on macOS
  • Fold All folds all regions in the editor:

    • Ctrl + K, Ctrl + 0 (zero) on Windows and Linux
    • + K, +0 (zero) on macOS
  • Unfold All unfolds all regions in the editor:

    • Ctrl + K, Ctrl + J on Windows and Linux
    • + K, + J on macOS

References: https://code.visualstudio.com/docs/getstarted/keybindings

Chopin answered 6/5, 2015 at 13:0 Comment(16)
@DouglasGaskell I made the same mistake. It is a zero not an o, Michael Fulton 's Fold Level answer made more sense to me.Henkel
Don't know if its a Code version issue, a Windows version issue, or something else, but on my PC it only works with Right-Ctrl. You may want to note that!Supertonic
Its basically Ctrl+K, Ctrl+[n] where n is the level number upto which you want to fold. Hence, if you are looking for an equivalent of Ctrl+M, Ctrl+O of VS(C#) on VSCode, it'll be Ctrl+K, Ctrl+3.Fuzz
VS Code (version 1.33.1) has an option to always show cold folding controls. Press CTRL + , to bring up Settings, enter folding in 'search settings' box and you'll see the Show Folding Controls option there.Uptrend
Is there a way to do it through the gui? I am going to forget this obcsure shortcut immediatelly.Durra
@Durra Press F1 and type Fold or UnfoldHabitforming
@Habitforming if I have to type a command (which I would have to remember) then that's not really a GUI operation, is it?Durra
@Durra It also shows you the currently assinged keybinding, if none is assigned, you can assign it yourself. Also, there might be an extension to add custom GUI buttonsHabitforming
I'd like to add that VS Code has a global boolean setting "Editor: Folding" that "controls whether the editor has code folding enabled". If these shortcuts don't work for you, this setting might be the reason (as it was for me).Winner
If you copy paste this Xml file gist with 434803 Raw lines https://gist.github.com/alemens/4b8f14c100785456cebdbadfde0532d9 into Visual Studio Code. And then you try to Fold All as explained above. You will see it will not fold all properly in fact from line 375190 the code result unfolded. Do you know why?Chokebore
thanks @AlexG, yes and with this method you can know what keys you could use, in my case was Ctrl + Shift + 'Bohemian
That's so primitive and not enough. How one is going to work with vast OpenAPI definitions?Phenolphthalein
Oh, it was not VSCode fault, it was "yours" guys @gavin and @Chopin :) You missed Ctrl-K Ctrl-] and Ctrl-K Ctrl-[ for recursive unfold/fold. Or maybe on the time of writing VSCode didn't support it and added it the later versions. TLDR: the answer needs an update!Phenolphthalein
@Durra Through the GUI, press the chevron or arrow when you hover over the line's gutter to collapse or expand a fold, respectively.Monoceros
I'm a psycho. I reversed this mapping in Keyboard shortcuts because "close bracket" goes with "close block", and "open bracket" goes with "open block".Insectivorous
It seems to me that you all understand the question wrong. Visual Studio has a function to collapse selection no matter where are curly braces or whatever else collapsable code placed. You just select whatever lines you want and collapse them. You don't have to add any code for that. Seems like vs code doesn't have that function. But it's really useful and some missing functions in vs code compared to vs are a pain.Harness
C
351

As of Visual Studio Code version 1.12.0, April 2017, see Basic Editing > Folding section in the docs.

The default keys are:

Fold All: CTRL+K, CTRL+0 (zero)

Fold Level [n]: CTRL+K, CTRL+[n]*

Unfold All: CTRL+K, CTRL+J

Fold Region: CTRL+K, CTRL+[

Unfold Region: CTRL+K, CTRL+]

*Fold Level: to fold all but the most outer classes, try CTRL+K, CTRL+1

Macs: use instead of CTRL (thanks Prajeet)

Collaborate answered 23/6, 2016 at 20:42 Comment(4)
Does it save and restore the state of folds between IDE start/shut down?Alrich
Some reason ctrl+k,ctrl+num only works on numbers above qwerty not on numpadHyperacidity
Fold to level [n] doesn't fold the section where the cursor is located. This always makes me think it didn't do what I expected. Is there an option to turn off this behavior?Giliane
ctrl+k kill lineHomecoming
B
195

Also see the ability to fold any arbitrary lines of code as of Insiders v1.70. That is any lines you select can be folded!

See https://mcmap.net/q/46280/-how-do-you-hide-arbitrary-section-of-code-in-vs-code for the command and demo.

Create Manual Folding Range from Selection
editor.createFoldingRangeFromSelection

This is bound to the above create command: Ctrl+K Ctrl+,

Remove Manual Folding Ranges
editor.removeManualFoldingRanges

This is bound to the above remove command: Ctrl+K Ctrl+.


Code folding by regions has arrived with v1.17. Folding by regions documentation. And v1.19 and 1.23.

[Generally you can add a space, for example // region and // endregion to //region and //endregion and it will also work.]

TypeScript/JavaScript: //#region and //#endregion or // #region and // #endregion
C#:                    #region and #endregion
C/C++:                 #pragma region and #pragma endregion
F#:                    //#region and //#endregion
PowerShell:            #region and #endregion
Python:                #region and #endregion
VB:                    #Region and #End Region
PHP:                   #region and #endregion
Bat:                   ::#region and ::#endregion or REM #region and REM #endregion
Markdown:              <!-- #region --> and <!-- #endregion -->
Golang                 //region and //endregion or //#region and //#endregion
Java                   //#region and //#endregion
CSS/SCSS/Less:         /* #region */ and /* #endregion */ or /*#region*/ and /*#endregion*/
SCSS/Less:             // #region and // #endregion
Go:                    // region, // endregion and // #region, // #endregion
shellscript:           # region and # endregion
Perl5                  #region and #endregion or =pod and =cut  
sql                    --#region and --#endregion

Important: If you don't see your language in the list ::

Each language also has snippets available for the markers. Type '#' and invoke code completion to see them. To have region markers configured for your language, contact the language extension provider.

So type # and then Ctrl+Space to see the region markers for any language.


Bise answered 6/10, 2017 at 2:9 Comment(7)
// region and // endregion are not working with VS Code version 1.22 (haven't tested versions below or above that though). But // #region and // #endregion works (note the '#' and space in both). This way ESLint (if you are using) won't show error if spaced-comment rule is on (i.e. not set to 'off' or 0).Mixup
In CSS, it's actually /* #region Foo Bar */ and /* #endregion */Insectivorous
@Mixup it depends on the file type (language). //region and //endregion are for JavaScript.Beggarweed
Works nicely in Docker .yaml files as well, if you install Microsoft's docker ext: marketplace.visualstudio.com/…Negligence
v1.41 : I tried XML and it worked! <!-- #region --> elements <!-- #endregion -->. It displays the text following the #region on the folded section. It properly folds from the current #region to the corresponding #endregion, even if there are others nested - just like parentheses in any equation. It remembers the fold setting for nested regions. Ctrl+k+Ctrl+[ and Ctrl+k+Ctrl+] close/open the folds correctly at the cursor. (which seems a little backwards to me, but whatevah) Great stuff!Sung
Maybe I am lazy, but is there any way to enclose the selected lines with region/endregion with a short key or something, instead of typing those at the start and end?Keystroke
@Negligence can you post a sample of #region working in Dockerfile? ty.Dumont
H
97

This feature is available in the standard build now. To make the collapse/expand controls appears, you need to mouse over the area just to the right of the line numbers as shown in this screenshot:

Enter image description here

Hartsock answered 8/9, 2016 at 17:17 Comment(3)
The question is, how to collapse all sections same time , not one by one. Is there a way to do it without shortcuts?Bend
for that you must use shortcutsHartsock
i would love to collapse large code blocks from end of block. some of my code blocks have hundreds of lines, and to collapse them, i first have to scroll upChrissie
N
75

ctrl + k + 0 : Fold all levels (namespace , class , method , block)

ctrl + k + 1 : namspace

ctrl + k + 2 : class

ctrl + k + 3 : methods

ctrl + k + 4 : blocks

ctrl + k + [ or ] : current cursor block

ctrl + k + j : UnFold

Nealy answered 13/2, 2019 at 9:18 Comment(3)
It's actually pairs of keypress combinations, not a single combination. For example: CTRL + K, CTRL + 0 (not CTRL + K + 0). The convention when depicting a sequence of keypress combinations is to show keys pressed together with plus, then sequence combinations with commas.Monoceros
Those commands work as described.Business
Those only work if you have namespace at level 1, class at 2, methods at 3, etc … it folds by indentation level, and not by 'type'Archway
A
73

You should add user settings:

{
    "editor.showFoldingControls": "always",
    "editor.folding": true,
    "editor.foldingStrategy": "indentation", 
}
Audreaaudres answered 11/4, 2018 at 14:4 Comment(2)
"editor.foldingStrategy" was by far the most helpful tip for me. I am editing Liquid code (Shopify) and was not able to fold my code. Once I switched from 'auto' to 'indentation' VS Code looked at the indentation not the specific language I was using, very helpful, thanksCoons
This has the added benefit of encouraging devs to observe tidy code practices! Dirty code? You'll have to live in your filth, my friendFranky
A
37

The default shortcut for collapse/extend are:

Ctrl + Shift + [ : "Fold"

Ctrl + Shift + Alt + [ : "Fold all"

Ctrl + Shift + ] : "Unfold"

Ctrl + Shift + Alt + ] : "Unfold all"

Or go to keybindings.json and change as you wish.

For example:

{
    "key": "cmd+k cmd+m",
    "command": "editor.foldAll",
    "when": "editorFocus"
},
{
    "key": "cmd+m cmd+k",
    "command": "editor.unfoldAll",
    "when": "editorFocus"
},
Antibes answered 29/3, 2016 at 10:28 Comment(5)
is this limited to some languages? doesn't work for me on OSX/typescript.Mentally
Please review this: ctrl+shift+alt+[ "Unfold all"You wrote [ instead of ]. Correct me if I am wrong.Pecan
@Mentally it doesn't work for me in python/linux either. Ctrl+K, Ctrl+0 (zero) and Ctrl+K, Ctrl+J do work though as per the accepted answerTorpedo
For non-US keyboards [ and ] are at the left of the backspace key (🔙).Ba
@Ba thanks for this. perhaps MS should change their keybinding cheatsheet e.g. code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdfEhling
C
35

If none of the shortcuts are working (like for me), as a workaround you can also open the command palette (Ctrl + 3 or View -> Command Palette...) and type in fold all:

enter image description here

Cohe answered 8/6, 2018 at 11:38 Comment(2)
I think I figured out what happens... it folds the block only if there is the [+] available, in python for example it does not fold the following: github.com/heldersepu/GMapCatcher/blob/master/gmapcatcher/…Middaugh
@HelderSepulveda Well, it supposedly folds block comments, but python doesn't have those. The code you linked uses multiple single line comments.Cohe
F
14

Collapsing is now supported in release 1.0:

Source Code Folding Shortcuts

There are new folding actions to collapse source code regions based on their folding level.

There are actions to fold level 1 (Ctrl+K Ctrl+1) to level 5 (Ctrl+K Ctrl+5). To unfold, use Unfold All (Ctrl+Shift+Alt+]).

The level folding actions do not apply to region containing the current cursor.

I had a problem finding the ] button on my keyboard (Norwegian layout), and in my case it was the Å button. (Or two buttons left and one down starting from the backspace button.)

Feather answered 15/4, 2016 at 7:21 Comment(0)
I
14

With JavaScript:

//#region REGION_NAME
   ...code here
//#endregion
Idiographic answered 19/1, 2018 at 5:13 Comment(0)
C
14

This is the latest built-in(default) keyboard shortcuts for folding and unfolding the code

vscode Keyboard shortcut

enter image description here

Ctrl+Shift+[ Fold (collapse) region
Ctrl+Shift+] Unfold (uncollapse) region
Ctrl+K Ctrl+[ Fold (collapse) all subregions
Ctrl+K Ctrl+] Unfold (uncollapse) all subregions
Ctrl+K Ctrl+0 Fold (collapse) all regions
Ctrl+K Ctrl+J Unfold (uncollapse) all

Nb: But in some cases, your vs code extension or user will alter the keyboard binding(shortcut). So best option that Checks like this

  1. view->command palette OR cntrl+shift+p
  2. type "fold" .It will suggest the fold and unfold and there shortcut. You can type that shortcut instead of command-palette

enter image description here

eg:

Fold All

enter image description here

UnFold All

enter image description here

Creolacreole answered 9/2, 2022 at 17:56 Comment(1)
I think the below is the best solution as per your answer. - view->command palette OR cntrl+shift+p - type "fold" .It will suggest the fold and unfold and there shortcut. You can type that shortcut instead of command-paletteAmmieammine
O
11

Just press ctrl + shift + p, and then type 'fold'. all keybinds about (un)fold will be shown. If ctrl k does not work, probably it's because the vim extension overrides the key. in this case, you should modify settings.json (press ctrl + shift + p, and then type 'settings' ) with

"vim.handleKeys": {
  "<C-k>": false,
},

enter image description here

Ottie answered 20/10, 2021 at 2:8 Comment(0)
H
9

This feature is now supported, since Visual Studio Code 1.17. To fold/collapse your code block, just add the region tags, such as //#region my block name and //#endregion if coding in TypeScript/JavaScript.

Example:

Region Folding

Herbert answered 29/10, 2017 at 0:30 Comment(1)
How do you create and embed a gif like this answer you posted ?Millimicron
F
9

Here is the most common useful default keymap of VSCode. And you cab easily customize them with your own keymap. CTRL + K and then:

Fold All: CTRL + 0

Unfold All: CTRL + J

Fold Region: CTRL + [

Unfold Region: CTRL + ]

Fold Level 1: CTRL+ 1

Fold Level 2: CTRL+ 2

Fold Level 3: CTRL+ 3

Fold Level 1: CTRL+ 4
Feign answered 8/7, 2021 at 1:55 Comment(2)
To use these, first press ctrol + k For example to fold all press ctrol + k, ctrol + 0Flow
ctrl + k deletes a row of text --- beware .. I am on Mac M2 + VsCodeGrowth
N
8

Code folding controls inside the editor to expand nodes of XML-structured documents and source code in VsCode

No technical tips here, just simple adjustments of the preferences of VsCode.

I managed to show code folding controls always in VsCode by going to Preferences and searching for 'folding'. Now just select to always show these controls. This works with the Typescript code and HTML of templates in the Angular 8 solution I tested it with.

This was tested with VsCode Insiders 1.37.0 running on a Windows 10 OS.

Show code folding controls always in VsCode

Natation answered 30/7, 2019 at 20:27 Comment(0)
B
8

v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:

Folded Range Highlighting

Folded ranges now are easier to discover thanks to a background color for all folded ranges.

fold highlight

Fold highlight color Theme: Dark+

The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.

"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }

Folding Refinements

Shift + Click on the folding indicator first only folds the inner ranges. Shift + Click again (when all inner ranges are already folded) will also fold the parent. Shift + Click again unfolds all.

fold shift click

When using the Fold command (kb(editor.fold))] on an already folded range, the next unfolded parent range will be folded.

Bise answered 3/2, 2020 at 18:18 Comment(1)
wow this is awesome, for vue js option apiInexplicable
M
5

As of version 1.3.1 (2016-07-17), Block Collapse is much more convenient.

Any line followed by an indented line will have a '-' character to allow collapse. If the block is collapsed, it will then be replaced by a '+' character that will open the collapsed block.

The (Ctrl + Shift + Alt + ]) will still affect all blocks, closing one level. Each repeated use closed one more level. The (Ctrl + Shift + Alt + [) works in the opposite way.

Hooray, block collapse finally works usefully.

Manipulate answered 16/7, 2016 at 12:19 Comment(2)
Adding to this - if you out-dent a comment around a region of code, you can use comments to build custom regions in your code and collapse entire custom segments! Great feature!Gerita
This doesn't work as of Jul 13 2019. Is there any other keboard shortcut substituting it? (collapsing/expanding one level at a time?{Mirnamirror
C
5

to fold/unfold current block use (ctrl+k)+(ctrl+l)

Carton answered 30/12, 2021 at 11:51 Comment(0)
E
5

From Visual Studio Code

Fold All (Ctrl+K Ctrl+0) folds all regions in the editor.
Unfold All (Ctrl+K Ctrl+J) unfolds all regions in the editor.
Fold Level X (Ctrl+K Ctrl+2 for level 2) folds all regions of level X, except the region at the current cursor position.

enter image description here

Enliven answered 6/7, 2023 at 0:20 Comment(0)
S
4

VSCode extension: Fold Level, one key fold to the level you want.

enter image description here

Scolopendrid answered 25/2, 2019 at 1:13 Comment(0)
S
4

Note: these shortcuts only work as expected if you edit your keybindings.json

I wasn't happy with the default shortcuts, I wanted them to work as follow:

  • Fold: Ctrl + Alt + ]
  • Fold recursively: Ctrl + ⇧ Shift + Alt + ]
  • Fold all: Ctrl + k then Ctrl + ]
  • Unfold: Ctrl + Alt + [
  • Unfold recursively: Ctrl + ⇧ Shift + Alt + [
  • Unfold all: Ctrl + k then Ctrl + [

To set it up:

  • Open Preferences: Open Keyboard Shortcuts (JSON) (Ctrl + ⇧ Shift + p)
  • Add the following snippet to that file

    Already have custom keybindings for fold/unfold? Then you'd need to replace them.

    {
        "key": "ctrl+alt+]",
        "command": "editor.fold",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+alt+[",
        "command": "editor.unfold",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+shift+alt+]",
        "command": "editor.foldRecursively",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+shift+alt+[",
        "command": "editor.unfoldRecursively",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+k ctrl+[",
        "command": "editor.unfoldAll",
        "when": "editorTextFocus && foldingEnabled"
    },
    {
        "key": "ctrl+k ctrl+]",
        "command": "editor.foldAll",
        "when": "editorTextFocus && foldingEnabled"
    },
Subshrub answered 8/5, 2020 at 10:49 Comment(0)
I
3

On a Mac, it's the RHS Command key, K, not the left for the code folding commands.

Otherwise the left hand Command key will delete the current line, K.

Islamism answered 17/8, 2017 at 13:30 Comment(0)
G
2

I wish Visual Studio Code could handle:

#region Function Write-Log
Function Write-Log {
    ...
}
#endregion Function Write-Log

Right now Visual Studio Code just ignores it and will not collapse it. Meanwhile Notepad++ and PowerGUI handle this just fine.

Update: I just noticed an update for Visual Studio Code. This is now supported!

Geostrophic answered 7/8, 2018 at 19:12 Comment(0)
M
2

Or, if you want to remove the folding buttons, for extra space:

"editor.folding": false

(add to your settings.json file)

Mcfall answered 23/7, 2020 at 12:38 Comment(0)
H
1

If you are editing a large file, it might be handy to increase Folding Maximum Regions setting, since by default it's limited to 5000.

"editor.foldingMaximumRegions": 5000
Hoogh answered 13/7, 2023 at 14:15 Comment(0)
A
0

More info here: region extensionhttps://marketplace.visualstudio.com/items?itemName=maptz.regionfolder

After installing the extension and using python, it works like this:

# region ARBITRARY_REGION_NAME

   code goes here...

# endregion

Also, selecting the desired area, use Ctrl+M+Ctrl+R.

(that is: first hit and hold Ctrl, then hit m, let go m, then hit r, and let go all)

Antipyretic answered 2/1, 2023 at 23:22 Comment(0)
B
0

If you encountered the issue where your class name is collapsed into due to ◦◦◦ or ..., it might be caused by Tailwind related extensions like this:

The extension will collapse the class because tailwind CSS can be repetitive and long, so the extension will help to fold those classes from something like:

<div class="some class names here"></div>

Into:

<div class="..."></div>

VSCode extensions can modify the behaviour of codes such as the formatting and display, so it will be better to review your Extensions list and ensure none of them caused a side effect that is unexpected. Disable them and try again to see whether it solved your issue.

Buote answered 27/4, 2023 at 4:36 Comment(2)
I'm not sure how this answers the question here... See also: https://mcmap.net/q/46281/-why-are-my-html-class-attributes-collapsed-inline-into-three-dots/11107541Cheremkhovo
Hi @user, someone has asked me to copy-paste my answer here because it is a duplicate of another question, which is what I did, and now it has been flagged as irrelevant... Original question: #76117198 (Sometimes it is hard to please everyone... when I try to answer in one and others say I shouldn't and should post in the duplicate instead, then now I get downvoted twice for copying over... I am tired to be kind)Buote

© 2022 - 2024 — McMap. All rights reserved.