简体   繁体   English

gvim自定义命令参数

[英]gvim custom command arguments

I'm trying to create a custom command to use vimgrep to search a pattern in a given file pattern like 我正在尝试创建一个自定义命令以使用vimgrep在给定的文件模式中搜索模式,例如

:command -nargs=* Find :tabnew <bar> vimgrep /<arg1>/gj <arg2> <bar> cw <cr>

How do I access the arguments arg1 and arg2? 如何访问参数arg1和arg2?

Edit 1 : I came up with the following solution 编辑1 :我想出了以下解决方案

command! -nargs=* Find call VimFind(<f-args>)
function! VimFind(searchPattern,filePattern,...)
  let searchCommand = 'vimgrep /'.a:searchPattern.'/gj '.a:filePattern.'|cw'
  if a:0 > 0 && a:1 == 'n'
    let searchCommand = 'tabnew|'.l:searchCommand
  endif
  execute l:searchCommand
endfunction

Is there a cleaner way to do this? 有没有更清洁的方法可以做到这一点?

Edit 2 : Ah well, the above function errors out and then opens a new tab when nothing is found 编辑2 :嗯,上面的函数错误出来,然后什么也没有找到时打开一个新的选项卡

By using <f-args> and a function, Vim parses the individual command arguments for you; 通过使用<f-args>和一个函数,Vim为您解析了各个命令参数。 that's a correct way to do this. 这是正确的方法。

To deal with errors from :vimgrep , you have to enclose the execute l:searchCommand with try...catch , eg: 要处理:vimgrep错误,您必须将try...catch execute l:searchCommand包含在try...catch ,例如:

try
    execute l:searchCommand
catch /^Vim\%((\a\+)\)\=:E/
    tabclose

    echohl ErrorMsg
    echomsg 'Search failed'
    echohl None
endtry

I don't see why you need to :tabnew before the search; 我不明白为什么您需要在搜索 :tabnew ; if you do this afterwards (but before the :cw ), you don't have to clean up in case of failed searches. 如果之后(但在:cw之前)执行此操作,则无需清理以防搜索失败。

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

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