Refactoring C/C++ in Vim (e.g. method extraction like in Eclipse)

No, although Vim is a good environment for editing, and can be customised in a lot of ways (code folding, syntax colouring, macro expansion etc.) most of these are done on the syntax level, rather than the semantic level. Even the code folding just matches up opposing braces.

To do a proper refactoring, you have to have a lot of semantic knowledge about the AST, what variables are declared in which scope, and so on. IDEs like Eclipse build up a cache of the variables defined in each lexical scope, so that they can quickly refer back to where they are used in terms of determining what to rename and where.

That’s not to say that you can’t do some things syntactically; after all, one can just take out a block of code and put it into a separate function easily enough. You might even be able to guess at some parameters (e.g. find a list of the variables, find out which ones have local declarations, remove them and what’s left are your parameters. But Eclipse also does other things—like figuring out whether any variables are modified in the function, and ensuring they’re passed back by the return value. It also checks for any thrown exceptions, and add them to the list.

The net effect is that whilst you may be able to approximate some of these in Vim, you really aren’t going to be able to get this working in a Vim-only enviornment. You could either use a Vim-like keybinding in Eclipse proper, or look at eclim. From the home page:

The primary goal of eclim is to bring
Eclipse functionality to the Vim
editor. The initial goal was to
provide Eclipse’s java functionality
in vim, but support for various other
languages (c/c++, php, python, ruby,
css, html, xml, etc.) have been added
and several more are planned.

Eclim is less of an application and
more of an integration of two great
projects. The first, Vim, is arguably
one of the best text editors in
existence. The second, Eclipse,
provides many great tools for
development in various languages. Each
provides many features that can
increase developer productivity, but
both still leave something to be
desired. Vim lacks native Java support
and many of the advanced features
available in Eclipse. Eclipse, on the
other hand, still requires the use of
the mouse for many things, and when
compared to Vim, provides a less than
ideal interface for editing text.

That is where eclim comes into play.
Instead of trying to write an IDE in
Vim or a Vim editor in Eclipse, eclim
provides an Eclipse plug-in that
exposes Eclipse features through a
server interface, and a set of Vim
plug-ins that communicate with Eclipse
over that interface.

This not only gives an Eclipse-like environment, it is Eclipse. But you still get the navigation and text editing features of vim. It sounds like this might suit your needs, although the documentation on refactoring support doesn’t indicate that it provides an extract method functionality.

Leave a Comment