brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Ctrl-r Ctrl-w in the Vim command line types the word under the cursor

Vim
~/tips/tip-vim-ctrl-r-ctrl-w-command-line

:%s/<Ctrl-r><Ctrl-w>/newname/g

Pastes the word under the cursor into a command or search you are typing in Vim.

Renaming a variable in Vim usually starts with typing its name into a substitute command. The name is already under the cursor, so typing it again is wasted effort, and a typo means the command silently matches nothing.

Put the cursor on the word, press : to open the command line, and then press Ctrl-r followed by Ctrl-w. Vim inserts the word under the cursor right there.

:%s/<Ctrl-r><Ctrl-w>/newname/g

With the cursor on counter, the command line now reads :%s/counter/newname/g and you only type the replacement. It works the same after / when you start a search, and in the middle of any other Ex command.

The same prefix has a few siblings, listed in :help c_CTRL-R_CTRL-W:

  • Ctrl-r Ctrl-a inserts the WORD under the cursor, meaning everything up to the next whitespace.
  • Ctrl-r Ctrl-l inserts the whole line.
  • Ctrl-r Ctrl-f inserts the file name under the cursor.

One caveat: the word is inserted as plain text. If it contains characters that mean something in a pattern, such as a dot or a dollar sign, they still act as pattern characters. For most identifiers that doesn’t matter. For something like file.txt, use Ctrl-r Ctrl-a and escape the dot yourself if you need an exact match.

Further reading: Vim help: cmdline, c_CTRL-R_CTRL-W

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 :mksession All Vim tips (45) All topics

Link