Visual Studio Code
Code Folding
Programming
Software Development
Coding Tips

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

VS Code supports code folding through keyboard shortcuts, gutter icons, the Command Palette, and custom region markers. The fastest way to collapse a block is to place your cursor inside it and press Ctrl+Shift+[ on Windows/Linux or Cmd+Option+[ on macOS. To unfold, use Ctrl+Shift+] or Cmd+Option+]. This article covers every folding mechanism VS Code provides, including language-aware folding, indentation-based folding, custom regions, and the settings that control folding behavior.

Keyboard Shortcuts for Folding

These are the core shortcuts every VS Code user should know:

ActionWindows / LinuxmacOS
Fold current blockCtrl+Shift+[Cmd+Option+[
Unfold current blockCtrl+Shift+]Cmd+Option+]
Fold allCtrl+K, Ctrl+0Cmd+K, Cmd+0
Unfold allCtrl+K, Ctrl+JCmd+K, Cmd+J
Fold level 1Ctrl+K, Ctrl+1Cmd+K, Cmd+1
Fold level 2Ctrl+K, Ctrl+2Cmd+K, Cmd+2
Fold level 3Ctrl+K, Ctrl+3Cmd+K, Cmd+3
Fold all block commentsCtrl+K, Ctrl+/Cmd+K, Cmd+/
Fold recursivelyCtrl+K, Ctrl+[Cmd+K, Cmd+[
Unfold recursivelyCtrl+K, Ctrl+]Cmd+K, Cmd+]
Toggle foldCtrl+K, Ctrl+LCmd+K, Cmd+L

The level-based shortcuts are particularly useful for large files. Ctrl+K, Ctrl+2 collapses everything to two levels of nesting, giving you a high-level overview of the file structure while keeping top-level blocks expanded.

Gutter Folding Icons

The fold/unfold arrows appear in the gutter (the area between line numbers and the editor content) when you hover over a foldable region. Click the downward-pointing arrow to collapse a block, and click the rightward-pointing arrow to expand it.

By default, these icons only appear on hover. To make them always visible:

json
{
    "editor.showFoldingControls": "always"
}

Set this in your settings.json file (open with Ctrl+, then click the JSON icon in the top right).

Folding Strategies

VS Code determines where fold regions begin and end using one of two strategies:

Indentation-Based Folding

This is the default fallback. VS Code looks at the indentation of consecutive lines to determine foldable blocks. Any line that is followed by more-indented lines creates a fold region.

This works for any language, even languages without a dedicated VS Code extension. It is the reason you can fold YAML, plain text files, and configuration formats without any special setup.

Language-Based Folding

When a language extension provides a folding range provider, VS Code uses the language's actual syntax structure to determine fold regions. This is more accurate than indentation because it understands constructs like multi-line strings, comments, and nested blocks that may not follow strict indentation rules.

To control which strategy is used:

json
{
    "editor.foldingStrategy": "auto"
}
ValueBehavior
"auto"Use language provider if available, fall back to indentation
"indentation"Always use indentation-based folding

Most of the time, "auto" is the correct choice. Switch to "indentation" only if a language extension's folding provider produces incorrect regions.

Custom Folding Regions

Most languages support region markers that let you define arbitrary foldable sections, independent of the code's syntactic structure.

JavaScript / TypeScript

javascript
1//#region Database initialization
2const pool = createPool({
3    host: process.env.DB_HOST,
4    port: parseInt(process.env.DB_PORT),
5    database: process.env.DB_NAME,
6});
7
8async function initializeDatabase() {
9    await pool.query('CREATE TABLE IF NOT EXISTS users (...)');
10    await pool.query('CREATE TABLE IF NOT EXISTS sessions (...)');
11}
12//#endregion

Python

python
1# region Data processing utilities
2def normalize(data):
3    return [x / max(data) for x in data]
4
5def filter_outliers(data, threshold=3):
6    mean = sum(data) / len(data)
7    return [x for x in data if abs(x - mean) < threshold]
8# endregion

C# / Java

csharp
1#region Repository Methods
2public async Task<User> GetUserById(int id)
3{
4    return await _context.Users.FindAsync(id);
5}
6
7public async Task<List<User>> GetAllUsers()
8{
9    return await _context.Users.ToListAsync();
10}
11#endregion

HTML

html
1<!-- #region Navigation -->
2<nav class="main-nav">
3    <ul>
4        <li><a href="/">Home</a></li>
5        <li><a href="/about">About</a></li>
6    </ul>
7</nav>
8<!-- #endregion -->

CSS / SCSS

css
1/* #region Typography */
2h1 { font-size: 2rem; font-weight: 700; }
3h2 { font-size: 1.5rem; font-weight: 600; }
4h3 { font-size: 1.25rem; font-weight: 500; }
5/* #endregion */

Region markers are especially valuable in large configuration files, test suites, and CSS files where natural syntactic blocks may not align with logical sections.

