Posts | About

Grep In Vim | Setup from Scratch

vimcheat-sheetsvideo

Posted on 2024-09-26 by Matt.

Cheat Sheet

:grep docs or :h :grep

The config shown here will not work as-is if using Neovim and ripgrep is available. See ripgrep

Grep for the string "Cat" in the current working dir (recursively)

:grep Cat -R .

Open the quickfix list

:copen

Manually cycle through entries in the quickfix list

:cnext
:cprev

Configure grepprg to search in current working dir (recursively)

-- lua
vim.opt.grepprg = "grep -HRIn $* ."

Keymaps

-- lua
-- use <Leader>gg to open quickfix list and Grep for a query
vim.keymap.set("n", "<Leader>gg", ":copen | :silent :grep ")

-- use ]q and [q to cycle through quickfix list
vim.keymap.set('n', ']q', ":cnext<CR>", { noremap = true, silent = true })
vim.keymap.set('n', '[q', ":cprev<CR>", { noremap = true, silent = true })

Execute the d command to all hits in the quickfix list

:cdo d

Execute the %s/Cat/Dog/g command to all files in the quickfix list.

:cfdo %s/Cat/Dog/g

With Ripgrep

If ripgrep is available, Neovim will automatically configure grepprg and grepformat for use with ripgrep.

-- lua
vim.opt.grepprg="rg --vimgrep -uu"
vim.opt.grepformat="%f:%l:%c:%m"
"" vimscript
set grepprg=rg\ --vimgrep\ -uu
set grepformat=%f:%l:%c:%m

Vim-Grepper

mhinz/vim-grepper

-- Keymap to open :Grepper
vim.keymap.set("n", "<Leader>gg", function() vim.cmd("Grepper") end, { silent = true })

-- configure to use ripgrep and git grep
vim.g.grepper = {
    tools = {"rg", "git"}
}
-- Use gs to take any motion and populate the search prompt
vim.keymap.set({"n", "x"}, "gs", "<plug>(GrepperOperator)")