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.
A brief aside:
Are Git-related Vim tips interesting to you? Andy and I are launching an email course called Git Better with Vim on November 1st. This course includes 24 lessons delivered over the course of 12 weeks. The lessons are similar in style to the VimTricks format you know and love, but a little more in-depth and with videos.
For the first 20 preorders, we’re offering 50% off with the code “
subscriber
”. For $14.99 you get a complete course on using Git inside Vim. We will cover everything you need to know to have an incredibly tight and efficient workflow between Vim and Git, including git hosts like GitHub and GitLab. You’ll never need or want to leave Vim!
Here’s a quick gif of these mappings in action:
Thanks to our loyal readers for all the Vim tricks — keep them coming! If you’ve got a useful tip, mapping, or plugin you want to share. Please email us!
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:
Hey there! I've used this in my vim config for about as long as this article has been available. I packaged it into a vim plugin for easy use and redistribution: https://github.com/alichtman/move-lines.vim
This is not working for me on vmi 8 on macos