Sort selected text from Visual Studio context menu

abatishchev picture abatishchev · Jul 28, 2010 · Viewed 22.8k times · Source

Currently VS has a very useful feature: sort usings (C#).

I want the same functionality for any random text, for example - XML nodes in config files.

How complex to implement that? VS addin, right? Is it possible to call some VS API which is used for sorting usings?

Answer

Tim Robinson picture Tim Robinson · Jul 28, 2010

Edit: Note that this solution does not work on VS2013 or higher, since support for macros was removed.

You don't necessarily need to code a VS addin to do this: Visual Studio has macros built in. To get started, use Tools, Macros, Record Temporary Macro.

Here's a 'Sort Lines' command I hacked together based on the code that Record Temporary Macro gave me:

Imports System
Imports EnvDTE

Public Module TimModule
    Sub SortLines()
        Dim Selection As TextSelection = DTE.ActiveDocument.Selection
        Dim Lines() As String = Selection.Text.Replace(Environment.NewLine, Chr(13)).Split(Chr(13))
        Array.Sort(Lines)
        DTE.UndoContext.Open("Sort Lines")
        ' Edit - see comments
        ' Selection.Text = String.Join(Environment.NewLine, Lines)
        Selection.Delete
        Selection.Insert(String.Join(Environment.NewLine, Lines)) 
        DTE.UndoContext.Close()
    End Sub
End Module