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?
Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.
Open the file in Vim. Press slash (/) key along with the search term like “/ search_term” and press Enter. It will highlight the selected word. Then hit the keystroke cgn to replace the highlighted word and enter the replace_term.
The easiest way to ask for help is to start with executing :help during a Vim session. This will drop us into the main help file which has an overview of the basics. To get help with a specific command, we can provide that command as an argument to the :help command.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With