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

How do I use relative line offsets in Ex commands to target lines near the cursor?

Answer

:.+1,.+3d

Explanation

Vim's Ex command addresses support arithmetic offsets relative to the current line (.), allowing you to target lines above or below the cursor without counting manually or entering visual mode. This is especially powerful for quick surgical edits when you know exactly how many lines away your target is.

How it works

  • . refers to the current line
  • .+N refers to N lines below the current line
  • .-N refers to N lines above the current line
  • You can combine these into ranges: .-2,.+2 means "from 2 lines above to 2 lines below"
  • The . is optional when using + or - alone: +1,+3d is equivalent to .+1,.+3d

Example

Delete the 3 lines immediately below the cursor (leaving the current line intact):

:.+1,.+3d
Before (cursor on line 2):
  line 1
  line 2      <- cursor here
  line 3
  line 4
  line 5
  line 6

After:
  line 1
  line 2
  line 6

Copy lines 2 above through 2 below to the end of the file:

:.-2,.+2t$

Move the line 1 below the cursor to 5 lines above:

:.+1m.-5

Tips

  • Combine with :g for powerful patterns: :g/TODO/.-1,.+1d deletes each TODO line plus its surrounding lines
  • Works with all range-accepting commands: :d, :y, :m, :t, :s, :!
  • Use /pattern/+2 to offset from a search match: :/func/+1,/^}/d deletes inside a function body

Next

How do I ignore whitespace changes when using Vim's diff mode?