Sort selected text from Visual Studio context menu

前端 未结 6 1713
忘掉有多难
忘掉有多难 2021-01-03 19:24

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 com

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 20:06

    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
    

提交回复
热议问题