tags:

views:

121

answers:

4

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?

A: 

Not using CodeRush or ReSharper is stealing from your employer

<ducks for downvotes>

(Yes, I know that requires VS (and AFAIK VS10 has this OOTB))

Ruben Bartelink
Are CodeRush and ReSharper available for vim? Wow...
Konamiman
@Konamiman: No, but if I for some reason felt I had to use vim, I'd shell out to VS to get either of them
Ruben Bartelink
There are a lot of microsoftees work with VIM rather than VS like me:)
Morgan Cheng
@Morgan: I know - only yanking chains. (Although I find it very hard to imagine myself in a parallel universe, coding away in a language that grabs its ankles for you to use a refactoring tool and then wilfully ignoring it.) Yes I understand that VS can hardly be described as a scriptable editor. Maybe reading Clean Code, APPP, Refactoring and using xunit.net and CR have just warped my worldview too much :P
Ruben Bartelink
+1  A: 
:1,4s/;$//
:sort
:1,4s/$/;/

(where 1,4 are lines with using statements)

Yossarian
This is a solution, even though it takes a lot of typing:)
Morgan Cheng
Try this one (select your using statements and press F5)::map <F5> :s/;/ /g<cr>gv:sort<cr>gv:s/ /;/g<cr>
Habi
A: 

On my linux box with a local other than C (tested fr_FR, fr_FR.UTF-8, en_US, en_GB), the sort command sorts as you expect. You could very well pipe to the sort command :

:1,4!sort

If you are on windows, I suppose you can install unix tools (like SFU) that could do the job since vim's sort command doesn't seem to handle locale.

Etienne PIERRE
Windows has a sort command.
Alex
+5  A: 

: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)

Luc Hermitte
Thanks. To make it better, we can remove duplicate using statements with::[range]sort ur /[^;]*/
Morgan Cheng
Of course we can. I edit the response.
Luc Hermitte