這是一個基本的「Align Properties」宏,用於演示如何使用Visual Studio宏來完成這種類型的功能。
Sub AlignProperties()
Dim win As EnvDTE.Window = DTE.ActiveWindow
If win.Type <> EnvDTE.vsWindowType.vsWindowTypeDocument Then
MsgBox("This macro can only be run in an active text editor window.")
Exit Sub
End If
' Determine the affected lines.
Dim startLine As Integer = DTE.ActiveDocument.Selection.TopLine
Dim endLine As Integer = DTE.ActiveDocument.Selection.BottomLine
If endLine < startLine Then
Dim temp As Integer = startLine
startLine = endLine
endLine = temp
End If
endLine = endLine - 1
' Parse the four columns: modifier, type, identifier, and rest.
Dim regex = New Regex("(\s+)(.*)\s+(.*)\s+(.*)\s+({.*)")
Dim leading As String = Nothing
Dim array(endLine - startLine, 3) As String
Dim widths(3) As Integer
For i As Integer = 0 To endLine - startLine
DTE.ActiveDocument.Selection.GotoLine(startLine + i)
DTE.ActiveDocument.Selection.SelectLine()
Dim line As String = DTE.ActiveDocument.Selection.text()
Dim match As Match = regex.Match(line)
If leading = Nothing Then
leading = match.Groups(1).ToString()
End If
For j As Integer = 0 To 3
Dim text As String = match.Groups(j + 2).ToString()
array(i, j) = text
widths(j) = Math.Max(widths(j), text.Length)
Next
Next
widths(3) = 0
' Align the four columns.
DTE.UndoContext.Open("Align Properties")
Try
For i As Integer = 0 To endLine - startLine
DTE.ActiveDocument.Selection.GotoLine(startLine + i)
DTE.ActiveDocument.Selection.SelectLine()
Dim line As String = DTE.ActiveDocument.Selection.text()
Dim replacement = leading
For j As Integer = 0 To 3
Dim padded As String = array(i, j).PadRight(widths(j) + 1)
replacement = replacement & padded
Next
DTE.ActiveDocument.Selection.text() = replacement
Next
Finally
DTE.UndoContext.Close()
End Try
End Sub
前:
後:
爲什麼?你應該總是使用團隊選擇的編輯器,否則當下一個人工作時,它會變得非常糟糕。原文很好,代碼是一個故事,而不是電子表格。投注也習慣了 – TFD 2011-09-25 23:18:39
正如已經提到的那樣,對齊代碼並不是一種好的代碼風格(糟糕的可讀性)。其中一個原因是,如果使用製表符對齊,則其他系統上的代碼可能看起來很糟糕。這是因爲製表符是由系統定義的。如果您使用四個空格作爲製表符,則其他人可以使用3個空格作爲製表符。因此,請確保您打開Visual Studio編輯器選項以將製表符轉換爲空格。 – Alexander 2011-09-27 08:40:17