Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 420
Troskyvs Avatar asked Feb 06 '23 12:02

Troskyvs


2 Answers

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

like image 170
Meninx - メネンックス Avatar answered Feb 08 '23 16:02

Meninx - メネンックス


You can add this mapping:

vnoremap <F7> :s/he/&r/g<cr>

Then when you press <F7> in visual mode, vim will do the text substitution on selected lines.

Note that, the :s cmd in above mapping is just example, it replaces all he into her, no matter if he is a part of other word, E.g. She's -> Sher's

like image 21
Kent Avatar answered Feb 08 '23 14:02

Kent