How do I search for a pattern and land on a specific line offset from the match?
Answer
/pattern/+N or /pattern/-N
Explanation
Vim's search command accepts an offset that places your cursor on a line relative to the match. The pattern /pattern/+3 finds the match and then moves the cursor 3 lines below it, while /pattern/-2 lands 2 lines above.
How it works
/function/+1 " Land 1 line below the match (the function body)
/function/-1 " Land 1 line above the match
/^class/+0 " Land on the match itself (default)
/pattern/e " Land on the end of the match
/pattern/b+2 " Land 2 characters after the beginning of the match
Example
You want to jump to the line after each function definition:
/^func /+1
This finds func at the start of a line and positions your cursor on the next line — the first line of the function body.
Other offset types
| Offset | Effect |
|---|---|
/pat/+N |
N lines below match |
/pat/-N |
N lines above match |
/pat/e |
End of the match |
/pat/e+N |
N characters after end of match |
/pat/b+N |
N characters after beginning of match |
/pat/s-N |
N characters before start of match |
Tips
- Offsets persist for
nandN— each subsequent match uses the same offset - Reset by searching without an offset:
/pattern - Works with
?(backward search) too:?pattern?+2 - This is especially powerful in substitute commands: they use the same offset semantics
- Documented under
:help search-offset