sponsor Vim development Vim logo Vim Book Ad

basic Tip #588: How to sort using visual blocks

 tip karma   Rating 220/68, Viewed by 10213 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   October 16, 2003 9:08      complexity:   basic
author:   Charles E. Campbell      as of Vim:   6.0

1. To sort lines based on a visually-selected column:

Check out
http://www.erols.com/astronaut/vim/index.html#VimFuncs ;
look under "Visual Block Sorting".  It uses Piet Delport's
vim-based binary insertion sort and some vim-glue to provide
visual-block sorts!

To enable it, put <bisort.vim> into your <.vim/plugin>
directory.

To then perform sorting based on a visual-block selection
(ctrl-v):

:'<,'>Vissort

2. To sort a visually-selected block (and leave the text outside the
   block in place):

Check out
http://www.erols.com/astronaut/vim/index.html#VimFuncs ;
look under "Visual Block Commands".  The <vis.vim> plugin
provides a command which allows other commands to be applied
only to the visually selected block.

To then perform sorting of just a visual-block (ctrl-v):

:'<,'>B !sort

Or, using Piet Delport's binary insertion sort:

:'<,'>B Bisort

Examples:

Original, visual-block select the central column
one   two    three
four  five   six
seven eight  nine
ten   eleven twelve

:'<,'>Vissort
seven eight  nine
ten   eleven twelve
four  five   six
one   two    three

:'<,'>B !sort
one   eight  three
four  eleven six
seven five   nine
ten   two    twelve

:'<,'>B Bisort
one   eight  three
four  eleven six
seven five   nine
ten   two    twelve

 rate this tip  Life Changing Helpful Unfulfilling 

<< Preview current file in Mozilla through localhost | Vim as refactoring tool (with examples in C#) >>

Additional Notes

[email protected] - NOSPAM, January 22, 2004 7:33
vissort has been updated to version 3: it now has BlockSort() which permits one
to sort blocks of text based on tags contained within them.
[email protected], May 15, 2004 4:49
For Windows users only. Visual blocking --in general-- is done with Ctrl-q. Do not use the arrow key to make the block, use only h-j-k-l.
[email protected] - NOSPAM, November 29, 2004 7:26
My website has changed from erols to:

   http://mysite.verizon.net/astronaut/vim/...

Unfortunately I cannot update the tip's text itself (yet).
anon, March 29, 2006 15:33
On this website there are only files for Vim 7 beta, what about script for v. 6.4?
twiki AT sepp DOT de, September 12, 2006 6:29
Cool, I've inserted into the PopUp menu of GVIM on Windows:

edit menu.vim
...
" The popup menu
...
vnoremenu 1.51 PopUp.&Sort; :Vissort<CR>
...

And use it completely by mouse.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
SourceForge.net Logo