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.

Often when editing code, I'll select a block in visual mode and do a search and replace over the block. After I make the changes, however, it leaves visual mode. How do a new find and replace over the same selection?

share|improve this question
    
Well I found one way, but it's a little cumbersome: :'<,'>s/old/new/g Any way to do this w/o having to type in the '<,'> ? –  labyrinth Dec 10 '10 at 17:14
add comment

3 Answers

up vote 61 down vote accepted

You may re-select the last selected visual area with "gv".

share|improve this answer
add comment

gv is definitely the fastest method (use last selection), but if you want a stable saved selection region (or several), you can always create macros.

Lets say I want to store a selection of my current method, which goes from lines 25-35. I can create a macro that selects the whole method by typing

q    //start recording
a    //use register a
25G  //Go to line 25
V    //visual-line mode
35G  //Go to line 35
q    // stop recording

I can then get that selection back by typing @a (run macro in register a). Repeat with any register, lines, or sections of lines, that you wish. Obviously if you make changes to the file the selection may change as well...

share|improve this answer
    
zmto enter that you need to know the line numbers. I think its better to define two marks and then use :'a,'b to operate on the range between them (or replace ' with backticks if want granularity within a line) –  sillyMunky Jan 16 at 1:24
    
Yeah, the line numbers thing was dumb -- I just used it as an example for how to create a selection macro. Using a range of marks is an interesting idea though... –  AlexMA Jun 25 at 18:38
add comment

Suppose I wanted to replace Goodbye with Hello and the code below was selected:

public static void main(String[] args){
    System.out.println("Goodbye World");
}

I would type in :s/Goodbye/Hello/ and vim will replace all instances of Goodbye with Hello

It's simply a combination of vim's regular expressions and visual mode selections. When you select, it should autofill '<,'>

share|improve this answer
    
Sorry, that's not what I was asking. What I'm asking is how do you reuse the selection to do another find and replace on the same range as selected before? –  labyrinth Dec 10 '10 at 18:24
1  
After replacing, you will get out of visual mode. type in gv and your visual mode will revert to the previous selection state. –  Scott Nguyen Dec 10 '10 at 22:03
add comment

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.