1

Is it possible to move selected lines up and down?

c = 3
a = 1
b = 2

I would like to select second and third lines and move them one line up, so that result be:

a = 1
b = 2
c = 3

I know that > and < moves lines right and left, but how to move them up and down?

0
2

You can do this with the :move ex command:

:2,3m0

In the above, 2,3 is a range which specifies which lines we want to move, m is an abbreviated form of the :move command, and 0 is an address which specifies where we want the lines to move to.

3
  • Is it possible to move relatively? Because I use rnu instead of nu and know only relative line numbers. – niekas Feb 25 at 10:03
  • @niekas It's possible to :move relative to the cursor, but not relative to the thing you're moving. e.g. :2,3m-8 will move lines 2 and 3 to be below the line that is 8 lines before the cursor; it won't move the lines 8 lines upwards (unless your cursor happens to be in the position where that's the same thing). – Rich Feb 25 at 10:11
  • Thats just great, I have tried :2,3m+8 and :2,3m-8 and they both work relatively. If I don't add a sign before the number, e.g. :2,3m8 it works with absolute line numbers. Would be nice to see this clarification in the answer :) – niekas Feb 25 at 10:15
2

You can select the lines with entering visual line mode V, deleting with d and pasting with p (after the cursor) or P (before the cursor). But if you need this often I highly recommend to read/watch Vimcasts episode #26 "Bubbling Text", which introduces two generic solutions with keybindings:

" Bubble single lines
nmap <C-Up> ddkP
nmap <C-Down> ddp
" Bubble multiple lines
vmap <C-Up> xkP`[V`]
vmap <C-Down> xp`[V`]

The second binding needs the excellent plugin unimpaired by Tim Pope:

" Bubble single lines
nmap <C-Up> [e
nmap <C-Down> ]e
" Bubble multiple lines
vmap <C-Up> [egv
vmap <C-Down> ]egv

Not the answer you're looking for? Browse other questions tagged or ask your own question.