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

How do I search backward in Vim?

Answer

?pattern

Explanation

The ?pattern command searches backward through the file for the given pattern, starting from the cursor position and wrapping around to the end of the file if no match is found before the beginning.

How it works

  • Press ? to enter backward search mode — the cursor moves to the command line with a ? prompt
  • Type your search pattern and press <CR> (Enter)
  • Vim moves the cursor to the nearest match above the current position
  • Press N to continue searching backward (same direction) or n to search forward (opposite direction)

Example

Given the text with the cursor on the last line:

The quick brown fox
jumps over the lazy dog
the end of the story

Typing ?the<CR> moves the cursor backward to the on the second line. Pressing N jumps to The on the first line (if ignorecase is set).

Tips

  • Use /pattern to search forward instead — the counterpart to ?
  • After a ? search, n goes backward (same direction) and N goes forward (opposite direction) — this is reversed compared to / searches
  • Use ?\<word\> to match whole words only
  • Use ?\Cpattern to force a case-sensitive search
  • Use ?\cpattern to force a case-insensitive search
  • Press ?<CR> (with no pattern) to repeat the last backward search
  • Use :set hlsearch to highlight all matches in the file
  • Press # as a shortcut to search backward for the word under the cursor

Next

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