LoginSignup
4
1

More than 5 years have passed since last update.

fzfを使用してgit grepを行う

Last updated at Posted at 2018-07-30

やりたいこと

  • Git grepをvimから呼び出す
  • fzfを使用して検索されたファイルの該当行に飛ぶ

準備

fzf, fzf.vimを入れておきしょう。

環境は

  • Mac 10.12.6
  • Custom Version 8.0.1633 (KaoriYa 20180324)

やり方

下記を.vimrcに追記して読み込む。
:Gitgrep hogehogeで使用できます。

.vimrc
command! -bang -nargs=+ Gitgrep call fzf#run({
      \ 'source': 'git grep -n -I -i <args>',
      \ 'sink': function('s:line_handler'),
      \ 'dir': s:get_git_base_path(expand("%:p:h")),
      \ 'up': '~40%',
      \ 'options': '+m'
      \ })

" .gitディレクトリがあるパスを取得する
function! s:get_git_base_path(current_dir) abort
  if isdirectory(expand(a:current_dir . '/.git'))
    return a:current_dir
  else
    let sp_dir = split(a:current_dir, '/')
    call remove(sp_dir, -1)
    return s:get_git_base_path('/' . expand(join(sp_dir, '/')))
  endif
endfunction

" 行が選択された時の動き
function! s:line_handler(line)
  let keys = split(a:line, ':')
  " path
  exec 'e '. keys[0]
  " line
  exec keys[1]

  normal! ^zz
endfunction

できなかったこと

  • .gitファイルがなかった場合のエラー処理
  • git grep <pattern> <path>のpath部分の指定

いい方法があれば教えてください。
https://gist.github.com/hsawaji/42a604c955929d26debc44d70885b4f7

参考

https://github.com/junegunn/fzf/wiki/Examples-(vim)
https://gist.github.com/drasill/adb258e1363a22e6e433

4
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1