Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm refactoring some code and I have several occurrences of the same block of code. I want to grab the block (probably in visual mode) and then replace every occurrence of it with a method call that I just defined.

Something like.

Some block
of code
that I
want to refactor

Some block
of code
that I
want to refactor

Some block
of code
that I
want to refactor

Some block
of code
that I
want to refactor

becomes...

method_call(stuff)

method_call(stuff)

method_call(stuff)

method_call(stuff)
share|improve this question

1 Answer 1

There are several ways to do this, depending on how often you plan to do it. The following method is pretty simple in that it uses ordinary Vim commands, but could be tedious if you had to do it a lot.

First, yank the block of code you want to refactor into the default register. For example, move the cursor to the first line of the block, type V, move the cursor to the last line of the block and type Y. Now copy the default register to the search register, replacing newlines by \n.

:let @/ = substitute(@", '\n', '\\n', 'g')

Finally, replace all the blocks by the method calls.

:%s//method_call(stuff)/
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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