vimtricks.wiki Concise Vim tricks, one at a time.

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+1 moves the current line down one line (same as :m.+1).
  • :m-2 moves the current line up one line.
  • :m0 moves the current line to the very top of the file.
  • :m$ moves the current line to the very end of the file.
  • :5m10 moves line 5 to after line 10.
  • :5,8m15 moves 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:

  1. Select lines with V.
  2. Type :
  3. 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.

Next

How do you yank a single word into a named register?