默认情况下,VIM 中的代码完成从单词的开头开始搜索。是否有可能在单词中的任何地方制作它。例如,如果我在 C 头文件中有“MY_DEVICE_CTRL_ADR”和“MY_DEVICE_STAT_ADR”,我可以开始输入 CTRL_,然后让 VIM 为我完成吗?
最佳答案
好的,这是非常粗略的准备,但它似乎工作(至少在简单的情况下)。
首先这里是一个对给定文件执行 vimgrep 的函数。这需要是一个单独的函数,以便以后可以静默调用。
function! File_Grep( leader, file )
try
exe "vimgrep /" . a:leader . "/j " . a:file
catch /.*/
echo "no matches"
endtry
endfunction
现在这是一个自定义完成函数,它调用
File_Grep()
并返回匹配单词的列表。关键是调用add()
函数,如果搜索词 ( a:base
) 出现在字符串中的任何位置,则将匹配项附加到列表中。 (见 help complete-functions
这个函数的结构。)function! Fuzzy_Completion( findstart, base )
if a:findstart
" find start of completion
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '\w'
let start -= 1
endwhile
return start
else
" search for a:base in current file
let fname = expand("%")
silent call File_Grep( a:base, fname )
let matches = []
for this in getqflist()
call add(matches, matchstr(this.text,"\\w*" . a:base . "\\w*"))
endfor
call setqflist([])
return matches
endif
endfunction
然后你只需要告诉 Vim 使用完整的函数:
set completefunc=Fuzzy_Completion
你可以使用
<c-x><x-u>
调用完成。当然,该函数可用于搜索任何文件,而不是当前文件(只需修改 let fname
行)。即使这不是您要寻找的答案,我希望它对您的探索有所帮助!
关于字符串中任意位置的 VIM 代码补全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8051374/