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 down
  • Ctrl-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 launch an email course called Git Better with Vim. 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.

Okay, 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!

How useful was this tip?

Average rating 3.8 / 5. Vote count: 139

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

102 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts