Refactoring in Vim

refactoringvim

Of course the fact that you can refactor on IDEs is priceless for many, I hardly ever do it when I am coding but I may try to do it when editing some one else's source. How do you accomplish such a trivial task across multiple files in Vim?

I found this plugin for refactoring Ruby, but how about "any" language?

Best Answer

I agree with the 'Vim is not an IDE' paradigm. But there are times when there isn't an IDE. Here's what I use in those situations:

Disclaimer: The ubiquity of Language Server Protocol servers, linters and fixers since I wrote this have also brought some great refactoring capabilities to Vim (and other editors). IMO they are a long way from equaling the capabilities of a purpose-built IDE (I prefer ALE and nvim-lspconfig for these kinds of features). See other answers on this question for more info!

:grep, :vimgrep, :GrepperAg, :Ggrep

Refactoring that has more to do with regular replacements I usually use :grep on my project tree and then record a macro to do the refactor - :g and :s are no brainers. Usually it'll let me quickly modify a large number of files with very little effort. Honestly, I use this method more than any other.

Depending on your workflow the built-in commands might be slow/inconvenient. If you use git, then you'll wanna use the excellent Fugitive plugin and its :Ggrep command to only search files checked into git. I also like the vim-grepper because it is search-tool-agnostic (supports ag, sift, ripgrep, etc) and speedy.

:argdo, :cdo, and :bufdo

:cdo and :argdo are handy to execute vim commands over a set of files.

command line

When it's harder to determine the list of files that need changes via :vimgrep I resort to the command line grep/find commands to more closely curate the list of files that I need to refactor. Save the list to a text file and use :e and a mashup of macro recordings to make the changes I need to make.

I find that the less rusty I keep my macro recording skills the more useful I find Vim for refactoring: feeling comfortable saving/restoring from registers, incrementing/decrementing register counter variables, cleaning/saving macro recordings to file for later use, etc.


Update

Since writing this more videocasts for the methods I describe have been published on vimcasts.org (I encourage you to watch ALL the Vimcasts!). For refactoring watch these ones:

Vimgolf is also a great way to practice.