Vim的自定义自动完成中的文件列表

时间:2011-08-27 15:05:35

标签: function vim autocomplete arguments

我正在使用Vim的Utl插件,我正在寻找一种创建自定义自动完成功能的方法,以生成文件中id标记的链接。我想要使​​用的格式是:

:CommandName <file> <id tag in file>

我希望该函数的行为类似于第一个参数的标准目录完成。对于第二个参数,我希望在第一个参数中为所有以“id =”开头的字符串搜索文件并返回值。

我已经从Utl主程序包中复制了一个类似的功能,但是我还没有接近使其工作,它目前看起来像这样:

fu! CompleteArgs(dummy_argLead, cmdLine, dummy_cursorPos)

" Split cmdLine to figure out how many arguments have been provided by user
" so far. If Using argument keepempty=1 for split will provide empty last
" arg in case of a new arg is about to begin or an non empty last argument
" in case of an incomplete last argument. So can just remove the last arg.
exe "echo \"cmdline:\" \"".a:cmdLine."\""
let utlArgs=split(a:cmdLine, '\s\+', 1)
execute "echo" string(utlArgs)
echo "echo" "test complete"
"remove the function name
call remove(utlArgs, -1)

" 1st arg to complete
if len(utlArgs)==1
return string(glob("*"))
endi

" 2nd arg to complete
if len(utlArgs)==2
    "insert code here
endif
endfun

有没有人有任何想法?

2 个答案:

答案 0 :(得分:1)

Answering一个非常相似的question我写了一个完整的函数 确定要完成的命令参数的数量。以下是它 版本适合您的情况。

command! -nargs=* -complete=custom,FooComplete Foo echo [<f-args>]
" 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
    if n == 1
        return string(glob('*'))
    endif
    return "1\n2\n3" " Replace this with appropriate id-completion code
endfunction

该函数正确处理转义的空格(这是一个空格的一部分) 参数,不是分隔符)和命令名前的空格。注意 建议候选人中的空白字符应该被转义,否则 一个参数将被Vim视为两个参数。

答案 1 :(得分:1)

您可以尝试frawor。如果您安装它,代码将如下:

execute frawor#Setup('0.0', {'@/fwc': '0.2',
            \           '@/commands': '0.0',})
" No need to write bang here: above command will forbid script to be sourced 
" twice, see :h frawor#Reload for how it can be updated.
function s:F.cmdfunc(file, tag)
    " It will be called when the command launches. Alternatively you can replace 
    " `s:F.cmdfunc' in the below command.add call with a string you already had 
    " before. Note that you will have to replace s: in function names with <SID> 
    " and s:* variables will be just unaccessible.
endfunction
function s:F.gettags(file)
    " This assumes that format is the same as used in ~/.vim/doc/tags. Note that 
    " if there may be any spaces, then you must escape them.
    return map(readfile(a:file), 'matchstr(v:val, "\\v^.{-}\\t")[:-2]')
endfunction
" This replaces direct :command call, see :h frawor-f-command.add
call s:_f.command.add('CommandName', s:F.cmdfunc,
            \{  'nargs': '+',
            \'complete': ['path in*F.gettags(@<)']})