vimの外部grepでagを使う

ackというperl製のgrepがいいという情報を聞いたのもつかの間(過去記事参照)、ackの3-5倍高速かつ、コマンド名が33%も短い(笑)agというgrepがいいという情報を聞いたのでvimの外部grepで使えるようにしてみた。

設定は前回と同じく自力でやる。
高機能で安定したもの(たぶん)を求めたい方は専用のプラギンが用意されていますのでそちらをどうぞ。

" grep設定
" ag -> ack -> grep の順に優先して使用
if executable('ag')
    set grepprg=ag\ --nogroup\ -iS
    set grepformat=%f:%l:%m
elseif executable('ack')
    set grepprg=ack\ --nogroup
    set grepformat=%f:%l:%m
else
    set grepprg=grep\ -Hnd\ skip\ -r
    set grepformat=%f:%l:%m,%f:%l%m,%f\ \ %l%m
endif

" 拡張子指定grep
command! -bang -nargs=+ -complete=file Grep call s:Grep(<bang>0, <f-args>)
function! s:Grep(bang, pattern, directory, ...)
    let grepcmd = []
    call add(grepcmd, 'grep' . (a:bang ? '!' : ''))
    if executable('ag')
        if a:0 && a:1 != ''
            call add(grepcmd, '-G "\.' . a:1 . '$"')
        else
            call add(grepcmd, '-a')
        endif
    elseif executable('ack')
        if a:0 && a:1 != ''
            call add(grepcmd, '--' . a:1)
        else
            call add(grepcmd, '--all')
        endif
    else
        if a:0 && a:1 != ''
            call add(grepcmd, '--include="*.' . a:1 . '"')
        endif
    endif
    call add(grepcmd, a:pattern)
    call add(grepcmd, a:directory)
    execute join(grepcmd, ' ')
endfunction

なんと驚きの3段構え!!
agコマンドのオプションは適当に設定したので使ってみてから調整しようと思います。
会社のサーバにもagをこっそり入れようか。