Tzu ng
Tzu ng

Reputation: 9244

Sort in block in vim

I'm looking for a way to sort in selected block in Vim. The scenario is I have something like this

{:a
 :c 
 :b}

# after sort, it should be 
{:a
 :b
 :c}

How I do it now is I have to enter :a and :c to new lines, running sort on selected block and then put the brackets back later. I'm looking for a way to sort without doing this extra operation.

Upvotes: 3

Views: 657

Answers (3)

Ingo Karkat
Ingo Karkat

Reputation: 172600

Here's one way with Ex commands. Sorting of ranges is pretty easy with :global and :sort. The following command sorts the lines between those delimited by curly braces:

:g/^{/+1,/^}/-1sort

But the complication here is that (in your example), the enclosing braces are on the same (first, last) lines as the data. We need to separate them out to adjacent lines first, and later undo that. :substitute can do that:

:%s/{\zs\|\ze}/\r/g
:g/^{/+1,/^}/-1sort
:%s/{\zs\n\|\n\ze}//g

Upvotes: 1

Meitham
Meitham

Reputation: 9670

One way you can do this is by reading the inner of the braces into a register.

"ayi{

This will copy the content, the lines, without the braces around them.

Then you can run that into the sort function

sort(split(getreg('a')))

This requires the modifiable flag to be set, as you're changing a non visible buffer. It sorts the buffer a in place. You could then paste that inside the braces vi{"ap.

Obviously you should put the while thing in a function/macro or command.

Upvotes: 1

axwr
axwr

Reputation: 2236

The following will reduce your effort slightly but still doesn't resolve it completely, basically it will sort based on what comes after the colon, then remove the brackets but it doesn't insert them again for you:

:'<,'>sort /^.\{-}:/ |%s/{\|}//g

Hope it helps, happy vimming.

Upvotes: 1

Related Questions