0

I know that one can do a project-wide search and replace using the results of an Rg search in FZF.vim by doing the following:

  1. Run :Rg SEARCH_TERM

  2. Use Alt + a (or in my case, Esc + a, since I'm using xfce-4 terminal) to select all matches, or Alt + d (or in my case, Esc + d) to deselect all matches. Press CR to open up the selected item in the current window. The quickfix list will be automatically populated with all selections.

  3. Run :cfdo %s/SEARCH_TERM/REPLACEMENT_TERM/g

However, I'd like to see if I can create a custom binding for this.

I saw that someone else had the following solution using mhinz/vim-grepper by including this in his .vimrc:

let g:grepper={}
let g:grepper.tools=["rg"]

xmap gr <plug>(GrepperOperator)

" After searching for text, press this mapping to do a project wide find and
" replace. It's similar to <leader>r except this one applies to all matches
" across all files instead of just the current file.
nnoremap <Leader>R
  \ :let @s='\<'.expand('<cword>').'\>'<CR>
  \ :Grepper -cword -noprompt<CR>
  \ :cfdo %s/<C-r>s//g \| update
  \<Left><Left><Left><Left><Left><Left><Left><Left><Left><Left><Left>

As this requires vimgrepper to be installed, I'm wondering if anyone has a solution that doesn't require vimgrepper and uses the Rg function in FZF.vim? I do project-wide search and replace quite often but would rather not have to install another plugin for this.

0

No plugins:

  • set the args list (e.g., :args git ls-files)
  • search (:vimgrep /pat/ ##)
  • replace (:cdo substitute/...)
  • save (:argdo update or :wall or whatever)

Alternately, search with :grep -R ... * or set grepprg=rg\ --vimgrep and pretend :grep is ripgrep. Then :cdo, etc., as above.

I’m using :cdo because I’m assuming the search term is the same in both search and replacement. So the quickfix already has the relevant lines, making a global-search (:cfdo %substitute) less efficient. If the terms differ, :cfdo might be a better option.

Given that all these operations are rather simple ex-commands, it’s straightforward to wrap them in a function (perhaps with some parameters, which you can use via :execute). Then have a command or a mapping to call the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.