'how to collapse code between two rows in vscode

function fruits() {

  //=======================
  const a = "APPLE";
  const b = "ORANGE";
  const c = "BANANA";
  //=======================

  ...
}

Is there a way to collapse the code between the dashed comment (//=====)



Solution 1:[1]

Here is an extension I made, Find and Transform, that can automate the process of adding the regeion/endregion markers around a selection and then fold the result.

Demo with different indentation levels:

macro insert region markers and fold

Use this keybinding in your keybindings.json:

{
  "key": "alt+m",                   whatever keybinding you want
  "command": "findInCurrentFile",
  // modify the below for your language id
  "when": "editorTextFocus && !editorReadonly && editorLangId == javascript",
  "args": {
    "replace": [
      "$${",
        "let indent = `${selectedText}`.match(/^(\\s*)/)[1];",

        "let str = `${indent}// #region <CONTENT>\n`;",
        "str += `${selectedText}\n`;",
        "str += `${indent}// #endregion`;",
        
        "return str;",   
      "}$$"
    ],
    "cursorMoveSelect": "CONTENT",   // select this after replacement

    "postCommands": "editor.fold"
  }
}

The replace is a javascript function. The variable indent is the padding (tabs or spaces) to add to the beginning of the comment lines to match the existing indent.

Since the replace code uses the amount of space at the beginning of the first line selected, make sure you select the entire lines as in the demo - select all the way to the left.

Different languages use different region markers for folding - in the example I used // #region and // #endregion. You should change that portion of the code for whatever region markers you need.

You could add a when clause to the keybinding so it only works for the specified language, like:

"when": "editorTextFocus && !editorReadonly && editorLangId == javascript"

In that way you could set up the same keybinding to use different region markers for different languages.

You see that this is added to the start of the region:

// #region <CONTENT> some people want to have a CONTENT field to fill in describing the folded code within. You can delete the <CONTENT> part if you are not interested in that. And if you are not, delete the cursorMoveSelect option line as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1