“Bubble” Lines Up And Down Like Sublime Text In Vim
NB: You can see this hack in my .vim
repo on GitHub.
Sublime Text allows you to use ^⌘↑ and ^⌘↓ to “bubble” a selected block of text up and down in a file.
For a single line, we could just use the dd
, j
, p
and P
motion and editing commands to move the current line around:
However, this doesn’t work for multiline selections and it overwrites the default register, wiping anything you’ve previously deleted to there.
A better solution is to use the :move
command. We can safely use it in both normal and visual mode because it works with multiline blocks:
We pass locations relative to the selection to :move
, '<-2
is 2 lines before the first line of the selection, '>+1
is one line after the last line.
In the visual mode mappings, we use gv
to return to visual mode with the previous selection highlighted after the :move
is complete.
By default, MacVim maps ^⌘↑ and ^⌘↓ to move around the quickfix list. We can disable that by setting the menu option’s key to <nop>
. Add this to your .gvimrc
:
If you hit ^⌘↑ or ^⌘↓ with a character-wise visual selection, the whole line will still be moved.
You can map different keys for different platforms.
We can also extend this to fix indentation of the block as you move it:
This is a bit unpredictable in my experience. YMMV.