How do I land the cursor a few lines above or below a search match?
Answer
/pattern/+3
Explanation
Vim's search command accepts an offset after the pattern that shifts where the cursor lands relative to the match. Instead of landing directly on the matched text, you can position the cursor a specific number of lines above or below, or even a number of characters to the right or left of the match.
How it works
/pattern/+Nplaces the cursorNlines below the match/pattern/-Nplaces the cursorNlines above the match/pattern/eplaces the cursor at the end of the match instead of the beginning/pattern/e+Nplaces the cursorNcharacters after the end of the match/pattern/b+Nplaces the cursorNcharacters after the beginning of the match- The offset applies to every subsequent
nandNjump as well — it's sticky
Example
Given a file where functions are preceded by doc comments:
// Calculates the total price
// including tax and discounts
function calculateTotal(items) {
let sum = 0;
return sum;
}
Searching with /function/+1 lands the cursor on the let sum = 0; line — one line below the match. This is useful when you want to jump into the body of a function rather than its signature.
Searching with /function/-1 would land on the last comment line above the function.
Tips
- Use
/pattern/eto land at the end of the match — perfect for appending text right after a keyword - The offset is remembered: pressing
nafter/pattern/+3will continue to land 3 lines below each subsequent match - Clear the offset by searching again without one:
/patternresets to landing directly on the match - Offsets work with
?(backward search) too:?pattern?-2searches backward and offsets - Combine with substitution patterns: after
/pattern/+2, you can use:.s/old/new/to substitute on the offset line - Use
/pattern/e+1to position the cursor one character after the match ends — great for inserting text immediately after a keyword