2016-04-25 56 views
0

我有一個名爲Index.txt下列行的文件:如何編寫.vimrc函數以匹配給定文件中的文件名並使用vsplit命令打開它?

/Project/A/B/C/D/main.c 
/Project/A/B/C/D/main_backend.c 
/Project/A/B/C/D/main_frontend.c 

我想創建一個命令調用Fsearch使用正則表達式中Index.txt執行搜索,匹配第一次出現和執行:vsplit與它。例如,如果我執行:

:Fsearch main_backend.c 

Vim應該執行:

:vsplit /Project/A/B/C/D/main_backend.c 

,如果我執行:

:Fsearch main*.c 

Vim應該執行:

:vsplit /Project/A/B/C/D/main.c 

這是我到目前爲止所嘗試的,但我很確定它coul d改進:

function! CopyMatches(reg) 
let l:file = grep -m 1 a:reg ~/Index.txt 
echom l:file 
if len(l:file) > 0 
    exec ':vsp ' . l:file 
else 
echom 'File not found: ' . l:file 
end 
endfunction 
command! -nargs=* Fsearch call CopyMatches('<args>') 

有什麼建議嗎?

回答

1

你可以試試這個:

function! CopyMatches(reg) 
    execute "silent! grep!" a:reg " ~/Index.txt" 
    redraw! 
    let l:file = getqflist() 
    if len(l:file) > 0 
     let l:path_head = fnamemodify("~/workspace", ":p") 
     for l:item in l:file 
      let l:current_file = l:path_head . "/" . l:item["text"] 
      if match(l:current_file, getcwd()) != -1 
       execute 'vsplit' fnamemodify(l:current_file, ":~:.") 
       return 
      endif 
     endfor 
     echom "File not found:" a:reg 
    else 
     echom "File not found:" a:reg 
    endif 
endfunction 

command! -nargs=* Fsearch call CopyMatches('<args>') 

說明:

  • :grep內置命令是Vim使用的包裝執行外部grep(見:help grep瞭解更多信息)。
  • :grep命令的:grep!形式不會自動跳轉到第一個匹配(即:grep!不會打開Index.txt)。
  • :silent!命令用於取消默認的全屏grep輸出。
  • Vim使用quickfix list:grep這樣你就可以從getqflist()功能(見:help getqflist()瞭解詳細信息)
+0

由於它的工作原理GR8得到所有出現。如果我想更改行,請使用先前的解決方案執行「silent!grep!」 a:reg「〜/ Index.txt」執行「silent!grep!」 a:reg「〜/ cscope.files」| 「grep'cut -d/-f 5- <<<」$ {PWD}「'」。這樣我總能得到相對的結果。 PLZ任何建議如何做到這一點? – ypp

+0

'system(「pwd | cut -d/-f 5 - 」。expand(「%」))'給出想要的搜索字符串我想用,所以我試着'執行「silent!grep!」 a:reg「〜/ cscope.files」| EXE「silent!grep」系統(「pwd | cut -d/-f 5 - 」。expand(「%」))'但是在執行Ctrl + c之後它仍然繼續運行給出錯誤'E486:pattern not found:dev ' – ypp

+0

說現在我的$ pwd是/ home/user/workspace/Project_1/A/B/C/ ':Fsearch main * .c' 說我得到以下結果(我在grep中沒有使用-m1) /家庭/用戶/工作區/ Project_1/A/B/C/D/main_frontend.c /home/user/workspace/Project_1/A/main_common.c 但我想':Fsearch main * .c'應該只讀取結果,即wrt $ pwd /home/user/workspace/Project_1/A/B/C/main_backend。c /home/user/workspace/Project_1/A/B/C/D/main_frontend.c – ypp

相關問題