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

How do I limit a search pattern to a specific line range without using :global?

Answer

/\%>10l\%<20lTODO

Explanation

Vim regex supports position atoms that can constrain where a match is allowed to occur. With \%>10l and \%<20l, you can search only inside lines 11 through 19 without changing the buffer or creating temporary folds, marks, or ranges. This is a fast way to scope navigation when you already know the rough region that matters.

This pattern is useful during large refactors where the same token appears everywhere but only one section is relevant. Instead of repeatedly jumping across unrelated matches, constrain the search itself and keep / navigation focused.

How it works

/\%>10l\%<20lTODO
  • \%>10l means the match must start after line 10
  • \%<20l means the match must start before line 20
  • TODO is the actual text you are searching for
  • Combined, the search operates only within a bounded line window

Example

Given:

 1 TODO global
...
11 TODO target-a
15 TODO target-b
20 TODO global-again

Searching with /\%>10l\%<20lTODO matches lines 11 and 15, but skips lines 1 and 20.

Tips

  • Swap TODO with any regex pattern, not just literal text
  • You can combine line atoms with column atoms like \%>5c for tighter targeting
  • For reusable workflows, map a command that prompts for bounds and builds the pattern dynamically

Next

How do I list only search-pattern history entries in Vim?