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:
v
to select "he"I guess we can do it with vmap? But how to achieve it? Thanks!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With