:vimgrep is Vim’s built-in search command for powerful, pattern-based searches across files or buffers. It leverages Vim’s regex capabilities and settings like ignorecase and smartcase.
Features of vimgrep
1. Vim-Specific Patterns
Vim extends standard regex with unique patterns for more flexible searches:
\v: “Very magic” mode. Treats most characters as regex metacharacters, reducing the need for backslashes.- Example:
:vimgrep /\vTODO|FIXME/ **/*.c
- Example:
\zsand\ze: Define the start (\zs) and end (\ze) of the match within a larger pattern.- Example: Match numbers after “ID:”:
:vimgrep /ID:\zs\d\+/ file.txt
- Example: Match numbers after “ID:”:
\|: Logical OR for matching multiple patterns.- Example: Match “error” or “warning”:
:vimgrep /error\|warning/ log.txt
- Example: Match “error” or “warning”:
\%l: Match at specific line numbers.- Example: Match “TODO” in lines <20:
:vimgrep /TODO\%<20l/ main.c
- Example: Match “TODO” in lines <20:
2. Behavior with Settings
ignorecase: Makes searches case-insensitive.:set ignorecase :vimgrep /error/ file.txtsmartcase: Overridesignorecaseif the search pattern contains uppercase characters.:set ignorecase smartcase :vimgrep /Error/ **/*.log
3. Using the Argument List (args)
Vimgrep supports the Argument list
Examples of vimgrep Usage
Basic Searches
-
Search for “TODO” in all
.pyfiles in the current directory and subdirectories::vimgrep /TODO/ **/*.py -
Search for “main” in a single file:
:vimgrep /main/ main.c
Advanced Searches
- Match “FIXME” only in the first 50 lines of a file:
:vimgrep /FIXME\%<50l/ code.c - Search for “TODO” followed by numbers:
:vimgrep /TODO\zs\d\+/ tasks.txt - Search with an OR pattern:
:vimgrep /error\|warning/ logs/*