Shift lines and selections faster with vim-move
One of my students showed me a cool Sublime Text feature that made editing a bit more efficient than Vim: Instead of moving lines by deleting them with dd, jumping to the desired location and pasting them, he just had to press a key combination. Because it looked so intuitive, I had to figure out how to emulate that with Vim.
First thing I stumbled upon and never knew before, is the :m[ove]
command.
It takes a range (or the current line) and moves the lines in that range to some
target “address”. The simplest possible movement is the :m+1
shortcut, that
swaps the current line with the one right below. Typing the command manually is
a chore but mapping that command and its inverse :m-2
is pretty
straightforward once you take care of the top and bottom boundaries. Moving
whole selections up and down is more interesting. Fortunately, you can get
easily retrieve selected range in a function and adaptively call :m
.
To make these mappings more manageable, I wrote a simple but pretty effective
plugin called vim-move. Put the matze/vim-move
repo into your Vundle
bundle and this is what you get:
By default, alt+k and alt+j move the current line in normal mode1 whereas ctrl+k and ctrl+j shift a selection in visual mode. You can prefix the calls with a count, e.g. 5ctrl+j which will then shift the line or selection relative by that number. To remap the keys you should
let g:move_map_keys = 0
and then map the keys, for example
vmap <C-j> <Plug>MoveBlockDown
vmap <C-k> <Plug>MoveBlockUp
nmap <A-j> <Plug>MoveLineDown
nmap <A-k> <Plug>MoveLineUp
Hope you like the plugin. If you have any suggestions or problems, open an issue on the issue tracker.
In some environments I have to use the GNOME terminal and need to re-map the normal mode keys because I am not able to stop the terminal from intercepting the alt key. If you know how to let the GNOME terminal use the alt key, I’d pay you a beer. Update: you can keep your wallets closed ;-)