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 ,n :set opfunc=GrepOperatorg@ vnoremap ,n :call GrepOperator(visualmode(), 1)