platypus
platypus

Reputation: 1205

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

In Vim, when I run a substitution command like

:%s/foo/bar/g

it replaces all occurrences of foo with bar in the entire buffer. When it completes, the cursor moves to the last location where foo was replaced with bar.

How can I run :%s/foo/bar/g without having the cursor leave its original location where it was before the substitution command was issued?

Is there some option I can set in the .vimrc file?

Upvotes: 29

Views: 6795

Answers (3)

ib.
ib.

Reputation: 28934

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.

Upvotes: 39

frippe
frippe

Reputation: 1393

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.

Upvotes: 3

Steve Jorgensen
Steve Jorgensen

Reputation: 12341

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

Upvotes: 27

Related Questions