How do I insert the word or WORD under the cursor into the command line?
Answer
/
Explanation
While typing in the Vim command line (: mode), pressing <C-r><C-w> inserts the word under the cursor, and <C-r><C-a> inserts the WORD (whitespace-delimited). This saves you from retyping identifiers, filenames, or variable names that are already visible in the buffer.
The shortcuts
| Shortcut | Inserts |
|---|---|
<C-r><C-w> |
The word under the cursor (letters, digits, underscores) |
<C-r><C-a> |
The WORD under the cursor (everything up to whitespace) |
<C-r><C-l> |
The entire current line |
<C-r><C-f> |
The filename under the cursor |
<C-r><C-p> |
The filename under the cursor, expanded with path |
Example
With cursor on myVariable:
:s/myVariable " instead, type:
:s/<C-r><C-w> " auto-fills :s/myVariable
Search and replace the word under cursor:
:%s/<C-r><C-w>/newName/g
Grep for the word under cursor:
:grep <C-r><C-w> **/*.py
With cursor on path/to/file.txt, insert the full path:
:edit <C-r><C-a>
Tips
<C-r><C-w>also works in search mode (/) — start a search and pull in the word under cursor*(search word under cursor) uses the same concept but only for searching;<C-r><C-w>works in any command-line context<C-r><C-a>is especially useful for URLs and file paths that contain dots, slashes, and hyphens- These all work in Insert mode too, though
<C-r>in Insert mode accesses registers (use<C-r>=expand('<cword>')for the same effect)