I want to create function that search for selection and then automatically replace selection with given text. Something like *Ncgn but with custom movement (not exactly word only).

My current function is:

function! s:VSetSearch(type, ...)
  let temp = @@
  if a:0
    silent exe "norm! gvy"
  elseif a:type == 'line'
    silent exe "normal! '[V']y"
    silent exe "normal! `[v`]y"

  let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
  call histadd('/', substitute(@/, '[?/]', '\="\\%d".char2nr(submatch(0))', 'g'))
  let @@ = temp

xnoremap <Plug>(vsearch-change-selected-forward) :<C-u>call <SID>VSetSearch(visualmode(), 1)<CR>:set hlsearch<CR>cgn
xnoremap <Plug>(vsearch-change-selected-backward) :<C-u>call <SID>VSetSearch(visualmode(), 1)<CR>:set hlsearch<CR>cgN

But I would like to have also mappings in normal mode that would work on operators, but I have no idea how to accomplish that.

  • I'm not sure if I get exactly what you're trying to do, but ciw is identical and shorter than *Ncgn – James Oct 16 '16 at 13:00
  • 1
    With one exception. ciw change current word and when I . it changes it again. When I use *Ncgn then selected word resides as current search, so . will change next occurrence of that word. Example asciinema.org/a/2nv6rrsu06mzajk9hslxd78t7. So this works like :s///gc but is much faster for simple search and replace. – Hauleth Oct 16 '16 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.