How to run a search and replace command without cursor moving in Vim?

When the :substitute command is run, prior to any replacements being carried out, the current position of the cursor is stored in the jump list (see :help jumplist).

In order to return to the position before the latest jump, one can use the `` or '' Normal-mode commands. The former jumps exactly to the stored position; the latter jumps to the first non-whitespace character on the line the stored position belongs to.

It is possible to both invoke a substitution command and move the cursor back afterwards, at once, by issuing the command

:%s/pat/str/g|norm!``

or, if jumping to the containing line is sufficient, by using the command

:%s/pat/str/g|''

It is not necessary to preface '' with norm! in the latter command, because the '' address is allowed by the range syntax of Ex commands and refers to the same line the Normal-mode command '' jumps to (see :help :range); both just look into the contents of the ' psudo-mark.


I just type Ctrl+O after the replace to get back to the previous location.


It's old, but for anyone coming across this question, I wanted to share my solution since it will work correctly even if nothing is substituted:

:exe 'norm m`' | %s/pattern/substitution/eg | norm g``

exe is needed since norm treats the bar as an argument.

Tags:

Vim

Macvim