【问题标题】:Is there a way to make use of two custom, complete functions in Vimscript?有没有办法在 Vimscript 中使用两个自定义的完整函数?
【发布时间】:2020-03-09 15:27:29
【问题描述】:

有没有办法在 Vim 中实现以下功能?

command! -nargs=* -complete=customlist,CustomFunc1 -complete=customlist,CustomFunc2 Foo call MyFunction(<f-args>)

当从 Vim 命令行调用函数 Foo 时,用户将能够用制表符完成 两个 参数。自动完成将从两个不同的列表中提取。

例如:

:Foo arg1 good<TAB> whi<TAB>

Tab 完成单词:

:Foo arg1 goodyear white

【问题讨论】:

    标签: vim


    【解决方案1】:

    有足够的信息通过 它的论点。知道命令行中的当前光标位置 完成后,可以确定参数的数量 目前正在编辑。这是返回的函数 该数字作为唯一的完成建议:

    " Custom completion function for the command 'Foo'
    function! FooComplete(arg, line, pos)
        let l = split(a:line[:a:pos-1], '\%(\%(\%(^\|[^\\]\)\\\)\@<!\s\)\+', 1)
        let n = len(l) - index(l, 'Foo') - 1
        return [string(n)]
    endfunction
    

    用对其中一个函数的调用替换最后一行 完成特定的论点(假设它们已经写好了)。 例如:

        let funcs = ['FooCompleteFirst', 'FooCompleteSecond']
        return call(funcs[n], [a:arg, a:line, a:pos])
    

    请注意,之前有必要忽略空格分隔的单词 命令名称,因为这些可能是范围的限制,或者 计数,如果命令具有其中任何一个(两者都允许空格)。

    用于将命令行拆分为参数的正则表达式采用 考虑到作为参数一部分的转义空格,以及 不是分隔符。 (当然,完成函数应该转义 建议候选人中的空格,与命令一样 有多个可能的论点。)

    【讨论】:

    • 太好了,谢谢!我可以从中得到一个可行的解决方案,稍后会进行更多调查。
    【解决方案2】:

    vim 没有内置的方法来执行此操作。在这种情况下我要做的是将逻辑嵌入到完成函数中。当您设置-complete=customlist,CompletionFunction 时,将使用三个参数调用指定的函数,顺序如下:

    • 当前参数
    • 到目前为止的整个命令行
    • 光标位置

    因此,您可以分析这些并根据您是否在第二个参数上调用另一个函数。这是一个例子:

    command! -nargs=* -complete=customlist,FooComplete Foo call Foo(<f-args>)
    function! Foo(...)
      " ...
    endfunction
    
    function! FooComplete(current_arg, command_line, cursor_position)
      " split by whitespace to get the separate components:
      let parts = split(a:command_line, '\s\+')
    
      if len(parts) > 2
        " then we're definitely finished with the first argument:
        return SecondCompletion(a:current_arg)
      elseif len(parts) > 1 && a:current_arg =~ '^\s*$'
        " then we've entered the first argument, but the current one is still blank:
        return SecondCompletion(a:current_arg)
      else
        " we're still on the first argument:
        return FirstCompletion(a:current_arg)
      endif
    endfunction
    
    function! FirstCompletion(arg)
      " ...
    endfunction
    
    function! SecondCompletion(arg)
      " ...
    endfunction
    

    这个例子的一个问题是它会因为包含空格的补全而失败,所以如果有这种可能,你将不得不进行更仔细的检查。

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2020-03-05
      • 2019-03-13
      • 2023-03-21
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多