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

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/+N places the cursor N lines below the match
  • /pattern/-N places the cursor N lines above the match
  • /pattern/e places the cursor at the end of the match instead of the beginning
  • /pattern/e+N places the cursor N characters after the end of the match
  • /pattern/b+N places the cursor N characters after the beginning of the match
  • The offset applies to every subsequent n and N jump 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/e to land at the end of the match — perfect for appending text right after a keyword
  • The offset is remembered: pressing n after /pattern/+3 will continue to land 3 lines below each subsequent match
  • Clear the offset by searching again without one: /pattern resets to landing directly on the match
  • Offsets work with ? (backward search) too: ?pattern?-2 searches 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+1 to position the cursor one character after the match ends — great for inserting text immediately after a keyword

Next

How do I edit multiple lines at once using multiple cursors in Vim?