iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
✌️

VSCode-style Project-wide Search and Replace in Neovim

に公開

I'm bun, a pseudo-Vimmer.

I usually use nvim and VSCode as my editors.

For VSCode, I use the neovim extension.
(I previously wrote an article on how to get started with it.)

https://zenn.dev/bun913/articles/02785aed0ba50e

In Vim, you can use vimgrep for project-wide searching and replacement.

However, I was thinking, "I want to make it easier to select target files manually, just like in VSCode."

↓ Something like the following. Also, since it's Vim, I want to use it without a mouse.

My environment is as follows:

  • macOS Big Sur 11.5.1
  • NVIM v0.5.0
  • Vim plugin management: dein.vim
  • ripgrep 13.0.0

https://github.com/Shougo/dein.vim

Using far.vim and rg

Since setting up various commands myself seemed tedious this time, I decided to use a plugin called far.vim along with rg (ripgrep), a Rust-based grep that works extremely fast.

Installing the rg command

https://github.com/BurntSushi/ripgrep

Installation instructions are provided on the official page, so please install it according to your environment.

On Mac, it can be installed via Homebrew.

brew install ripgrep

Installing far.vim

https://github.com/brooth/far.vim

Since I use dein, I add the following to dein.toml:

[[plugins]]
repo = 'brooth/far.vim'

I also added the following settings to my init.vim or other configuration files:

" far.vim
let g:far#enable_undo=2
" Use rg for far searches
let g:far#source="rgnvim"
set lazyredraw            " improve scrolling performance when navigating through large results
set regexpengine=1        " use old regexp engine
set ignorecase smartcase  " ignore case only when the pattern contains no capital letters
" Shortcut settings
" Shortcut for replacement with ctrl + g
nnoremap <C-g> :Far  **/*<Left><Left><Left><Left><Left>
" Shortcut for search with ctrl + s
nnoremap <C-s> :F  **/*<Left><Left><Left><Left><Left>
let g:far#window_layout="tab"

Usage Example

In my case, I have configured <C-s> as the shortcut for project-wide search, so the search results are displayed as follows.

If you want to jump to a file, you can move to it immediately by pressing Enter on the filename.

Also, for replacement, you can call the shortcut with <C-g> and select the files to be replaced.
(Pressing t toggles between excluding and including files.)

After selecting files, you can execute the replacement with :Fardo and undo it with u.

That's all.

For seasoned Vimmers, this might be something that can be handled with standard features, but I hope this helps someone!

Discussion