代码自动补全或是代码提示,是编程中常用的功能,能帮助我们提高编码的效率
Vim 作为一个文本强大的文本编辑器,通过一些设置后,就可以实现代码补全的功能。
使用内建代码提示
快捷键
首先Vim是内建代码补全功能的,在不需要通过任何设置的情况下就能使用。
在您编辑代码的时候,键入 ctrl+x, ctrl+o, ctrl+n, ctrl+p 等快捷键,就会弹出智能提示的菜单,具体使用方法请看Vim中的插入模式补全
例如,php中我在 -> 操作符之后键入 ctrl+N
改进一下
这样虽然是补全了,但是不是那种输入时即时匹配的一定要输入 ->t 然后键入 ctrl+N 这样出现的提示才是 t开头的。
现在我们要实现已经出现提示菜单后输入字母实现即时的过滤和匹配,其实很简单,在你的 .vimrc 中加入下面这句代码
set completeopt=longest,menu
关于这句代码的意义,可以查看Vim的completeopt选项
现在用起来舒适多了
全能补全 (omni)
关于 omni 可以查看这里的介绍。
我们常用的全能补全是 CTRL-X CTRL-O , 但每次按这样两个组合键也比较麻烦,我们可以映射一个快捷键。
"==== omni
imap <C-L> <C-x><C-o>
这样按 CTRL-L 就行了。当然还有 SuperTab 插件来帮助我们用 Tab 键来实现所有的补全功能。
(在php文件中使用全能补全的效果)
使用 autocomplpop.vim 插件
介绍
用惯一些IDE的朋友,一开始可能不习惯Vim的自动补全,主要是每次都要按下一个组合键才会出现提示,而不是像IDE里面那样只要输入了某个操作符就会触发自动补全。
autocomplpop.vim 这个插件就可以很好的解决这个问题。
基本使用
首先访问链接[1],下载 autocomplpop.vim 后,放到Vim文件目录下的plugin目录中,然后重启一下 vim 就会发现在编码时会自动的弹出提示了。
打开 autocomplpop.vim ,可以再 DOCUMENT 部分看到使用方式与一些设置。
增加智能提示触发命令
该插件的默认设置可以完成一些基本的提示,但是每种语言都不同,需要触发 全能 (omni) 补全 的操作符也不同,所幸 autocomplpop 可以让我们自己定制触发的命令模式,这样就可以实现无限扩展以达到自己的需求。
autocomplpop已经实现了部分语言的自动全能补全,比如 ruby文件中按 "." 或者 "::" 就会触发全能补全,看一下改插件中已经实现的一些语言
" Which completion method is used depends on the text before the cursor. The
" default behavior is as follows:
"
" 1. The keyword completion is attempted if the text before the cursor
" consists of two keyword character.
" 2. The filename completion is attempted if the text before the cursor
" consists of a filename character + a path separator + 0 or more
" filename characters.
" 3. The omni completion is attempted in Ruby file if the text before the
" cursor consists of "." or "::". (Ruby interface is required.)
" 4. The omni completion is attempted in Python file if the text before
" the cursor consists of ".". (Python interface is required.)
" 5. The omni completion is attempted in HTML/XHTML file if the text
" before the cursor consists of "<" or "</".
" 6. The omni completion is attempted in CSS file if the text before the
" cursor consists of ":", ";", "{", "@", "!", or in the start of line
" with blank characters and keyword characters.
光有这些我们可能还不能满足,下面我们试着自己来添加一些触发命令
加入PHP的全能提示触发命令
php 中 一般是会在 "$", "->", "::" 后需要出现自动补全,在 .vimrc 中加入以下代码:
if !exists('g:AutoComplPop_Behavior')
let g:AutoComplPop_Behavior = {}
let g:AutoComplPop_Behavior['php'] = []
call add(g:AutoComplPop_Behavior['php'], {
/ 'command' : "/<C-x>/<C-o>",
/ 'pattern' : printf('/(->/|::/|/$/)/k/{%d,}$', 0),
/ 'repeat' : 0,
/})
endif
这样就可以了。
注重,某些时候,可能会在第一次按下触发补全的操作符时停顿一会,这可能是因为可匹配的项目过多,Vim正在索引,过后就会快了。