0

I got this in my .vimrc:

set grepprg=grep\ -nriI\ --exclude=tags\ --exclude-dir=vendor

" The Silver Searcher
if executable('ag')
  " Use ag over grep
  let &grepprg = "ag --nogroup --nocolor --ignore wiki --ignore tags --ignore tests --ignore dist -w"

  ..
endif

" bind \ (backward slash) to grep shortcut
command -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!
nnoremap \ :Ag<SPACE>

when I type \ the prompt turns into :Ag, when I search for single words, it works like a charm. But when I search for sentences with spaces in between (even if i enclose with ") nothing works.. how do i fix this?

4

 Why It's Broken

The problem is that you've used -bar in your command definition. This attribute is used to specify that you can use a | after an invocation of your new command e.g.:

:Ag search_term | copen

However, the -bar flag also checks for " characters to start a comment (See :help :command-bar.)

This means that when you issue the command:

:Ag "find me"

The "find me" is interpreted as a comment, resulting in Vim running the command:

:Ag

...and you get the following error (because you specified that arguments are required with -nargs=+):

E471: Argument required

Workarounds

One workaround is to use ' characters instead (noting the difference between the two when used in e.g. bash — now you can no longer search for things containing single quotes):

:Ag 'find me'

Alternatively, you can escape whitespace:

:Ag find\ me

How to Fix It

However, you can also simply remove the -bar attribute:

command -nargs=+ -complete=file Ag silent! grep! <args>|cwindow|redraw!

N.B. It is not necessary to use the -bar attribute to allow the use of | in the definition of a command, in case that's why you added it.

After doing so, all of the following will work:

:Ag find\ me
:Ag 'find me'
:Ag "Can't find me"

Extra Credit

If you don't want to have to use quotes or escaping when invoking :grep or :Ag, you can get Vim to do the escaping for you:

function! Ag(args) abort
  execute "silent! grep!" shellescape(a:args)
  cwindow
  redraw!
endfunction

command -nargs=+ -complete=file Ag call Ag(<q-args>)

Now this works:

:Ag find me
  • wow.. vim is an ocean, and you guys are the experienced navigators.. you got my appreciation, and respect. – abbood Jan 25 '18 at 5:53
  • hey Rich my ag stil l doesn't find something like this Mail::queueOn.. it seems the :: are messing things up? – abbood Jan 31 '18 at 6:41
  • @abbood I just copied the code above into a new .vimrc and it seems to find Mail::queueOn fine (I tested both versions). What output do you get if you replace execute with echom command, run Ag::queueOn, and then run the command :messages? – Rich Jan 31 '18 at 9:42

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.