如何配置Vim通过ctags实现非前缀部分匹配自动补全
Absolutely, you can make Vim do non-prefix (substring-based) autocompletion—either by tweaking its built-in features with a custom function, or leveraging ctags. Let’s walk through both approaches clearly:
方法1:自定义内置补全函数实现子串匹配
Vim’s default <C-n>/<C-p> uses prefix matching, but we can build a simple custom completion function to handle substring matches instead. Add this to your .vimrc:
function! SubstringComplete(findstart, base) if a:findstart " Locate the start of the current word under the cursor let line = getline('.') let start = col('.') - 1 while start > 0 && line[start-1] =~ '\w' let start -= 1 endwhile return start else " Gather keywords from buffers and tags let keywords = [] call extend(keywords, getcompletion(a:base, 'buffer')) call extend(keywords, getcompletion(a:base, 'tags')) " Filter to keep only keywords containing our substring let matches = filter(keywords, 'stridx(v:val, a:base) != -1') " Deduplicate and sort the results let matches = sort(uniq(matches)) return matches endif endfunction " Set our custom function as the completion handler set completefunc=SubstringComplete " Bind <C-n> to trigger substring completion (replace with your preferred key) inoremap <C-n> <C-x><C-u>
Now when you type test_gener and hit <C-n>, Vim will pull up all keywords (including _generator_function_1) that contain the substring gener. Select the one you want, and it’ll auto-complete to test_generator_function_1.
方法2:结合ctags实现智能补全
If you prefer using ctags, here’s how to set it up for flexible matching:
Generate your tags file:
Navigate to your project root and run:ctags -R --extra=+q .The
--extra=+qflag adds extra metadata to tags, making them easier to work with.Configure Vim to use tags:
Add these lines to your.vimrc:set tags=./tags; " Recursively look for tags files upwards from the current directory set complete+=t " Include tags in Vim's default completion sourcesUse substring completion with tags:
For substring matches, pair this with the custom completion function from Method 1—it already includes tags as a source. Alternatively, if you want to stick to Vim’s native tag completion (<C-x><C-]>), you can tweak your workflow to search for the middle substring (e.g., typegenerthen hit<C-x><C-]>) and manually prependtest_if needed, but the custom function is more seamless.
Extra Tips
- Add these settings to make completion case-insensitive (but still respect uppercase when you type it):
set ignorecase set smartcase - Feel free to rebind the completion shortcut to whatever you prefer—swap
<C-n>with<C-p>or another key if that fits your workflow better.
内容的提问来源于stack exchange,提问作者Leeren

