Skip to content

Instantly share code, notes, and snippets.

@takakd
Forked from 17g/grep_menuitem.vim
Last active January 8, 2017 16:42
Show Gist options
  • Save takakd/03e41c36cb62b8350f589c99a95cd22c to your computer and use it in GitHub Desktop.
Save takakd/03e41c36cb62b8350f589c99a95cd22c to your computer and use it in GitHub Desktop.
NerdTreePluginのgrep_menuitem.vimって便利だけど実行後にこっそりカレントディレクトリが変更されてしまってる。。スペースなどが入った場合もそのまま検索できるようにしたかった。なので少し付け加え。Forked from https://gist.github.com/masaakif/414375
"shove this in ~/.vim/nerdtree_plugin/grep_menuitem.vim
"
"A really rough integration of :grep with nerdtree. Adds a 'g' menu item that
"prompts the user for a search pattern to use with :grep. :grep is run on the
"selected dir (using the parent if a file is selected)
"
" Originally written by scrooloose
" (http://gist.github.com/205807)
" Forked by masaakif
" (http://gist.github.com/205807)
if exists("g:loaded_nerdtree_grep_menuitem")
finish
endif
let g:loaded_nerdtree_grep_menuitem = 1
call NERDTreeAddMenuItem({
\ 'text': '(g)rep directory',
\ 'shortcut': 'g',
\ 'callback': 'NERDTreeGrep' })
function! NERDTreeGrep()
let dirnode = g:NERDTreeDirNode.GetSelected()
let pattern = input("Enter the search pattern: ")
if pattern == ''
echo 'Aborted'
return
else
if match(pattern, '"') >= 0
let pattern = substitute(pattern, '"', '\\"', 'g')
endif
let pattern = join(['"', pattern, '"'], '')
endif
"use the previous window to jump to the first search result
wincmd w
"a hack for *nix to make sure the output of "grep" isnt echoed in vim
let old_shellpipe = &shellpipe
let &shellpipe='&>'
try
" add for save current path
let s:current_dir=expand("%:p:h")
exec 'silent cd ' . dirnode.path.str()
" use the_platinum_searcher
exec 'silent Pt ' . pattern . ' .'
finally
let &shellpipe = old_shellpipe
" add for return to path of before executing grep
exec 'silent cd ' . s:current_dir
endtry
let hits = len(getqflist())
if hits == 0
echo "No hits"
elseif hits > 1
copen
"echo "Multiple hits. Jumping to first, use :copen to see them all."
endif
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment