Share via


SortLines macro for Visual Studio

Ever want to quickly alphabetize a part of your code? I couldn't for the life of me find a way to do this within Visual Studio, so ended up writing my own. 

Here's a macro that you can use (and bind to a keyboard shortcut) within your own Visual Studio environment:

Sub SortLines()
    Dim selection As EnvDTE.TextSelection = ActiveDocument.Selection
    Dim editPoint As EnvDTE.EditPoint = selection.TopPoint.CreateEditPoint

If (selection.TopPoint.Line = selection.BottomPoint.Line) Then
     Return
    End If

Dim bottomLine = selection.BottomPoint.Line
If (selection.BottomPoint.AtStartOfLine)
Then
bottomLine = bottomLine - 1
End If

Dim selectedText = editPoint.GetLines(selection.TopPoint.Line, bottomLine + 1)
Dim lines = selectedText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)

Array.Sort(lines)

DTE.UndoContext.Open("Sort Lines")

Try
selection.MoveToLineAndOffset(selection.TopPoint.Line, 1)
selection.MoveToLineAndOffset(bottomLine, 1, True)
selection.EndOfLine(True)
selection.Delete()

For i = LBound(lines) To UBound(lines)
selection.Insert(lines(i))
If (i < UBound(lines)) Then
selection.NewLine()
selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn)
End If
Next
Finally
' If an error occurred, then make sure that the undo context is cleaned up.
' Otherwise, the editor can be left in a perpetual undo context.
DTE.UndoContext.Close()
End Try
End Sub

To "install" a macro in Visual Studio:

  1. Launching the Macro Explorer from the Tools menu.
  2. You'll likely have a module created automatically for you on first run, but if not, you can create one. (I call mine "EditingEnhancements".)
  3. Copy the macro from the list below to your module.
  4. Bind it to a keyboard shortcut of your own choosing.  
    1. From Tools->Options, choose General/Keyboard.
    2. Search for the macro name that you just saved to your macros
    3. Bind it to the keyboard shortcut of your choosing.

Hope you find this useful!