Skip to content

Instantly share code, notes, and snippets.

@shapeoflambda
Created May 23, 2020 07:56
Show Gist options
  • Save shapeoflambda/603f65b1b49c0d31020f6bf0a41ab341 to your computer and use it in GitHub Desktop.
Save shapeoflambda/603f65b1b49c0d31020f6bf0a41ab341 to your computer and use it in GitHub Desktop.
Grep operator
function! GrepOperator(type, ...)
" We will select and yank to perform the operation.
" So, saving the previous selection and default register
" content, so that we can reset it after the operation is complete.
let sel_save = &selection
let &selection = "inclusive"
let reg_save = @@
if a:0 " Invoked from Visual mode, use gv command.
silent exe "normal! gvy"
elseif a:type == 'line'
silent exe "normal! '[V']y"
else
silent exe "normal! `[v`]y"
endif
" Grep and open if there are results
execute "silent grep ". shellescape(@@) ." | cwindow"
" Restore the default register content and previous selection
let &selection = sel_save
let @@ = reg_save
endfunction
nnoremap <silent> ,n :set opfunc=GrepOperator<CR>g@
vnoremap <silent> ,n :<C-U>call GrepOperator(visualmode(), 1)<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment