I want to replicate Sublime Text's "CTRL-D" behavior which highlights the current word under the cursor.
* and # don't work here, because they automatically move the cursor (like n and N), which I explicitly don't want.
In order to hightlight the current word under the cursor, I have found the following to be effective:
yiw
:let @/=@@
:set hls
If you type this manually it works just fine, as intended.
My problem is that I just don't get it what I do wrong to put this on a keymap so I can bind it.
What I've tried so far is:
create a function, then map it to a key:
function SearchWordUnderCursor()
silent! yiw
silent! :let @/ = @@
silent! :set hls
endfunction
use the inline keybinding, like so:
nmap <C-D> yiw | :let @/ = @@ | :set hls
Both methods don't work as intended and I don't know what I'm doing wrong.
The search pattern/register is set just fine, but the immediate highlighting is not working, you'd have to manually n or N once to display the highlighting, but that moves the cursor, as opposed to the "manual" method.
Why is it so hard to get it done as if it was typed manually?
I'm using NVIM v0.2.2.
silent!
from the code vim helpfully cries yiw: not an editor command
.In a function every line is :
(ex-)command. Your yiw
is equivalent to :yiw
and this is not an editor command. (This also means that you can safely omit :
before commands). To run a Normal-mode command say :normal
explicitly:
function SearchWordUnderCursor()
silent! normal yiw
silent! let @/ = @@
silent! set hls
endfunction
<BAR>
instead of |
and pass all the keys you press including Enter:nmap <C-D> yiw <BAR> :let @/ = @@<CR> <BAR> :set hls<CR>