I know that * selects the word under the cursor, but what if I want to actually select a WORD ?
Just to be clear, I would then like to use the selection for a replace, something like :%s//foo/g
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityI would then like to use the selection for a replace, something like :%s//foo/g
:%s/^R^A/foo/g
See :h c_CTRL-R_CTRL-A
You are looking for the help topic :h <cWORD>
. When you combine it with :h expand()
it allows you to get the WORD under your cursor. You can try this command to understand how it works:
:echo expand('<cWORD>')
Now if you want to have for example <leader>*
to work as *
but with WORDs you could use the following mapping which will use expand('<cWORD>')
as the current search pattern:
nnoremap <leader>* :execute '/' . expand('<cWORD>')<CR>
If you want to use that directly in a substitution you could do something like this:
execute 's/' . expand('<cWORD>') . '/foo/g'
See :h execute()
if you are not familiar with this way of building commands.
Another approach is to map your *
key in visual mode to make it search for the selection:
" search visual selection
vnoremap * y/\V<C-R>=escape(@",'/\')<CR><CR>
Then, you can do viW*
to effectively search the WORD under the cursor.
Also, you could use a map to quickly start replacing the current selection:
nnoremap gr :s/<c-r>///g<left><left>