how to implement regions/code collapse in javascript
Asked Answered
B

18

159

How can you implement regions a.k.a. code collapse for JavaScript in Visual Studio?

If there are hundreds of lines in javascript, it'll be more understandable using code folding with regions as in vb/C#.

#region My Code

#endregion
Beauharnais answered 17/12, 2009 at 13:0 Comment(1)
None of these solutions worked as well for me as this one. #46268408Waterlog
L
26

Blog entry here explains it and this MSDN question.

You have to use Visual Studio 2003/2005/2008 Macros.

Copy + Paste from Blog entry for fidelity sake:

  1. Open Macro Explorer
  2. Create a New Macro
  3. Name it OutlineRegions
  4. Click Edit macro and paste the following VB code:
Option Strict Off
Option Explicit Off

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections

Public Module JsMacros

    Sub OutlineRegions()
        Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection

        Const REGION_START As String = "//#region"
        Const REGION_END As String = "//#endregion"

        selection.SelectAll()
        Dim text As String = selection.Text
        selection.StartOfDocument(True)

        Dim startIndex As Integer
        Dim endIndex As Integer
        Dim lastIndex As Integer = 0
        Dim startRegions As Stack = New Stack()

        Do
            startIndex = text.IndexOf(REGION_START, lastIndex)
            endIndex = text.IndexOf(REGION_END, lastIndex)

            If startIndex = -1 AndAlso endIndex = -1 Then
                Exit Do
            End If

            If startIndex <> -1 AndAlso startIndex < endIndex Then
                startRegions.Push(startIndex)
                lastIndex = startIndex + 1
            Else
                ' Outline region ...
                selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
                selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
                selection.OutlineSection()

                lastIndex = endIndex + 1
            End If
        Loop

        selection.StartOfDocument()
    End Sub

    Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
        Dim lineNumber As Integer = 1
        Dim i As Integer = 0

        While i < index
            If text.Chars(i) = vbCr Then
                lineNumber += 1
                i += 1
            End If

            i += 1
        End While

        Return lineNumber
    End Function

End Module
  1. Save the Macro and Close the Editor
  2. Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox
  3. now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+E. I don't know why - I just entered it first time and use it now :)
Lacylad answered 17/12, 2009 at 13:1 Comment(8)
This one is useful and the important point to note from the site's comments is "You must check the name of the module in the above code with the name of your new Macro. both names must match!"Beauharnais
Does this work on VS2010? I can't get to. The Macro doesn't show up when searching for it.Belia
@Mr. Flibble: Not Sure.. I only have VS2005.Lacylad
OK. I've asked in a new question here: #2923677Belia
Microsoft now has an extension for VS2010 that provides this functionality (see my answer below for link).Rennarennane
Very Nice But Please is there is a way while highlight a javascript code and do a shortcut to put a #region in the begining and #endregion in the end to make it easy please ??? :) i think it will be a very helpful thingElevation
@Marwan: If you have a question, then ask another one. Do not comment on this answer.Lacylad
@Marway - Check out the answer below from Kaushik Thanki about using Web Essentials -Thermosiphon
A
87

Good news for developers who is working with latest version of visual studio

The Web Essentials are coming with this feature .

Check this out

enter image description here

Note: For VS 2017 use JavaScript Regions : https://marketplace.visualstudio.com/items?itemName=MadsKristensen.JavaScriptRegions

Ainsley answered 15/2, 2016 at 12:21 Comment(6)
@William some day people will need this for sure ;)Ainsley
as time is going, this will the defacto accepted answer.Doublet
Works perfect with latest version of VSCode - Typescript as of 6/10/2019.Advocate
This also work for VS2019 as well, and I don't have Web Essentials installed.Hecker
@LukeVo then seems vs2019 inbuilt support this one,Ainsley
Never use Web Essentials BE AWARE it takes you on a loop basis trying toinstall the same thimgs everytime you open vs2015. Also your JS collpase functions will not work. COMPLETELY USELESSPolysyndeton
R
53

Microsoft now has an extension for VS 2010 that provides this functionality:

JScript Editor Extensions

Rennarennane answered 13/6, 2011 at 14:32 Comment(4)
This is fantastic! I hope they include this into the next VS update. Thanks for sharing!Icky
Really wonderful extension, even better than the third party outlining extension.Briggs
any of this happening for VS 2012 and 2013?Highboy
This is great! Is there any version for VS 2012 or 2013?Coons
B
45

Thats easy!

Mark the section you want to collapse and,

Ctrl+M+H

And to expand use '+' mark on its left.

Belle answered 9/9, 2015 at 8:38 Comment(2)
It worked!. Saved me as it made my code look slimmer as i have lots of ajax calls under a single ajax calls.Teniacide
It is a temporary solution. If you close and re-open the file, the selected area disappears.Ruelu
P
32

For those about to use the visual studio 2012, exists the Web Essentials 2012

For those about to use the visual studio 2015, exists the Web Essentials 2015.3

The usage is exactly like @prasad asked

Pedology answered 1/10, 2013 at 17:57 Comment(1)
+1 - this should be the answer, as most people will be using 2012/2013 by now! (it also works for 2013)Schoonover
L
26

