views:

25

answers:

1

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?

+1  A: 

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")
        Selection.Text = String.Join(Environment.NewLine, Lines)
        DTE.UndoContext.Close()
    End Sub
End Module
Tim Robinson
You are using TextSelection.Text property to change the text. This is usually a reason of a very slow execution. It may take even several seconds. The better way is to use TextSelection.Insert and Delete methods. I haven't tested it but I recommend to replace line:Selection.Text = String.Join(Environment.NewLine, Lines)with 2 lines:Selection.DeleteSelection.Insert(String.Join(Environment.NewLine, Lines))Then you can place your macro on toolbar or menu (http://www.helixoft.com/blog/archives/7) or assign key shortcut to it (http://www.helixoft.com/blog/archives/8)
Peter Macej
@Peter, thanks. I didn't spend long writing this - if you add an answer to the OP I'll vote it up
Tim Robinson