如何使用Visual Studio中的空格自动对齐类似的代码行

时间:2011-01-27 12:01:20

标签: c# vb.net visual-studio

是否有现有的宏或插件可以改变这个

public string Name { get; set; }
public int Age { get; set; }
public Person Mother { get; set; }

进入这个?

public string Name   { get; set; }
public int    Age    { get; set; }
public Person Mother { get; set; }

我将描述我认为直观明显的算法 - (对于特定的选择)使每个令牌尽可能地留在一条线上,但不要比任何一个更左边任何其他行上相同索引的标记。

2 个答案:

答案 0 :(得分:12)

这是一个原始的“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

在:

Before

后:

After

答案 1 :(得分:10)

不是一个完整的解决方案,但Productivity Power Tools有类似的名称为“对齐作业”:

  

这个扩展名对于通过在键入Ctrl + Alt +]时对齐分配来使代码更具可读性非常有用,这样就可以:

_test = test;
_commandTarget = commandTarget;
_state = state;
     

把它变成这个:

_test          = test;
_commandTarget = commandTarget;
_state         = state;