121

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?

8
  • 2
    Refactoring is very language-specific. You need to look for specific add-ons for each language you're interested in. You'll presumably find add-ons for some and not for others. If there's one you want and can't find, then if you're feeling ambitious, you might try to write one, using an existing add-on for another similar language as a starting point. Jan 8, 2012 at 22:42
  • 3
    VIM is designed around editing single files, and maybe files under a directory - not projects. Many IDE-supported refactorings will impact files across the whole project (e.g. renaming a class). I think it would be tricky to get this "right" with an editor like (g)VI(m), to the point where I think a company or a big project would have to take it on. They'd basically have to parse each language to avoid doing simple string substitutions and become prone to errors (ctags gives some of this), as well as the corresponding project types (to know which files to edit). Jan 9, 2012 at 0:21
  • 1
    Thanks for the comments, I think this is where things start to get tricky and trying to bend VIM to an IDE is not such as an elegant solution to using only one program to edit multiple languages. I truly do not want to give up on VIM due to some of the "advanced" features being available on IDEs. Jan 9, 2012 at 0:32
  • 7
    @ldigas: That would work around the problem. But it is quite against recommended practices for some languages (e.g. Java). Basically the code bending to fit the tool's needs, when it really should be the other way around. Jan 9, 2012 at 9:08
  • 1
    @MerlynMorgan-Graham - What you say IS true, but as much as that sounds bad, everyone "bends" code to fit their tool's needs.
    – Rook
    Jan 9, 2012 at 12:43

15 Answers 15

97

Disclaimer: a huge ecosystem of Language Server Protocol servers have been created since I wrote this. They have brought great refactoring capabilities to Vim (and other editors). IMO they are still far from equaling the capabilities of a purpose-built IDE, but they're great. I prefer ALE, nvim-lspconfig, null-ls, and refactoring.nvim to leverage these features (and neovim). See other answers for more info!


I subscribe to the 'Vim is not an IDE' philosophy. But there are times when there isn't an IDE. Here's what I do in those situations:

:grep and :cdo commands

If the refactoring task has more to do with regular replacements I use a :vimgrep-like command to find files, record a macro to do the refactor or use :g and :s if its a no brainer, and use :cdo (:argdo, :bufdo, etc) to execute the macro/command over all the matches.

Usually vim'll let me quickly modify a large number of files with very little effort. Honestly, I use this method more than any other.

The built-in vim commands might be slow/inconvenient for you. If you use git, you'll wanna use the excellent Fugitive plugin and its :Ggrep command to only search files checked into git. I also like vim-grepper because it is search-tool-agnostic (supports ag, sift, ripgrep, etc). I often use quickfix-reflector to winnow down matches, and edit directly in the quickfix window.

command line

When a simple :grep command doesn't cut it, I resort to the command line 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.

Striving to understand my tools always makes the job easier: git staging, CLI tools, and the language that I'm working with.


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.

9
  • 20
    Refactoring is WAY more than pattern matching, that's why IDE's are needed to automate this in a safely manner. Obviously, you can do it manually, but considering the available options, and that most of the times it's safer to do it manually, why would you even consider any other option? Sep 18, 2015 at 21:47
  • 2
    @CutbertoOcampo I agree with you to some extent: depending on myriad aspects of a project (structure, language(s), staff skills & resources, to name a few), there MAY be a great refactoring tool applicable to your problem. My answer applies to situations when that is not true, and you want to tackle the problem in Vim.
    – dsummersl
    Sep 21, 2015 at 16:21
  • 2
    that's fine, I understand people may feel more comfortable doing thing using their long-time preferred tools, and that there're are some hacks that can perform really well, probably better than any IDE out there, but for an out-of-the-box solution I'd say an actual IDE would perform better for most users. I'd be thinking on a 80-20% kind of situation (even more, with the balance in favor of the IDE). Sep 22, 2015 at 16:41
  • 1
    There is an ide for practically every language. Trying to refactoring with vim or regex sounds absolutely insane. Why would you even try?
    – rollsch
    Jul 15, 2017 at 13:00
  • 3
    @rolls to be potent enough to grab a random colleague's in-need machine with not-your-ide or whatever cfg you can only live with and leave a good impression around (not for "just impression" but for reputation and future position).
    – bloody
    Apr 8, 2020 at 18:15
47

Language Server Protocol (LSP)

The Language server protocol contains the feature for smart renaming of symbols across a project:

https://microsoft.github.io//language-server-protocol/specifications/specification-3-14/#textDocument_rename

For example following language server support this:

You can find more language servers under https://langserver.org/.

Vim

A vim editor client is necessary to use them within vim. Following options exist:

  1. LanguageClient-neovim (requires rust) suggests the mapping:

     nnoremap <silent> <F2> :call LanguageClient_textDocument_rename()<CR>
    
  2. coc.nvim (requires node.js) suggests the mapping:

     " Remap for rename current word
     nmap <leader>rn <Plug>(coc-rename)
    
  3. Ale has

     nnoremap <silent> <Plug>(ale_rename) :ALERename<Return>
    

    Ale does not define any keybindings. This has to be done by the user.

  4. vim-lsp provides following command

     :LspRename
    

    Similar to Ale no mapping is suggested. However, of course you can define one as following

     nmap <leader>r <plug>(lsp-rename)
    

    (<leader>r is to be replaced by your choice; I do not know one which most plugins agree on)

  5. vim-lsc has a default mapping:

     'Rename': 'gR'
    

See also YouCompleteMe which facilitates LSPs as well.

Neovim

Neovim has initial builtin support for lsp since 13.11.2019

