Moving Lines
There are several ways to move lines around in Vim. Twitter follower @0_void_ reminded us that ddp
will move the current line down one. This, of course, is native Vim functionality: dd
removes the current line and p
pastes it below. Replace the p
with P
and you put the line back where it was, as P
pastes above. (You should follow @vim_tricks on Twitter: lots more tips and conversations happening there.)
I also use some handy mappings to make moving chunks of lines up or down even easier, these came courtesy of reader Steve Carol:
nnoremap <c-j> :m .+1<CR>==
nnoremap <c-k> :m .-2<CR>==
inoremap <c-j> <Esc>:m .+1<CR>==gi
inoremap <c-k> <Esc>:m .-2<CR>==gi
vnoremap <c-j> :m '>+1<CR>gv=gv
vnoremap <c-k> :m '<-2<CR>gv=gv
Add these to your .vimrc
to allow moving the current line down or up with Ctrl-j
and Ctrl-k
. They work in both visual mode and insert mode. Plus, you can visual select multiple lines and then move the whole chunk the same way:
Ctrl-j
– Move current line downCtrl-k
– Move current line up
When is this useful? Well, anywhere really — it’s great for moving methods around. But I use this a lot when doing a Git interactive rebase. These mappings make it a breeze to adjust the order of my commits to exactly how I want.
Here’s a quick gif of these mappings in action:
