In the buffer
Before:
def fetch(url, retry_delay_ms=250):
for attempt in range(3):
time.sleep(retry_delay_ms / 1000)
^
log.debug("slept %d ms", retry_delay_ms)
The cursor is on retry_delay_ms on the third line (it can be on any letter of the word). Type :%s/, then <C-r><C-w>. The command line now reads :%s/retry_delay_ms. Finish with /backoff_ms/g and <Enter>:
def fetch(url, backoff_ms=250):
for attempt in range(3):
time.sleep(backoff_ms / 1000)
log.debug("slept %d ms", backoff_ms)
^
Every occurrence is renamed. The cursor lands on the first non-blank character of the last line that changed, which is how :s always leaves it.
When you would reach for it
You are looking straight at a long identifier, retry_delay_ms or HTTP_CONNECTION_TIMEOUT_SECONDS, and you want to rename it, :grep for it, or open its :help page. Typing it again on the colon line is slow, and one typo means a substitution that quietly matches nothing. Your cursor is already on the word, so <C-r><C-w> lets vim do the typing for you, spelled exactly the way the buffer spells it.
Gotchas
- Ctrl-W on its own on the command line deletes the word before the cursor. If you let go of Ctrl between the two keys, or press
<C-w>without<C-r>first, you erase part of your command instead of inserting a word. - The inserted text is a plain pattern with no word boundaries. With the cursor on
retries,:%s/<C-r><C-w>/attempts/galso turnsmax_retriesintomax_attempts. Wrap it as\<<C-r><C-w>\>(see Variants) when you only mean the whole word. - If the cursor is on whitespace or punctuation, vim does not complain. It grabs the next keyword on the line instead. With the cursor on the
=intotal = 0,<C-r><C-w>inserts0. Look at what landed on the command line before you press Enter. - The word goes in as typed text, so pattern characters in it keep their meaning. That rarely matters for
<C-w>, since keywords are letters, digits, and underscores, but it does matter for the<C-a>variant: a.inconfig.loadmatches any character.
Variants
retries = 0
max_retries = 5
while retries < max_retries:
^
attempts = 0
max_retries = 5
while attempts < max_retries:
^
:%s/\<<C-r><C-w>\>/attempts/g: wrapping the word in \< and \> limits the match to the whole word, so max_retries stays as it is.
cfg = config.load_defaults()
^
x = config.load_defaults()
cfg = CONFIG
x = CONFIG
^
:%s/<C-r><C-a>/CONFIG/g: Ctrl-A inserts the WORD under the cursor (everything between whitespace), so you get config.load_defaults() with its dot and parentheses, not only load_defaults.
retries = 0
^
max_retries = 5
while retries < max_retries:
attempts = 0
max_retries = 5
while attempts < max_retries:
^
* then :%s//attempts/g: a different route to the same result. * searches for the word with boundaries already added, and an empty pattern in :s reuses the last search. Ctrl-R Ctrl-W is the one to use when the word is going into something other than a substitution, such as :help <C-r><C-w> or :vimgrep <C-r><C-w> **/*.py.