Saturday, November 24, 2007

Extract variable in Vim

I have automated the extract variable refactoring in Vim. Well, at least for languages where you don't have to declare types. This includes Python, the language I use at work. It can also be used with Ruby and other dynamic languages, as well as with languages featuring type inference, like Nemerle and Haskell.

Select (in visual mode) a value you want to extract, and press ctrl-e. This will pop up a dialog asking for the name of the variable. A line with the assignment will be added above and all occurrences of the value will be replaced with the given name. The replacement will happen only in the lines after the assignment.

To enable it, copy the snippet to your vimrc file.

function! ExtractVariable()
    let name = inputdialog("name please")
    if name != ""
        execute "normal O" . name . " = "
        normal p
        execute (line('.')+1) . ",$s/" . escape(getreg('"'), '/\') . "/" . name . "/" 
    endif
endfunction

noremap <c-e> y:call ExtractVariable()<cr>