Search code examples
dictionaryselectvimreplacemode

How to map vim visual mode to replace my selected text parts?


I wish to replace part of my words, as selected by visual mode. E.g.:

I've got a simple text file:

------------------
hello there hehe
She's not here
------------------

I need to change all "he" into "her".

What I wish to do is not to type %s command, but under visual mode:

  1. v to select "he"
  2. Press some hot key, and vim prompts me to input the new text
  3. I type the new text, press Enter, done.

I guess we can do it with vmap? But how to achieve it? Thanks!


Solution

  • To get the solution all credits go to User @xolox from his answer which I developed to get the required task:

    vnoremap ; :call Get_visual_selection()<cr>
    
    
    function! Get_visual_selection()
      " Why is this not a built-in Vim script function?!
      let [lnum1, col1] = getpos("'<")[1:2]
      let [lnum2, col2] = getpos("'>")[1:2]
      let lines = getline(lnum1, lnum2)
      let lines[-1] = lines[-1][: col2 - (&selection == 'inclusive' ? 1 : 2)] 
      let lines[0] = lines[0][col1 - 1:] 
      let selection = join(lines,'\n')
      let change = input('Change the selection with: ')
      execute ":%s/".selection."/".change."/g"
    endfunction
    

    You can change the mapping ; to any hot key you want.

    enter image description here