How does one keep the cursor in its place after a file-replace using :%s/find/replace/g ? I looked at restoring cursor position, but not quite what I was looking for, and I could jump back to previous position using ''.

  • So what are you looking for? Using '' or <C-o> is sort of the answer :-) Do you want it to happen automatically? Mar 16, 2015 at 14:53
  • Automatically would be great; I'm hoping to eliminate an extra couple of keys, since I find myself going find-replace a lot, oh and learn something new (_:
    – KM.
    Mar 16, 2015 at 15:06
  • @Carpetsmoker as well as `` ) Actually it looks like this particular question boils down to the issue whether it is possible to find some autocmd event we can listen to and trigger this automatically.
    – shabunc
    Mar 16, 2015 at 18:53

2 Answers 2


The anwolib plugin has a :KeepView command:

:KeepView %s/find/replace/g
  • Is there a way to "enable" KeepView for all find-replace operations? I'm trying to minimize typing (_:
    – KM.
    Mar 16, 2015 at 17:57
  • 1
    You can create a shorter :KV alias command, or even :kv using cmdalias.vim. To be even more extreme: :nnoremap : :KeepView<Space> Mar 16, 2015 at 19:59
  • 1
    Aaaand it's still the same two keys as with ''. Apr 11, 2016 at 12:17

I would suggest something like:

fun! SubstiTute()
    let l = 1
    let limit = line('$')
    while l < limit
        call setline(l, substitute(getline(l), 'this', 'that' , 'gc'))
        let l = l + 1

Using setline() in conjunction with substitute() your jumplist and changelist will not be messed up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.