Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the order of line fragments within a visual block in Vim?

Tags:

vim

I would like to reverse the order of line fragments selected within a Visual Block in vim. That is, starting from

one   = [33];
two   = [22];
three = [11];

I would like to get,

one   = [11];
two   = [22];
three = [33];

by selecting the block of

         33
         22
         11

and reversing the line order only within this block.

Can this be achieved? I tried using !tac, as described in a related question, but that reversed entire lines, not just the selected block.

like image 757
Ted Pudlik Avatar asked Sep 11 '18 22:09

Ted Pudlik


People also ask

How do I reverse the order of lines in Vim?

command! -bar -range=% Reverse <line1>,<line2>g/^/m0|nohl " REVERSE line ordering, and move those lines to the top of the file.

How do I use visual block mode in Vim?

To enable the Visual block mode in Vim, you have to try out the “Ctrl+V” command within the normal mode. You can see that the new. txt file has been opened in the Visual Block mode.

How do I switch lines in Vim?

To swap the current line with the next one, type ddp while in command mode.

How do I select a block of code in Vim?

Press v to begin character-based visual selection, or V to select whole lines, or Ctrl-v or Ctrl-q to select a block. Move the cursor to the end of the text to be cut/copied. While selecting text, you can perform searches and other advanced movement. Press d (delete) to cut, or y (yank) to copy.


1 Answers

There's a plugin called "vis" that tries to do exactly what you're looking for: https://github.com/vim-scripts/vis

After installing it, you can select the columns in visual mode and execute :B sort to sort just that area.

As an unfortunate side effect, I seem to be getting extra spacing around the selection:

one   = [ 11 ];
two   = [ 22 ];
three = [ 33 ];

This might be some oddity in my own Vim config, or it might be a general issue. I'd suggest you try the plugin and see for yourself.

like image 193
Andrew Radev Avatar answered Oct 12 '22 17:10

Andrew Radev