How do I move selected lines up or down in visual mode?
Answer
:'<,'>move'>+1 or :'<,'>move'<-2
Explanation
How it works
Vim's :move command lets you relocate lines to a different position. When combined with visual mode, it becomes a powerful way to rearrange blocks of code.
After selecting lines with V (linewise visual mode), you can:
- Move the selection down one line:
:'<,'>move'>+1 - Move the selection up one line:
:'<,'>move'<-2
When you press : in visual mode, Vim automatically fills in '<,'> which represents the visual selection range. You only need to type move'>+1 or move'<-2.
Here is what the markers mean:
'>is the last line of the visual selection'<is the first line of the visual selection+1means one line after the end of selection (moves down)-2means two lines before the start (moves up, since -1 would place it on itself)
For convenience, you can map these to key shortcuts in your vimrc:
vnoremap J :move'>+1<CR>gv=gv
vnoremap K :move'<-2<CR>gv=gv
The gv=gv part reselects and re-indents the moved block.
Example
Starting text:
line A
line B
line C
line D
- Place cursor on line B, press
V, thenjto select lines B and C - Type
:move'>+1and press Enter
Result:
line A
line D
line B
line C
The selected lines B and C moved down past line D.