ChatGPT解决这个技术问题 Extra ChatGPT

How do I collapse sections of code in Visual Studio Code for Windows?

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

Is this feature supported?


C
Community

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

Ctrl + Shift + [ on Windows and Linux

⌥ + ⌘ + [ on macOS

Unfold unfolds the collapsed region at the cursor: Ctrl + Shift + ] on Windows and Linux ⌥ + ⌘ + ] on macOS

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

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

Ctrl + K, Ctrl + J on Windows and Linux

⌘ + K, ⌘ + J on macOS

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


@DouglasGaskell I made the same mistake. It is a zero not an o, Michael Fulton 's Fold Level answer made more sense to me.
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!
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.
@Preza8 Press F1 and type Fold or Unfold
@Preza8 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 buttons
C
Community

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)


Does it save and restore the state of folds between IDE start/shut down?
Some reason ctrl+k,ctrl+num only works on numbers above qwerty not on numpad
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?
ctrl+k kill line
niceee broooo!!!!!!
M
Mark

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://stackoverflow.com/a/72954133/836330 for the command and demo.

Fold Selected Lines, editor.foldSelected. 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.


// 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).
In CSS, it's actually /* #region Foo Bar */ and /* #endregion */
@ozanmuyes it depends on the file type (language). //region and //endregion are for JavaScript.
Works nicely in Docker .yaml files as well, if you install Microsoft's docker ext: marketplace.visualstudio.com/…
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!
P
Peter Mortensen

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:

https://i.stack.imgur.com/8XhHa.png


The question is, how to collapse all sections same time , not one by one. Is there a way to do it without shortcuts?
for that you must use shortcuts
G
Gama11

You should add user settings:

{
    "editor.showFoldingControls": "always",
    "editor.folding": true,
    "editor.foldingStrategy": "indentation", 
}

"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, thanks
M
Misha Akopov

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


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.
G
Gama11

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"
},

is this limited to some languages? doesn't work for me on OSX/typescript.
Please review this: ctrl+shift+alt+[ "Unfold all"You wrote [ instead of ]. Correct me if I am wrong.
@dcsan 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 answer
For non-US keyboards [ and ] are at the left of the backspace key (🔙).
J
Jorn Vernee

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:

https://i.stack.imgur.com/ADNTf.png


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/…
@HelderSepulveda Well, it supposedly folds block comments, but python doesn't have those. The code you linked uses multiple single line comments.
P
Peter Mortensen

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.)


G
Gama11

With JavaScript:

//#region REGION_NAME
   ...code here
//#endregion

b
bleuthoot

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:

https://code.visualstudio.com/assets/updates/1_17/region-folding.gif


u
user3113626

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,
},

https://i.stack.imgur.com/jT7iv.png


l
lava

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

vscode Keyboard shortcut

https://i.stack.imgur.com/DxR0i.png

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

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-palette

https://i.stack.imgur.com/B7RpQ.png

eg:

Fold All

https://i.stack.imgur.com/tcfgY.gif

UnFold All

https://i.stack.imgur.com/HMxe5.gif


M
Mark

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.

https://i.stack.imgur.com/LEPVx.png

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.

https://i.stack.imgur.com/3wzq1.gif

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


wow this is awesome, for vue js option api
T
Tore Aurstad

https://i.stack.imgur.com/hFXFG.gif

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.

https://i.stack.imgur.com/77f81.gif


P
Peter Mortensen

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.


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!
This doesn't work as of Jul 13 2019. Is there any other keboard shortcut substituting it? (collapsing/expanding one level at a time?{
G
General Grievance

Here is the most common useful default keymap of VS code. and You easily can customize by your own keymap.

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

To use these, first press ctrol + k For example to fold all press ctrol + k, ctrol + 0
v
vikyd

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

https://i.stack.imgur.com/w4wuJ.gif


J
JesusIniesta

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"
    },

m
mahmoud elgml

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


P
Peter Mortensen

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.


P
Peter Mortensen

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!


l
lenooh

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

"editor.folding": false

(add to your settings.json file)