前言javascript
Visual Studio的代碼摺疊功能很是好用,#region #endregion 這個詞連搜狗的詞庫裏面都出現了(不含'#'號),可見使用頻率很高,可是他不支持js的代碼摺疊 : ( 最近Ext用得比較多,一寫就是上百行JS代碼,很是不方便,想着本身寫個擴展或插件什麼的,意外搜到了下面的文章,已經用宏來實現了,本文能夠理解爲該文的簡單譯本,注意宏代碼部分我有所改動 : )
html
文章java
1. Using #region Directive With JavaScript Files in Visual Studioide
環境工具
Microsoft Visual Studio 2008oop
正文spa
1. 打開宏資源管理器:視圖 -> 其餘窗口 -> 宏資源管理器.net
![](http://static.javashuo.com/static/loading.gif)
2. 建立一個新模塊
插件
![](http://static.javashuo.com/static/loading.gif)
3. 編輯宏: 選中模塊 -> 右鍵編輯
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()
'
農民伯伯 --- 自動爲"//#endregion"結束的代碼添加最後一行,否則出錯
If
selection.Text.EndsWith(REGION_END)
Then
selection.EndOfLine()
selection.NewLine()
selection.SelectAll()
End
If
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
保存便可。這裏能夠省去新建宏的步驟,他會根據代碼自動給你生成一個宏的。
注意我加的代碼段,若是不加,而且你的JS最後一行爲#endregion,宏將報錯,顯示「值不在預期的範圍內」。
4. 設置快捷鍵
4.1 工具 -> 選項 - > 環境 -> 鍵盤
4.2 在顯示命令包含下面的文本框中輸入宏名outli,不用輸全,下面能顯示你新建的宏
4.3 點一下 按快捷鍵 下面的文本框, 而後自定義快捷鍵組合,我定義的是Ctrl+M,Ctrl+J,點分配(別忘了!),點肯定。
5.效果
5.1 輸入代碼:
//
aasdsadsad
//
#region
//
#endregion
5.2 快捷鍵Ctrl+M,Ctrl+J啓動宏,能看到系統的右下角顯示可愛的小方塊在轉動,js編輯框顯示效果以下:
![](http://static.javashuo.com/static/loading.gif)
5.3 以後就能夠用快捷鍵Ctrl+M,Ctrl+L來[展開/摺疊]代碼了,注意關閉以後從新打開須要再啓動一次宏,展開效果以下:
結束
想到不如作到,但作以前要是能先Google一下也許能事半功倍: )