I currently have this mapping:

" bind K to grep word under cursor
nnoremap K :grep! "\b<C-R><C-W>\b"<CR>:cw<CR><ENTER>

My ag setting in vimrc:

if executable('ag')
  " Use ag over grep
  let &grepprg = "ag"

This works perfect for regular words, but say I put my cursor under the term customer-segmentation, This command gets executed:

:ag "\bcustomer\b"

how can I make it execute this instead:

:ag "\bcustomer-segmentation\b"
  • You can also use <ctrl-r><ctrl-a> Commented Aug 12, 2022 at 19:30
  • 1
    @VivianDeSmedt Yep! But the problem with <c-r><c-a> is that it also includes other characters, so if the cursor is on e.g. "test-this" it will grab the quote marks as well as the hyphenated words.
    – Rich
    Commented Aug 12, 2022 at 19:45
  • @Rich, you are right it is not a solution. I tought it is a chance to make it known and it could help on some cases it might help ;-) Commented Aug 13, 2022 at 5:53
  • @VivianDeSmedt I agree!
    – Rich
    Commented Aug 14, 2022 at 7:56

1 Answer 1


A straightforward (if not exactly elegant) way to do this is just to temporarily set iskeyword to include the hyphen:

nnoremap <silent> K :let s:old_iskeyword = &l:iskeyword<CR>
    \:setlocal iskeyword+=-<CR>
    \:grep! "\b<C-R><C-W>\b"<CR>
    \:let &l:iskeyword = s:old_iskeyword<CR>
    \:unlet s:old_iskeyword<CR>

Above, I did it with line-continuations. If you prefer, you could instead define a function:

nnoremap <silent> K :call MyGrep()<CR>

function! MyGrep() abort
  let old_iskeyword = &l:iskeyword
  setlocal iskeyword+=-
  execute 'grep! "\b' .. expand("<cword>") .. '\b"'
  let &l:iskeyword = old_iskeyword
  • Excellent thanks! I chose the first way as it's faster on usage than the second
    – abbood
    Commented Aug 11, 2022 at 4:07
  • You probably want :setlocal/&l:/etc., even if it may not be necessary
    – D. Ben Knoble
    Commented Aug 11, 2022 at 14:30
  • @D.BenKnoble Like you say, I can't think of any scenario where using :setl would make any difference, but I've edited it in anyway as a best practice.
    – Rich
    Commented Aug 12, 2022 at 6:40
  • @D.BenKnoble I also added in s: and removed the completely unnecessary :unlet, both of which were in an earlier draft but somehow didn't make it into the actual answer.
    – Rich
    Commented Aug 12, 2022 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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