Visual Studio實現JS代碼折疊功能
環(huán)境
Microsoft Visual Studio 2008
正文
1. 打開宏資源管理器:視圖 -> 其他窗口 -> 宏資源管理器
2. 創(chuàng)建一個新模塊
3.編輯宏:選中模塊 -> 右鍵編輯
- 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 = "http://#region"
- Const REGION_END As String = "http://#endregion"
- selection.SelectAll()
- '農民伯伯 --- 自動為"http://#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工具 -> 選項 - > 環(huán)境 -> 鍵盤
4.2在顯示命令包含下面的文本框中輸入宏名outli,不用輸全,下面能顯示你新建的宏
4.3點一下 按快捷鍵 下面的文本框, 然后自定義快捷鍵組合,我定義的是Ctrl+M,Ctrl+J,點分配(別忘了!),點確定。
5.效果
5.1輸入代碼:
- //aasdsadsad
- //#region
- //#endregion
5.2快捷鍵Ctrl+M,Ctrl+J啟動宏,能看到系統(tǒng)的右下角顯示可愛的小方塊在轉動,js編輯框顯示效果如下:
5.3之后就可以用快捷鍵Ctrl+M,Ctrl+L來[展開/折疊]代碼了,注意關閉之后重新打開需要再啟動一次宏,展開效果如下:
結束
想到不如做到,但做之前要是能先Google一下也許能事半功倍。
【編輯推薦】