Interactively, you can use <C-O>
or the change mark ``
to move back to the original position, as shown at vim replace all without cursor moving.
In a Vimscript, especially when this runs on every buffer write, I would wrap the code:
let l:save_view = winsaveview()
%substitute///
call winrestview(l:save_view)
The former move commands might still affect the window view (i.e. which exact lines and columns are shown in the viewport), whereas this solution restores everything as it was.
Bonus stuff
Also, be aware that the {pattern}
used in the :substitute
is added to the search history. To avoid that, append
call histdel('search', -1)
(The search pattern itself isn't affected when you have this in a :function
.)
or use the :keeppatterns
command introduced in Vim 8:
keeppatterns %substitute///
Related plugins
I've implemented similar functionality in my AutoAdapt plugin. You'll see all these tricks used there, too.