Learn Practice Daily golf Reference

How to move a line up or down in Vim

In Normal mode, ddp swaps the line with the one below it and ddkP with the one above. Or type :m+1 and press ↵ to move it down one, :m-2 and ↵ to move it up one.

Try it here

Put the checklist in order

The tests run before the build, and the tag comes before publishing. The cursor is on the build line: ddp moves it down one. Then go down to the tag line and move it up one with ddkP.

1 of 2Move the build line down one with ddp
1## Release checklist
2- Build the package
1- Run the tests
+- Build the package
2- Publish to npm
3- Tag the release
4- Announce it
NORMALLoading the editor…1/20.0s2:1

This editor needs a keyboard. Read on, and play it at your computer.

KeysWhat it does
ddpMove the line down one (swap it with the line below).
ddkPMove the line up one. On the last line, use ddP (see below).
:m+1 ↵Move the line down one.
:m-2 ↵Move the line up one, on any line.
:m0 ↵Move the line to the top of the file.
:m$ ↵Move the line to the bottom of the file.
:m12 ↵Move the line to below line 12.
:5,8m12 ↵Move lines 5 to 8 to below line 12.
:'<,'>m'>+1 ↵In Visual mode: move the selected lines down one (press : and Vim types the '<,'> for you).
V, extend, d, move, pMove a selection of lines anywhere you can walk to.

How ddp and :m work

ddp is two commands. dd cuts the line, the line below takes its place under the cursor, and p puts the cut line back below that one: the two have swapped. ddkP cuts the line, steps up with k, and puts it back above.

:m (short for :move) moves the line to below the line you name, counted from the current line. +1 is the line below, so :m+1 moves it down one. To move it up one, it has to go below the line two above, so up is :m-2, not :m-1 (which leaves it where it is). 0 means above the first line, so :m0 moves it to the top.

Moving a block, and a mapping for it

With a range in front, :m moves several lines at once: :5,8m12 moves lines 5 to 8 to below line 12. In Visual mode, select the lines with V and press :; Vim fills in '<,'>, the selection, so :'<,'>m'>+1 moves the selection down one and :'<,'>m'<-2 moves it up one.

Many people map that to a key, so a selection can be nudged up and down the file. One common version, for your ~/.vimrc:

  • vnoremap <A-j> :m '>+1<CR>gv=gv
  • vnoremap <A-k> :m '<-2<CR>gv=gv

The gv=gv part reselects the lines, fixes their indentation and selects them again, ready for the next press. Alt keys don't reach Vim in every terminal; if they don't in yours, pick other keys.