How do I make Vim's search stop at the end of the file instead of wrapping back to the top?
Answer
:set nowrapscan
Explanation
By default Vim's wrapscan option is enabled, which causes / and ? searches to wrap silently from the end of the file back to the beginning (and vice versa). Setting :set nowrapscan disables this: when no more matches are found forward or backward, Vim reports an error and stops instead of looping.
How it works
:set wrapscan(default) — search wraps around the file end transparently:set nowrapscan— search stops at the file boundary; Vim displays:E385: search hit BOTTOM without match for: pattern(forward search)E384: search hit TOP without match for: pattern(backward search)
- Toggle:
:set wrapscan!(or short::set ws!) - Check current value:
:set wrapscan?
Example
With two occurrences of error on lines 5 and 20, cursor on line 25:
" wrapscan on (default):
/error → jumps to line 5 (wrapped around silently)
" nowrapscan on:
/error → E385: search hit BOTTOM without match
Tips
- Essential for macros and scripts that repeatedly search forward — with
wrapscan, a macro can loop infinitely; withnowrapscan, it stops cleanly when no match remains - Add
set nowrapscanto~/.vimrcif you prefer predictable boundary behaviour nandNalso respectwrapscan, so the fix applies to repeat-search navigation too- Combine with
set shortmess-=sto keep the "search wrapped" hint messages visible when you do want wrapping