Find a file (via recursive directory search) in Vim

后端 未结 15 1153
感情败类
感情败类 2020-12-22 18:42

Is there any way to search a directory recursively for a file (using wildcards when needed) in Vim? If not natively, is there a plugin that can handle this?

15条回答
  •  一整个雨季
    2020-12-22 18:56

    Quickfix-like result browsing

    Usage:

    Find my.regex
    

    Outcome:

    • a new tab opens
    • each line contains a relative path that matches a grep -E regex
    • hit:
      • or gf to open the file on the current line in a new tab
      • gf to open the file on the current tab and lose the file list

    Find all files instead:

    Find
    

    Alternative methods:

    • Gfind my.regex: only search for Git tracked files (git ls-files). Fugitive request: https://github.com/tpope/vim-fugitive/issues/132#issuecomment-200749743
    • Gtfind my.regex: like Gfind, but search from the git Top level instead of current directory
    • Locate somefile: locate version

    Code:

    function! Find(cmd)
      let l:files = system(a:cmd)
      if (l:files =~ '^\s*$')
        echomsg 'No matching files.'
        return
      endif
      tabedit
      set filetype=filelist
          set buftype=nofile
      " TODO cannot open two such file lists with this. How to get a nice tab label then?
      " http://superuser.com/questions/715928/vim-change-label-for-specific-tab
      "file [filelist]
      put =l:files
      normal ggdd
      nnoremap   gf
      execute 'autocmd BufEnter  lcd ' . getcwd()
    endfunction
    command! -nargs=1 Find call Find("find . -iname '*'" . shellescape('') . "'*'")
    command! -nargs=1 Gfind call Find('git ls-files | grep -E ' . shellescape(''))
    command! -nargs=1 Gtfind call Find('git rev-parse --show-toplevel && git ls-files | grep -E ' . shellescape(''))
    command! -nargs=1 Locate call Find('locate ' . shellescape(''))
    

提交回复
热议问题