下面通过解释实现脚本阐明实现的搜索方式:
“ 用户按",fd "(,是<leader>,fd是快捷,含义是查找目录,空格键把焦点带到命令行)F命令可以路径补齐
nmap <silent> <leader>fd :F grep -n --exclude-from $prj/opt/exclude <c-r>=GetGrepWord()<cr> -r
" 在项目中查找,src_filelist是项目文件列表
nmap <silent> <leader>fp :F cat $prj/src_filelist \| xargs grep -s -n <c-r>=GetGrepWord()<cr>
“ 在项目和目录中查找
nmap <silent> <leader>fpd :F cat $prj/src_filelist \| grep x \| xargs grep -s -n <c-r>=GetGrepWord()<cr>
nmap <silent> <leader>fdp :F cat $prj/src_filelist \| grep x \| xargs grep -s -n <c-r>=GetGrepWord()<cr>
" 在quickfix中查找
nmap <silent> <leader>fi :copen<cr>:w! .quickfix<cr>:F cat .quickfix \| grep
com! -complete=dir -nargs=+ F call FindExecute("<args>")
fu! FindExecute(pattern)
let var="\"" . a:pattern . "\""
echo var
cgetexpr system(a:pattern)
cw
endf
map <silent> <F2> ,fp<CR>
map <silent> <F3> :cp<cr>
map <silent> <F4> :cn<cr>
其中GetGrepWord()是从光标所在位置或gui clip board中取合适的关键字,实现如下:
fu! GetGrepWord()
let exclude_chars = [',', ')', '(', '*', ';', '[', ']', "\'", "\"", ":", "{", "}", "\n", "\\"]
let word=expand("<cword>")
let sel=@*
"if selection is too long, discard it
if strlen(sel) >= 30
let sel=""
endif
for C in exclude_chars
let word=substitute(word, C, "", "g")
let sel=substitute(sel, C, "", "g")
endfor
if strlen(word) >= 3 "discard too short word, we won't grep it.
" we always search the whole word for keyword under cursor
return "'\\\\<" . word . "\\\\>'"
endif
if strlen(sel) >= 3
" replace whitespace and tab with .
let sel=substitute(sel, " ", ".", "g")
let sel=substitute(sel, "\t", ".", "g")
return sel
endif
return ""
endf