Blog entry here explains it and this MSDN question.

You have to use Visual Studio 2003/2005/2008 Macros.

Copy + Paste from Blog entry for fidelity sake:

  1. Open Macro Explorer
  2. Create a New Macro
  3. Name it OutlineRegions
  4. Click Edit macro and paste the following VB code:
Option Strict Off
Option Explicit Off

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.Collections

Public Module JsMacros

    Sub OutlineRegions()
        Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection

        Const REGION_START As String = "//#region"
        Const REGION_END As String = "//#endregion"

        selection.SelectAll()
        Dim text As String = selection.Text
        selection.StartOfDocument(True)

        Dim startIndex As Integer
        Dim endIndex As Integer
        Dim lastIndex As Integer = 0
        Dim startRegions As Stack = New Stack()

        Do
            startIndex = text.IndexOf(REGION_START, lastIndex)
            endIndex = text.IndexOf(REGION_END, lastIndex)

            If startIndex = -1 AndAlso endIndex = -1 Then
                Exit Do
            End If

            If startIndex <> -1 AndAlso startIndex < endIndex Then
                startRegions.Push(startIndex)
                lastIndex = startIndex + 1
            Else
                ' Outline region ...
                selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
                selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
                selection.OutlineSection()

                lastIndex = endIndex + 1
            End If
        Loop

        selection.StartOfDocument()
    End Sub

    Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
        Dim lineNumber As Integer = 1
        Dim i As Integer = 0

        While i < index
            If text.Chars(i) = vbCr Then
                lineNumber += 1
                i += 1
            End If

            i += 1
        End While

        Return lineNumber
    End Function

End Module
  1. Save the Macro and Close the Editor
  2. Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox
  3. now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+E. I don't know why - I just entered it first time and use it now :)
Lacylad answered 17/12, 2009 at 13:1 Comment(8)
This one is useful and the important point to note from the site's comments is "You must check the name of the module in the above code with the name of your new Macro. both names must match!"Beauharnais
Does this work on VS2010? I can't get to. The Macro doesn't show up when searching for it.Belia
@Mr. Flibble: Not Sure.. I only have VS2005.Lacylad
OK. I've asked in a new question here: #2923677Belia
Microsoft now has an extension for VS2010 that provides this functionality (see my answer below for link).Rennarennane
Very Nice But Please is there is a way while highlight a javascript code and do a shortcut to put a #region in the begining and #endregion in the end to make it easy please ??? :) i think it will be a very helpful thingElevation
@Marwan: If you have a question, then ask another one. Do not comment on this answer.Lacylad
@Marway - Check out the answer below from Kaushik Thanki about using Web Essentials -Thermosiphon
P
26

By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.

Pettaway answered 6/10, 2014 at 10:0 Comment(2)
THANK YOU! Can you tell me how to undo this if I accidentally create a region that I want to remove or change?Piatt
You can undo with CTRL + M + U - more shortcuts there: msdn.microsoft.com/en-us/library/td6a5x4s.aspxPhotograph
C
20

The JSEnhancements plugin for Visual Studio addresses this nicely.

Centripetal answered 11/5, 2011 at 18:23 Comment(0)
I
18

For those who have come here for Visual Studio Code, the same syntax works

// #region MongoDB Client
const MongoClient = require('mongodb').MongoClient;
const url = constants.credentials["uat"].mongo.url
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, client) {
    if (err) {
        console.log(err);
    }
    else {
        docDB = client.db("middlewareDB");
    }
});
// #endregion

When collapsed, it looks like below

enter image description here

Indefinable answered 8/3, 2021 at 7:53 Comment(0)
J
9

Thanks to 0A0D for a great answer. I've had good luck with it. Darin Dimitrov also makes a good argument about limiting the complexity of your JS files. Still, I do find occasions where collapsing functions to their definitions makes browsing through a file much easier.

Regarding #region in general, this SO Question covers it quite well.

I have made a few modifications to the Macro to support more advanced code collapse. This method allows you to put a description after the //#region keyword ala C# and shows it in the code as shown:

Example code:

//#region InputHandler
var InputHandler = {
    inputMode: 'simple', //simple or advanced

    //#region filterKeys
    filterKeys: function(e) {
        var doSomething = true;
        if (doSomething) {
            alert('something');
        }
    },
    //#endregion filterKeys

    //#region handleInput
    handleInput: function(input, specialKeys) {
        //blah blah blah
    }
    //#endregion handleInput

};
//#endregion InputHandler

Updated Macro:

