views:

1701

answers:

3

Lets say we have a a text and i enter in visual mode and select a text and how do i quickly do a search for the highlight text and replace it with something else

thanks

+1  A: 

I don't think you can do this out of the box. But lots of people like this feature, so there's tons of macros and such (I've added it myself). Here is one you can add, for example; just press * to search for the next match on the visually selected text.

John Feminella
+5  A: 

Try execute the following or put in into your .vimrc

vnoremap <C-r> "hy:%s/<C-r>h//gc<left><left><left>

By pressing ctrl + r in the visual mode you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with 'y' or decline with 'n'.

This command will override your register 'h' so you can choose other one ( by changing 'h' in the command above to other lower case letter ) that you don't use.

Mykola Golubyev
Where do you add this ? ... sorry i am really new to vim
solomongaby
If you under unix like system you have ~/.vimrc file. Put the given line to this file and restart vim.
Mykola Golubyev
+1. Good tip, Mykola!
John Feminella
+1  A: 

I have this in my vimrc:

function! GetVisual() range
    let reg_save = getreg('"')
    let regtype_save = getregtype('"')
    let cb_save = &clipboard
    set clipboard&
    normal! ""gvy
    let selection = getreg('"')
    call setreg('"', reg_save, regtype_save)
    let &clipboard = cb_save
    return selection
endfunction

vmap <leader>z :%s/<c-r>=GetVisual()<cr>/

This will grab the visual selection and start a substitution command with it.

EDIT: I should point out that this does not work with multiline visual selections. While GetVisual() doesn't have a problem returning it, I'm not sure how to properly put it into the command line. If anyone has any tips on how I might do this, please comment.

Jeremy Cantrell