Vim replace all without cursor moving

2019-03-23 11:11发布

问题:

In Vim, when I do:

:%s/foo/bar/g

It will replace all occurrence of 'foo' with 'bar' in the entire document. When it completes, the cursor has moved to the last position where 'foo' was replaced with 'bar'.

How do you run :%s/foo/bar/g without the cursor leaving the original position before issuing this command?

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

回答1:

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



回答2:

When the :substitute command is run, before actual replacements are done, position of the cursor is stored in a jump list. In order to return to the position before the latest jump, one can use the `` or '' Normal mode commands. While the former jumps exactly to the stored position, the latter moves the cursor to the first non-blank character on the line where that position is located.

So, to quickly return the cursor back to its original location, type `` after substitution command is finished.

To combine substituting and moving the cursor into one command, issue

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

or, if it is enough to jump not to the precise position but only to its line,

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

As shown above, '' can be used in preference to norm!'' in the second command because of the range syntax of Ex commands (see :help :range).



标签: vim macvim