Option Explicit On
Option Strict On

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module JsMacros


    Sub OutlineRegions()
        Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection, EnvDTE.TextSelection)

        Const REGION_START As String = "//#region"
        Const REGION_END As String = "//#endregion"

        selection.SelectAll()
        Dim text As String = selection.Text
        selection.StartOfDocument(True)

        Dim startIndex As Integer
        Dim endIndex As Integer
        Dim lastIndex As Integer = 0
        Dim startRegions As New Stack(Of Integer)

        Do
            startIndex = text.IndexOf(REGION_START, lastIndex)
            endIndex = text.IndexOf(REGION_END, lastIndex)

            If startIndex = -1 AndAlso endIndex = -1 Then
                Exit Do
            End If

            If startIndex <> -1 AndAlso startIndex < endIndex Then
                startRegions.Push(startIndex)
                lastIndex = startIndex + 1
            Else
                ' Outline region ...
                Dim tempStartIndex As Integer = CInt(startRegions.Pop())
                selection.MoveToLineAndOffset(CalcLineNumber(text, tempStartIndex), CalcLineOffset(text, tempStartIndex))
                selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
                selection.OutlineSection()

                lastIndex = endIndex + 1
            End If
        Loop

        selection.StartOfDocument()
    End Sub

    Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer) As Integer
        Dim lineNumber As Integer = 1
        Dim i As Integer = 0

        While i < index
            If text.Chars(i) = vbLf Then
                lineNumber += 1
                i += 1
            End If

            If text.Chars(i) = vbCr Then
                lineNumber += 1
                i += 1
                If text.Chars(i) = vbLf Then
                    i += 1 'Swallow the next vbLf
                End If
            End If

            i += 1
        End While

        Return lineNumber
    End Function

    Private Function CalcLineOffset(ByVal text As String, ByVal index As Integer) As Integer
        Dim offset As Integer = 1
        Dim i As Integer = index - 1

        'Count backwards from //#region to the previous line counting the white spaces
        Dim whiteSpaces = 1
        While i >= 0
            Dim chr As Char = text.Chars(i)
            If chr = vbCr Or chr = vbLf Then
                whiteSpaces = offset
                Exit While
            End If
            i -= 1
            offset += 1
        End While

        'Count forwards from //#region to the end of the region line
        i = index
        offset = 0
        Do
            Dim chr As Char = text.Chars(i)
            If chr = vbCr Or chr = vbLf Then
                Return whiteSpaces + offset
            End If
            offset += 1
            i += 1
        Loop

        Return whiteSpaces
    End Function

End Module
Josiahjosias answered 6/1, 2010 at 20:36 Comment(2)
VS 2010 has an updated extensions framework and someone was nice enough to create a code-folding plugin called "Visual Studio 2010 JavaScript Outlining" here: jsoutlining.codeplex.comJosiahjosias
Can we write the macro in C# instead of VB ?Puerperal
B
7

This is now natively in VS2017:

//#region fold this up

//#endregion

Whitespace between the // and # does not matter.

I do not know what version this was added in, as I cannot find any mention of it in the changelogs. I am able to use it in v15.7.3.

Bernita answered 7/6, 2018 at 16:5 Comment(0)
H
5

For VS 2019, this should work without installing anything:

enter image description here

    //#region MyRegion1

    foo() {

    }

    //#endregion

    //#region MyRegion2

    bar() {

    }

    //#endregion
Hecker answered 31/10, 2020 at 21:48 Comment(0)
I
2

It works like a charm in PhpStorm

//#region My Region 1
    ...
//#endregion

//#region My Region 2
    ...
//#endregion

my regions

Ioab answered 28/8, 2020 at 7:42 Comment(0)
N
1

On VS 2012 and VS 2015 install WebEssentials plugin and you will able to do so.

http://vswebessentials.com/features/javascript

Nimrod answered 26/11, 2015 at 0:30 Comment(0)
S
1

For visual studio 2017.

    //#region Get Deactivation JS
    .
    .
    //#endregion Get Deactivation JS

This was not working earlier so I downloaded extension from here

Extension Name(JavaScript Regions) By Mads Kristensen

Sanferd answered 14/6, 2018 at 9:36 Comment(0)
C
0

if you are using Resharper

fallow the steps in this pic

enter image description here then write this in template editor

  //#region $name$
$END$$SELECTION$
  //#endregion $name$

and name it #region as in this picture enter image description here

hope this help you

Coopery answered 24/10, 2016 at 15:24 Comment(0)
F
0

None of these answers did not work for me with visual studio 2017.

The best plugin for VS 2017: JavaScript Regions

Example 1:

enter image description here

Example 2:

enter image description here

Tested and approved:

enter image description here

Fakieh answered 13/6, 2017 at 1:56 Comment(2)
your answer just duplicate this oneOtherworld
As I see in the edit history, there were no changes in image URL after initial submit in 2016Otherworld
F
-2

Region should work without changing settings

//#region Optional Naming
    var x = 5 -0; // Code runs inside #REGION
    /* Unnecessary code must be commented out */
//#endregion

To enable collapsing comment area /**/

/* Collapse this

*/

Settings -> Search "folding" -> Editor: Folding Strategy -> From "auto" to "indentation".

TAGS: Node.js Nodejs Node js Javascript ES5 ECMAScript comment folding hiding region Visual studio code vscode 2018 version 1.2+ https://code.visualstudio.com/updates/v1_17#_folding-regions

Fadil answered 2/11, 2018 at 10:17 Comment(0)
F
-4

Not only for VS but nearly for all editors.

(function /* RegionName */ () { ... })();

Warning: has disadvantages such as scope.

Fabriane answered 1/7, 2015 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.