See for common configurations of LSPs the project nvim-lspconfig which suggests <space>rn as a mapping for vim.lsp.buf.rename().

Other Refactorings

I do not know if there are plans for the LSP protocol to support more complex refactorings, such as changing class structure, adding parameters to methods/functions or moving a method to a different class. For a list of refactorings see https://refactoring.com/catalog/.

2
  • Unfortunately, the support for refactoring in the LSP is currently pretty weak compared to the state of art. github.com/Microsoft/language-server-protocol/issues/61
    – Mickael
    Aug 12, 2017 at 8:30
  • 2
    AFAIK that renaming for coc-rename only works on the current buffer. It didn't update the use of the exported name globally in the project (across files).
    – oligofren
    May 31, 2019 at 10:35
18

Python

For the python language following plugins provide 'smart' renaming capabilities for vim:

  • jedi-vim (github) <leader>r
  • ropevim (github) CTRL-c r r
  • python-mode (github) :h pymode-rope-refactoring
13

C-Family

  1. Try the plugin Clighter for rename-refactoring for the c-family. It is based on clang, but there are limitations and the plugin is marked as deprecated.

    Suggested mapping by Clighter is

     nmap <silent> <Leader>r :call clighter#Rename()<CR>
    

    Note, the successor plugin clighter8 has removed the renaming functionality in the commit 24927db42.

  2. If you use neovim, you can take a look at the plugin clamp. It suggests

     nmap <silent> <Leader>r :call ClampRename()<CR>
    
0
5

Maybe not the most elegant solution, but I found it very handy: I use ECLIM to connect VIM and Eclipse. Of course all my source code editing is done in VIM, but when it's time to refactor, one can take advantage of Eclipse's superior cababilities in this matter.

Give it a try.

5

I wrote this plugin for generic refactoring. It still requires many improvements. Sometime in the future I'll try to abandon ctags in favour of clang for C&C++ refactorings.

5

Plugin YouCompleteMe (YCM) (20k stars on github)

http://ycm-core.github.io/YouCompleteMe/#the-refactorrename-new-name-subcommand

:h RefactorRename-new-name

In supported file types, this command attempts to perform a semantic rename of the identifier under the cursor. This includes renaming declarations, definitions and usages of the identifier, or any other language-appropriate action. The specific behavior is defined by the semantic engine in use.

Similar to FixIt, this command applies automatic modifications to your source files. Rename operations may involve changes to multiple files, which may or may not be open in Vim buffers at the time. YouCompleteMe handles all of this for you. The behavior is described in the following section.

Supported in filetypes: c, cpp, objc, objcpp, cuda, java, javascript, typescript, rust, cs

By default there is no mapping.

2
  • So for now this works only for javascript, typescript and java?
    – S.R
    Mar 13, 2018 at 7:42
  • In order to make this work across multiple files on the C-Family (using clangd) you need to add this to your .vimrc: let g:ycm_clangd_args = ['-cross-file-rename']
    – jav
    Nov 10, 2020 at 16:41
4

Place cursor at name to refactor and type

gd (or gD if you're refactoring a global variable).

Then

cgn new_name esc

and

. one or more times to refactor next occurrence(s)

or

:%norm . to refactor all occurrences in the buffer at once.

3

Plugin Factorus

There is another vim plugin dedicated for refactoring called factorus which is available on github.

Currently (2017-12), it supports the languages

  • c,
  • java, and
  • python.
1

I write a lot of C/C++ code in vim. The most common refactoring that I do is renaming variables, class names, etc. Usually, I use :bufdo :%s/source/dest/g to do a search/replace in files, which is almost the same as renaming provided by big IDE's.
However, in my case, I found that I usually rename similar entities, spelled in different cases (i.e CamelCase, snake_case, etc.), so I decided to write a small utility to help with this kind of "smart-case" search/replace, it is hosted here. It is a command-line utility, not a plugin for vim, I hope that you can find it useful.

1

Go

  1. The tool godoctor (github) supports several refactoring capabilities
  • Rename
  • Extract Function
  • Extract Local Variable
  • Toggle var ⇔ :=
  • Add Godoc stubs

There is a vim plugin https://github.com/godoctor/godoctor.vim which makes them available

With cursor in thing to rename:

:Rename <newname>

Highlighting block to extract:

:Refactor extract newfunc
  1. vim-go

    • Precise type-safe renaming of identifiers with :GoRename.
  2. Language server gopls

0

For refactoring, if you're using Unite (and you should), you can then use vim-qfreplace and make it extremely easy. Check this video that demonstrates how it works. Once your workflow is set, you can make some mappings to optimize it (instead of typing most things like in the video).

0

A combination of two plugins: vim-ripgrep, to find across files and put the results in the quickfix window, and quickfix-reflector to save the changes right in the quickfix window and have it automatically save each change across the files.

0

I would consider using the spacemacs version of emacs. It is uses the same modes and most keystrokes as Vim but has many more add-on because of it's lisp nature. If you want to program in C++ you just add the c++ layer and most of the IDE is just set up for you already. For other interpreted languages like python or bash you do not need to leave spacemacs to use them. They even have a way to run blocks of code directly within your text which works fantastic for literate programming or reproducible programming where the code and the data are in the same file. Both done as text.

Spacemacs is much more heavy handed in it's initial load but the additional stuff you can do with it is worth the few seconds of startup cost. One layer org-mode is worth checking it out. It is the best outliner, programmer, day timer / todo list I have ever used.

0

The CoC addon has (among other features) the ability to rename variables.

https://github.com/neoclide/coc.nvim

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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