1

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"
  ..
endif

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"
4
  • You can also use <ctrl-r><ctrl-a> Aug 12 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
    Aug 12 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 ;-) Aug 13 at 5:53
  • @VivianDeSmedt I agree!
    – Rich
    Aug 14 at 7:56

1 Answer 1

3

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>
    \:cw<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
  cwindow
endfunction
4
  • Excellent thanks! I chose the first way as it's faster on usage than the second
    – abbood
    Aug 11 at 4:07
  • You probably want :setlocal/&l:/etc., even if it may not be necessary
    – D. Ben Knoble
    Aug 11 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
    Aug 12 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
    Aug 12 at 6:41

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.