How do I search for a pattern in the current file and navigate results with the quickfix list?
Answer
:vimgrep /pattern/ %
Explanation
When you need to find all occurrences of a pattern in the current file and jump between them systematically, :vimgrep with % is more powerful than basic / search. It populates the quickfix list with every match, giving you a persistent, navigable list of results.
How it works
:vimgrepis Vim's built-in grep command that searches files and populates the quickfix list/pattern/is the search pattern (supports full Vim regex)%refers to the current file- After running, use
:copento see all matches in the quickfix window - Navigate with
:cnext/:cprev(or]q/[qwith unimpaired-style mappings)
Example
Suppose you have a file with multiple function definitions and want to jump between them:
:vimgrep /function\s\+\w\+/ %
:copen
This populates the quickfix list with every line containing a function definition. The quickfix window shows:
file.js|3| function initialize() {
file.js|15| function processData() {
file.js|42| function cleanup() {
Press <CR> on any line to jump directly to that match.
Tips
- Add
jflag (:vimgrep /pattern/j %) to avoid jumping to the first match automatically - Use
:lvimgrepinstead to populate the location list (per-window) rather than the quickfix list - Combine with
:cdoto perform operations on all matches