I want to write a command that specifies \"the word under the cursor\" in VIM. For instance, let\'s say I have the cursor on a word and I make it appear twice. For instance, i
Another easy way to do this is to use the *
command.
In regular mode, when over a word, type
*:s//\0\0<Enter>
*
makes the search pattern the current word (e.g. \<abc\>).
:s//
does a substitution using the current search pattern, and \0
in the replacement
section is the matched string.
You can then repeat this behaviour, say over word "def", by either typing the same again, or by typing
*@:
@:
just repeats the last ex command, without a need for an <Enter>, in this case the substitution.
You can also record a quick macro to do this using the q
command
qd*:s//\0\0<Enter>q
Then repeat it to your hearts content by typing
@d
when over a word you want to double. As this is only one character less than the prior solution, it may not be worth it to you - unless you will be doing other ex-commands between the word-doubling, which would change the behaviour of @:
@user11211 has the most straightforward way to duplicate the word under cursor:
yiwP
yank inner word (moves cursor to start of word), paste (before cursor).
eg. straigh[t]forward ----> straightforwar[d]straightforward
[] is cursor
To elaborate...
You probably want to have the cursor following your duplicated word:
yiwPea
straigh[t]forward ----> straightforwardstraightforward[]
NOTE:
yiw
is yank inner word (without whitespace)
yaw
is yank all word (including trailing whitespace).
yawPea
is therefore duplicate word including whitespace, and position cursor.
straigh[t]forward ----> straightforward straightforward[]