Folding Settings Reference

All folding-related settings in VS Code:

json
1{
2    // Enable or disable folding entirely
3    "editor.folding": true,
4
5    // Choose folding strategy: "auto" or "indentation"
6    "editor.foldingStrategy": "auto",
7
8    // Show fold controls: "always" or "mouseover"
9    "editor.showFoldingControls": "mouseover",
10
11    // Highlight folded ranges with a background color
12    "editor.foldingHighlight": true,
13
14    // Maximum number of foldable regions (performance guard)
15    "editor.foldingMaximumRegions": 5000,
16
17    // Import folding controls in the editor
18    "editor.foldingImportsByDefault": false
19}

The foldingMaximumRegions setting is worth knowing about. For very large files (10,000+ lines), computing fold regions can slow down the editor. If you notice lag, check whether this limit is being hit.

Folding in the Command Palette

Open the Command Palette with F1 or Ctrl+Shift+P and type "fold" to see all available commands:

  • Fold: Fold the innermost block at the cursor
  • Unfold: Unfold the block at the cursor
  • Fold All: Collapse everything
  • Unfold All: Expand everything
  • Fold Level 1-7: Collapse to a specific nesting depth
  • Fold All Block Comments: Collapse only comment blocks
  • Fold All Regions: Collapse only custom region markers
  • Unfold All Regions: Expand only custom region markers
  • Toggle Fold: Toggle the fold state at the cursor

The "Fold All Block Comments" command is particularly useful when reviewing code. It hides documentation blocks so you can focus on the implementation.

Practical Workflow Tips

Reviewing a Large File

When opening a large unfamiliar file, start with Ctrl+K, Ctrl+1 to fold everything to the top level. This gives you the class and function structure. Then selectively unfold the sections you need.

Organizing Test Files

Use region markers to group related tests:

javascript
1//#region User Authentication Tests
2describe('login', () => {
3    test('succeeds with valid credentials', () => { /* ... */ });
4    test('fails with wrong password', () => { /* ... */ });
5    test('locks account after 5 failures', () => { /* ... */ });
6});
7//#endregion
8
9//#region User Profile Tests
10describe('profile', () => {
11    test('returns user data', () => { /* ... */ });
12    test('updates display name', () => { /* ... */ });
13});
14//#endregion

Hiding Boilerplate

In files with repetitive boilerplate (imports, configuration, serialization), fold those sections to focus on the logic:

python
1# region Imports
2import os
3import sys
4import json
5import logging
6from datetime import datetime
7from pathlib import Path
8from typing import List, Dict, Optional
9# endregion
10
11# region Configuration
12CONFIG = {
13    "db_host": os.environ.get("DB_HOST", "localhost"),
14    "db_port": int(os.environ.get("DB_PORT", "5432")),
15    "log_level": os.environ.get("LOG_LEVEL", "INFO"),
16}
17# endregion
18
19# The actual logic you care about starts here
20def process_batch(items: List[Dict]) -> List[Dict]:
21    results = []
22    for item in items:
23        # ...

Common Pitfalls

  • Confusing Ctrl+[ (outdent line) with Ctrl+Shift+[ (fold block). Without Shift, you are changing indentation instead of folding.
  • Using indentation-based folding in a language that has a dedicated folding provider. The indentation strategy may produce wrong regions for multi-line strings, comments, or template literals. Keep foldingStrategy set to "auto".
  • Adding region markers without corresponding end markers. An unmatched #region or //#region is silently ignored but creates confusion when someone tries to fold it.
  • Over-using region markers in files that already have natural structure (classes, functions). If every function is wrapped in a region, the markers add noise without value. Use them for logical groupings that cross syntactic boundaries.
  • Not knowing about Ctrl+K, Ctrl+0 (fold all) and Ctrl+K, Ctrl+J (unfold all). These two shortcuts are the fastest way to get an overview of a large file or restore it to full view.
  • Ignoring the foldingMaximumRegions setting when working with very large generated files. If folding stops working in a file, this limit may have been reached.

Summary

  • Fold blocks with Ctrl+Shift+[ (Windows/Linux) or Cmd+Option+[ (macOS). Unfold with the matching ] shortcut.
  • Use Ctrl+K, Ctrl+0 to fold everything and Ctrl+K, Ctrl+J to unfold everything.
  • Level-based folding (Ctrl+K, Ctrl+1 through Ctrl+K, Ctrl+7) gives you a structural overview at any nesting depth.
  • Define custom foldable sections with language-specific region markers (//#region, # region, #region, <!-- #region -->).
  • Configure folding behavior through editor.foldingStrategy, editor.showFoldingControls, and editor.foldingMaximumRegions in settings.json.
  • Use "Fold All Block Comments" from the Command Palette to hide documentation while reviewing implementation.

Course illustration
Course illustration

All Rights Reserved.