Collapse all methods in Visual Studio Code
Asked Answered
B

12

988

In Visual Studio Professional, we have a shortcut key, Ctrl + M Ctrl + O to collapse all methods and properties in a class. How can I do a similar thing in Visual Studio Code?

I know there are shortcut keys like Ctrl + Shift + [, but this does not meet the needs.

Is it possible to get the Visual Studio Professional-like behaviour in Visual Studio Code?

Bevatron answered 8/3, 2017 at 0:6 Comment(5)
see this link #30068267Accomplish
You can also press F1 whilst editing, and in the search bar, type fold or unfold and you will see clickable options to do everything below and more, it also shows the keyboard shortcuts.Supervisor
cmd + shift + p (then search for "fold" to find it or even select it)Priggery
For those having problems with any of the CTRL-shortcuts: check your active addons. I had a vim-addon installed which seemed to block those shortcuts.Sprightly
For (currently) most famous vim-addon Vim (vscodevim) you may add this to your settings.json: "vim.handleKeys": { "<C-k>": false }Sprightly
C
1782
  • Fold All:

    • Windows and Linux: Ctrl + K Ctrl + 0 (ZERO)
    • Mac: + K + 0
  • Unfold All:

    • Windows and Linux: Ctrl + K Ctrl + J
    • Mac: + K + J

To see all available shortcuts in the editor:

  • Windows and Linux: Ctrl + K Ctrl + S
  • Mac: + K + S

Screenshot of Visual Studio keyboard shortcuts

All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts

Catholicism answered 30/4, 2017 at 20:3 Comment(11)
Thanks with Cmd+k Cmd+S to open the short key setting. It's really helpful.Chapland
For those confused like I was, that's a ZERO, not an o.Decagram
Unfortunately this does not apply to current versions like 1.41+ (or even lower versions). Anyway - the posted picture still seems to be correct, because you have to Press&Hold Ctrl. then press K, release Ctrl, press&hold it again, and then press one of the other keys like O, 1, 2 and so on! Pressing Ctrl.+K, releasing everything and then pressing S for example does "Save all". The releasing and pressing of Ctrl. again is important here and makes the difference! See some answer below...Ornamental
seems like shortcuts made to longcuts. :).Acatalectic
@Ornamental Your statement that [control + k, 1] and [control + k, control + 1] are two different shortcuts is correct and usefully points out that this answer isn't as clear as it should be. However, your statement that you need to release and re-press control in between the k and the 1 to activate the latter shortcut is wrong. You can simply hold control while you press and release k and then press and release 1 to activate the shortcut [control + k, control + 1]. Just wanted to clarify that.Looselimbed
@Looselimbed Thanks for your info. Just tried it, you are right. No need to release CTRL in between K and 1. At least now, in version 1.51.1. Maybe I simply misunderstood the answer those days. The answer in its current state is fine. It's [CTRL+K+S], not [CTRL+K, S]Ornamental
PS: The 0 button needs to be the one above the alphabets. Num-pad 0 doesn't seem to work.Latticed
For those that are confused, VS Code handles listening to a first keystroke then a second one. To Fold all regions, you would press on Ctrl+K then on Ctrl+0 You would need to release Ctrl between the two presses. (You actually can notice that VS code prompts a message in its Blue bar status stating that it's "waiting for a second key or chord")Oteliaotero
Just for added clarity, I had mistakenly thought Ctrl K + Ctrl # would unfold those items that are not folded by the particular number. For instance, I had already folded all levels using Ctrl K + Ctrl 0 and then hit Ctrl K + Ctrl 2. I couldn't figure out why nothing was happening, assuming it would unfold to level 2. However, it simply folds everything to the level set, regardless of it's previous state. So if you have some portions folded that you would like unfolded it might be best to unfold everything using Ctrl K + Ctrl J and then fold to your desired level.Pozzuoli
vscode is actually too goodRussellrusset
This might not work if you imported Sublime shortcuts (at least it did not work for me). If so you can ⌘+shift+p and type fold all as mentioned by reply bellowAdeline
S
413
  • Ctrl + K + Ctrl + 0: fold all levels (namespace, class, method, and block)
  • Ctrl + K + Ctrl + 1: namespace / @Component(For Angular)
  • Ctrl + K + Ctrl + 2: class / methods
  • Ctrl + K + Ctrl + 3: methods / blocks
  • Ctrl + K + Ctrl + 4: blocks / inner blocks
  • Ctrl + K + Ctrl + [ or Ctrl + k + ]: current cursor block
  • Ctrl + K + Ctrl + j: UnFold

From Visual Studio Code

enter image description here

Solar answered 13/2, 2019 at 8:42 Comment(4)
btw, for those of us on OSX, use cmd in place of ctrlCallimachus
This should be the accepted answer as "fold all" is cleary not the same as "collapse all methods and properties", this anwers the question perfectlyTonneau
Sounds like Ctrl + K + 3 doesn't work fine in Java, folds a for loop in a method instead of folding the method itself. Tried multiple times.Altitude
That's incorrect, namespaces, classes, methods, etc. do not necessarily sit at levels 1, 2, 3, etc. It just deals with folding/unfolding whatever is at these levels.Baroscope
T
250

Like this ? (Visual Studio Code version 0.10.11)

Fold All (Ctrl+K Ctrl+0)

Unfold All (Ctrl+K Ctrl+J)

Fold Level n (Ctrl+K Ctrl+N)

Taxeme answered 8/3, 2017 at 11:56 Comment(9)
Unfortunately no. This one collapses everything, including the class itself, methods,if-else conditions and loops inside the methods. Where as in VS professional it just collapses methods. When we open a method it opens up fully.Bevatron
Added a 'fold level' shortcut. Maybe it's what you're looking for ?Taxeme
@Bevatron In a typescript file, Ctrl + K, 2 does exactly that for me.Hade
This answer is both concise and also completely correct/clear. Most others, including the accepted answer, fail to resolve the ambiguity between the shortcuts [control + k, 0] and [control + k, control + 0].Looselimbed
ctrl+n is the shortcut. edit the answer making it [n]. "Fold Level n (Ctrl+K Ctrl+[ n ] )". or tell there that N=any numberIdiotism
For dummies => press Ctrl+K then take your hand off the keys and press Ctrl+0 to fold allMendie
This is not working with version 1.68.1Pony
This work in version 1.71Taxeme
ctrl + k, 0 ==0(zero)Froghopper
L
138

The beauty of Visual Studio Code is

Ctrl + Shift + P

Hit it and search anything you want.

In your case, hit Ctrl + Shift + P and type fold all.

Lohman answered 4/7, 2017 at 10:20 Comment(8)
Cmd + Shift + p for Mac users.Heroworship
best answer for me!Papagena
This is the best approach to be used for visual studio folding.Virgil
Best answer for me too. I prefer using the F1 key though.Amorous
There are some things I still use key combinations for, but getting used to Cmd + P and Cmd + Shift + P is by far the best that ever happened to my VSCode workflow.Gannie
best answer!!!!Afflictive
Not the best answer for me, if you're used to the word "collapse" then you won't find it in that search.Altitude
This solves issue of colliding shortcuts for me, thank you!Adeline
I
37

Mac Users

Fold Commands

enter image description here

Unfold commands enter image description here

Inculpable answered 1/1, 2019 at 4:38 Comment(1)
For dummies => press ⌘+K then take your hand off the keys and press ⌘+0 to fold all –Mendie
R
28

Ctrl+K, Ctrl+1 and then Ctrl+K, Ctrl+2 will do close to what you want.

The first command collapses level 1 (usually classes), and the second command collapses level 2 (usually methods).

You might even find it useful to skip the first command.

Raney answered 15/3, 2018 at 12:10 Comment(5)
What do you mean by "will do close to what you want." (it seems incomprehensible)?Diesel
@PeterMortensen - In English, this construct basically resolves to "[this suggestion] will [accomplish something similar to] what you want [to accomplish]." He's saying the suggestion will do (accomplish) close to (similar to) what the OP wants (the thing he wants to do).Quattrocento
Correct and precise answer for the current version 1.42.1, because it helps to understand, that you have to release Ctrl. and press&hold it again before each of the K and 1 keys!Ornamental
thx, Ctrl+K, Ctrl+2 do the job in May, 2020Impeach
If its already fully collapsed, first do Ctrl+K,Ctrl+J to "expand all". THEN do one of the mentioned commands, to expand just the level(s) you want. Otherwise, you may find that the contents of each method are collapsed at the block level, requiring unfolding each block.Cornett
R
25

Collapse All is Fold All in Visual Studio Code.

Press Ctrl + K + S for All Settings. Assign a key which you want for Fold All. By default it's Ctrl + K + 0.

Resort answered 9/7, 2019 at 6:36 Comment(2)
This does not bring value as this is already discussed in other upvoted answers.Spiker
@Nilambar I disagree. This is the only answer that helped me change the keybind quickly.Jennine
M
24

Use Ctrl + K + 0 to fold all and Ctrl + K + J to unfold all.

Mayotte answered 31/1, 2019 at 6:15 Comment(2)
@SunilGarg You can use Ctrl + Shift + [ to fold single code block and Ctrl + Shift + ] to unfoldMayotte
Use Ctrl + K + / to old all comments multiple lines.Sarajane
T
12

You should add user settings:

{
   "editor.showFoldingControls": "always",
   "editor.folding": true,
   "editor.foldingStrategy": "indentation", 
}
Tyratyrannical answered 11/4, 2018 at 14:11 Comment(4)
I've tried messing with this several times. Unsure how these settings help. I notice more - symbol buttons, but that's it. This doesn't seems to accomplish closing or opening "all" blocks.Pericycle
@Pericycle I think the first line just shows all those icons instead of only showing them when you hover over the thin space near line numbers. the indentation foldingStrategy seems to be the default, as I haven't changed that myself, so you didn't notice anything. Not sure what folding does.Wroughtup
@JakeT. Thanks! That makes more sense. I kinda figured out the first one. I wish there was a way to auto fold all blocks or specific types of code when you open the files. For example typescript interfaces at the top of files are annoying as hell. When I hover an interface I can see it's definition so I don't need them open and taking up real estate.Pericycle
@Pericycle No problem. I don't know if getting fine grained on which types to open/close is feasible, but the answer above ( https://mcmap.net/q/53238/-collapse-all-methods-in-visual-studio-code ) will show you how to close all, and then you could use the command to open an individual block as needed while editing code. It's the best low-effort solution available that I've found.Wroughtup
R
2

Technically speaking (if you want to be really precise), every answer here is wrong (hopefully not mine though). The top answers all revolve around toggling folding by specific nesting levels, which can be close enough for certain programming languages and coding styles, but across all languages and their grammars, there is no such happy accident or law of the universe that things that are commonly given folding by language support extensions will somehow line up such that this works with 100% accuracy in all cases.

In Python (and many other languages), you can define classes in classes. That's just one simple example of how that assumption about folding nesting levels breaks.

This extends to many (but not all) similar questions like "how can I fold all functions?" and "how can I fold all classes?".

VS Code's current design doesn't have any arbitrarily extensible tagging/annotation/classification feature for folds provided by extensions. It does have a sealed enumeration of "kinds" of folds (see FoldingRangeKind and FoldingRange), which (at the time of this writing) only lists Comments, Imports, and Region, which (obviously) does not include anything related to "methods". That distinction is what enables commands like Fold All Block Comments and Fold All Regions (and their associated, respective keybindings).

See the related issue ticket [folding] Please add more folding types (functions, classes) #98201, which was automatically closed because it didn't receive enough community support in time to get added to the backlog. You could try raising the feature-request again in a new issue ticket, but it'd still need to garner enough community support in a specific time window (see this), and it'd likely be declined for reasons I explain briefly later.

It is possible to write extensions that use language analysis to toggle the correct stuff using the editor.fold command (see also the definition of FoldingArguments) and executeCommand. I don't know of many extensions that actually do this, but you might be able to find some by searching the extension marketplace. Ex. zeevro.fold-to-definitions (I have no affiliation with this extension)

Actually..., looking at the source code of zeevro.fold-to-definitions, the way it implements it is quite elegant/ingenious. It queries all symbols provided by language support extensions using the vscode.executeDocumentSymbolProvider command, which includes the symbols' line numbers in the result set, filters by symbol kind, and then folds any folding regions for those line numbers. It's not totally foolproof, but I think it should probably work most of the time. As you can see from the API docs for symbol kinds, it's still a sealed enumeration, but it covers many more different kinds of language structures than are covered by FoldingRangeKind. I've pinged a maintainer to take a look at it, and they weighed in that if a new issue ticket was raised requesting something like this in core VS Code, it would probably be declined in favour of implementation via extension, since it's a lot of work to maintain all the existing command palette commands already (again, see the related wiki page).

Richmond answered 2/4 at 21:36 Comment(0)
C
1

I recently made an extension for collapsing C# code to definitions since I was also missing that feature from Visual Studio. Just look for "Fold to Definitions" and you should find it, or just follow this link.

The repository is public, so you can easily inspect the extension.ts file and adapt it to other languages. It is nowhere near perfect, but it does the job. It uses regular expressions to find methods, properties, and classes, and then moves the selection to those lines and executes a fold command.

Coburg answered 14/12, 2018 at 8:25 Comment(0)
C
-3

To collapse methods in the Visual Studio Code editor:

  1. Right-click anywhere in document and select "format document" option.
  2. Then hover next to number lines and you will see the (-) sign for collapsing method.

NB.: As per the Visual Studio Code documentation, a folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.

Country answered 12/4, 2017 at 21:42 Comment(2)
Is there a way to make this work more intelligently. When you have TypeScript, the { } symbols don't just signify functions/methods. Often it relates to Objects, if/else statements too - and suddenly all that is being collapsed too.Bobsleigh
OP and the people coming to this question are looking for shortcuts to do what you described. Manually collapsing every code blocks is a tedious task.Dearborn

© 2022 - 2024 — McMap. All rights reserved.