How do I move a line or selection up or down in Vim?
Answer
:move +1 / :move -2
Explanation
The :move command relocates lines to a specific position without using delete and paste. It preserves registers and is cleaner than dd/p for rearranging code. Combined with mappings, it provides IDE-like line-moving shortcuts.
How it works
:move +1— move current line down one position:move -2— move current line up one position:move 0— move current line to the top of the file:move $— move current line to the end of the file:'<,'>move '>+1— move visual selection down
Example
" Convenient mappings
nnoremap <A-j> :move +1<CR>=="
nnoremap <A-k> :move -2<CR>=="
vnoremap <A-j> :move '>+1<CR>gv=gv
vnoremap <A-k> :move '<-2<CR>gv=gv
Before (cursor on line 2):
line 1
line 2 ← :move +1
line 3
After:
line 1
line 3
line 2
Tips
==after:movere-indents the line to match its new contextgv=gvin the visual mapping reselects and re-indents the moved block:movedoesn't affect any registers — cleaner thandd+p- Alt+J/K mappings mirror VS Code and other editors' line-moving shortcuts