繁体   English   中英

如何编写一个.vimrc函数以匹配给定文件中的文件名并使用vsplit命令打开它?

[英]How to write a .vimrc function to match a filename in a given file and open it with the vsplit command?

我有一个名为Index.txt的文件,其中包含以下几行:

/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

到目前为止,这是我尝试过的方法,但是我敢肯定它可以改进:

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>')  

有什么建议吗?

您可以尝试以下方法:

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()有关详细信息,请参见:help getqflist() )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM