How do I move a line or range of lines to a different location in the file?
Answer
:m {address}
Explanation
How it works
The :m command (short for :move) moves one or more lines to after the specified address. Unlike :t (copy), :m removes the lines from their original position. The syntax is:
:[range]m {address}
Common forms:
:m+1moves the current line down one line (same as:m.+1).:m-2moves the current line up one line.:m0moves the current line to the very top of the file.:m$moves the current line to the very end of the file.:5m10moves line 5 to after line 10.:5,8m15moves lines 5 through 8 to after line 15.
The key benefit of :m over delete-paste (dd then p) is precision: you can specify exact source and destination line numbers and the operation does not pollute your registers.
Example
Suppose you have:
1: import os
2: import sys
3: import json
4:
5: def main():
To move the import json line to be the first import:
:3m1
Result:
1: import os
2: import json
3: import sys
4:
5: def main():
To move a visually selected block of lines to the end of the file:
- Select lines with
V. - Type
: - Complete:
:'<,'>m$
Comparison with :t
| Command | Action |
|---|---|
:m |
Moves lines (cut and paste) |
:t |
Copies lines (copy and paste) |
Both commands use the same address syntax and neither affects registers, making them ideal for reorganizing code without disrupting your yank history.