Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort using statement of C# code in vim?

Tags:

c#

vim

stylecop

Recently I edit C# code in vim. And the build system has StyleCop enabled so that all using statement should be in alphabetical order.

So, I tried to select below lines of code in visual mode, then type ":sort".

using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Security;
using System.ServiceModel;

The result is:

using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Security;
using System.ServiceModel;

It doesn't pass StyleCop checking because "System.Security" is not ahead of "System.Security.Permissions". The ASCII value of ";" is larger than ASCII value of ".".

The preferred result is:

using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.ServiceModel;

How to achieve it?

like image 251
Morgan Cheng Avatar asked Dec 09 '09 10:12

Morgan Cheng


People also ask

How do you sort a statement in C#?

Select Edit from the menu bar. Select Intellisense > Sort Usings. You can also configure different settings for using directives in Tools > Options > Text Editor > C# > Advanced.

How do I sort text in Visual Studio?

Shift + Alt + L , Shift + Alt + S => Ascending sort. Shift + Alt + L , Shift + Alt + S (same selection same keys) => Descending sort.

How do I get rid of unused codes in Visual Studio?

First is putting your cursor on one of the grayed out lines and clicking the light bulb, then clicking Remove Unnecessary Usings. (NOTE: The shortcut key for this is CTRL-.)


2 Answers

:h :sort is your friend:

:[range]sort r /[^;]*/

If along the way you wish to remove duplicates, add the uniq flag:

:[range]sort ur /[^;]*/

(This won't do any good if you have different comments after the ';' though)

like image 169
Luc Hermitte Avatar answered Oct 11 '22 08:10

Luc Hermitte


:1,4s/;$//
:sort
:1,4s/$/;/

(where 1,4 are lines with using statements)

like image 26
nothrow Avatar answered Oct 11 '22 07:10

nothrow