Searching with / and ?

Vim · Essentials · 8 min

Search is the fastest way to move to anything you can see or remember, and it powers substitution.

Type / followed by a pattern and Enter to search forward, ? to search backward. Then:

  • n jumps to the next match in the same direction, N in the opposite direction.
  • * searches forward for the whole word under the cursor, # backward.
  • / followed by just Enter repeats the last search.

The pattern is a Vim regular expression: /^def finds lines starting with def, /foo\|bar finds either word (in Vim's default "magic" mode, | needs a backslash). \< and \> match word boundaries, which is what * adds for you.

A few options make search much nicer; put them in your vimrc:

  • set incsearch shows the match while you type.
  • set hlsearch highlights all matches; :nohlsearch (:noh) clears the highlight until the next search.
  • set ignorecase smartcase makes searches case-insensitive unless you type a capital letter.

Search is also a motion, so it combines with operators: d/end deletes up to (not including) the next end, and c/) changes everything up to the next parenthesis. Every jump you make with search is recorded in the jump list; Ctrl-o takes you back to where you were and Ctrl-i forward again.

Example

/TODO        " jump to the next 'TODO'
n            " next match
N            " previous match
*            " search the word under the cursor
/\<id\>      " whole word 'id' only, not 'width'
d/return     " delete from cursor up to 'return'
Ctrl-o       " jump back to where you started
:noh         " clear the search highlight

Remember

  • / forward, ? backward, n/N next/previous, * word under cursor
  • set incsearch hlsearch ignorecase smartcase
  • Ctrl-o jumps back after a search took you somewhere

Watch out for

  • Forgetting that . and * are regex characters: /a.b also matches axb. Escape them as \. when you mean a literal dot.

Check yourself

  1. With `ignorecase` and `smartcase` set, which search is case-sensitive?
  2. What does `d/foo` delete?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/pattern.txt.html