1

I'm trying to do this:

nnoremap <leader>* :let @/ ="<cword>"<cr><bar>:set hlsearch<cr>                                                   

but can't get the first bit to work

nnoremap <leader>* :let @/ ="<cword>"<cr>

I want to highlight the word under the cursor but not jump to the next match automatically (often this is useful if you have multiple files open and you want to highlight a function definition in another file where you are using the function in the first file.

I came up with the let bit after reading :h @/ and given :let is an ex command I thought I'd be able to use <cword>

I've got stuck with adding or removing the quotes - no quotes gives an error and quotes just makes it search for "<cword>" literally. Likewise I also tried single quotes.

I'd be open to other ways of achieving the same thing but I'd also like to get to the bottom of why this doesn't work

  • What is the point of such mapping? There already is * and g*. – Hauleth Jan 1 '18 at 18:01
  • @Hauleth I think you mean * and #? This is like that but it doesn't jump to the next/previous occurence, just shows you the other ones, or prepares you to search in a different window using n/N – JonnyRaa Jan 2 '18 at 17:03
  • No, I meant g* which is equivalent to your mapping as * also adds word boundary guards before and after target word. – Hauleth Jan 2 '18 at 17:55
1

Managed to work it out after running into some difficulties using <cword> in a different mapping that was using / to search...

I ended up with this:

nnoremap <leader>* :let @/ = '\<'.expand("<cword>").'\>'<cr>:set hlsearch<cr>:echo<cr> 

This post showed me how to use cword in search.

This site told me that . is string concatenation

The \< and \> are vim regex for start and end of word so it stops it highlighting part of nohlsearch if you used the command on hlsearch

The echo at the end is just to clear the commandline.

When doing something a bit like this but more complicated I also got caught by the difference between single and double quotes.... basically use single quotes when you're doing regex!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.