开发者

Sort selected text from Visual Studio context menu

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?


VS 2019 & VS 2022:

  1. Select lines. The last selected line is where the cursor is - the line is taken into account even if it is empty and there is no visible selection.
  2. Shift + Alt + L, Shift + Alt + S => Ascending sort.
  3. Shift + Alt + L, Shift + Alt + S (same selection same keys) => Descending sort.

The command can also be invoked from menu (@sharpener): Edit | Advanced | Sort Lines


A nice AddOn for Visual Studio is Code Maid

You select some lines and chose from Context Menu "Sort Lines"

Sort selected text from Visual Studio context menu

And voilá, your lines are sorted nicely in alphabetical order:

Sort selected text from Visual Studio context menu


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


Just found a good free addon: Menees VS Tools 2012 (or 2010 ver) - does exactly that and a few more text tricks. There was a few minor negatives when I installed it, but after leaving a comment on the review page it got fixed within days. Waay to go! =)

There is a 2017 version now: Menees VS Tools 2017


This comes up at the top of searches still so I'll add this latest solution. If you are running a current VS Code (and why wouldn't you?) you can use the built-in sorter by hitting ctrl-shift-p (Mac is cmd-shift-p) and type "sort" in the subsequent search box. There are many options.


You can copy the code into Sublime Text, select the section of code and hit F9 (or go to Edit > Sort Lines). You can then copy it back into Visual Studio.


I am personally using the Web Essentials extension by Mads Kristensen. You just select the lines you want to sort and Alt+3 or Alt+4 (asc/desc).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