I would like, for example, to be able to replace the word normal
by the word short
or longest
without entering Insert mode.
Would be practical for instance when renaming a variable
int normal = 0;
I know of the replace mode <Shift>-R
which works well when you want to replace a word by another one with the same length but is there a way for this use case ?
I would normally just diw
to delete inner word then start typing in Insert mode but I'm not that familiar with Vim so I'm wondering if there is a better way that doesn't involve Insert mode.
If not possible in Vim by default, I'm also interested in a remap
As hinted to in the comment, the easiest way to change "normal" in the code
int normal = 0:
to something else would be to place the cursor on "normal" and do ce
(or ciw
if the cursor is not on the first character of the word). Note that this uses insert mode to insert text. Which is unsurprisingly the whole point of insert mode.
To do so without entering insert mode, one could use the :substitute
command like this:
:s/normal/shrt/
To avoid spelling out "normal", one can use Ctrl-RCtrl-W to insert the Word under the cursor into the command line.
See :help :substitute
and :help c_CTRL-R_CTRL-W
for reference.
This replaces "normal" with "shrt" completely bypassing insert mode. For this simple replacement, this is more complicated than ciw
above. It's worthwhile when replacing all occurrences of "normal" anywhere in the file by prefixing :s
with whole-buffer range: :%s
.
This can be used to rename a variable throughout a file. Although I'd throw in some word boundaries (\<
and \>
) to match the whole word only and add the g
flag to substitute several matches on one line:
:%s/\<normal\>/shrt/g
There's another shortcut: the *
command will search for the (whole) word under the cursor and :s
will use the last search pattern if none is given. Place your cursor on "normal" and press *:%s//shrt/g
to have every "normal" replaced by "shrt".