How do I insert the word under the cursor into the Vim command line?
Answer
<C-r><C-w>
Explanation
When typing a command on the Vim command line, pressing <C-r><C-w> inserts the word currently under the cursor. This saves you from having to retype identifiers, filenames, or variable names that are already visible in your buffer.
How it works
<C-r><C-w>— insert the small word under the cursor (equivalent toexpand('<cword>'))<C-r><C-a>— insert the WORD under the cursor (includes punctuation, equivalent toexpand('<cWORD>'))<C-r><C-f>— insert the filename under the cursor<C-r><C-l>— insert the entire current line
These all work from the : command prompt, / search prompt, or any command-line input.
Example
With the cursor on myVariable in your code:
let myVariable = 42
Type :echo then press <C-r><C-w> to get:
:echo myVariable
Or for a search-and-replace: type :%s/ then <C-r><C-w> to pre-fill the search pattern with the word under your cursor.
Tips
- Especially useful with
:%s/<C-r><C-w>/replacement/gfor quick renaming - In the search prompt,
*and#are faster for whole-word search, but<C-r><C-w>works in any command context <C-r><C-a>grabs more text (WORD), useful for URLs or file paths with dots