Improve your efficiency with VIM - 2

From juliano.info

Jump to: navigation, search

Here is another VIM trick. This one allows you to do auto-completion using the Tab key while you type. This script helps me a lot while i'm programming, it makes typing very fast after you get used to.

Tab completion

Put the following code in a file named tab-completion.vim inside your VIM plugins directory (~/.vim/plugin on Linux, \Vim\vimfiles\plugin on Windows):

" Vim script file
" Name:		Tab Completion
" Maintainer:	Juliano Ferraz Ravasi <jferraz users sourceforge net>
" Last Change:	2005-01-22
" Version:	1.0
" Location:	(none)

function! <SID>J_TabWrapper()
    let line = getline('.')
    let col = col('.') - 1

    if col >= 1 && line[col - 1] =~ '\k'
	return "\<C-P>"
    elseif col >= 2 && line[col - 1] == ' ' && line[col - 2] =~ '\k'
	return "\<Left>\<Delete>\<Tab>"
    else
	return "\<Tab>"
    endif
endfunction

function! <SID>J_BackTabWrapper()
    let line = getline('.')
    let col = col('.') - 1

    if col >= 1 && line[col - 1] =~ '\k'
	return "\<C-N>"
    elseif col >= 1 && line[col - 1] =~ '\s'
	return "\<BS>"
    else
	return "\<S-Tab>"
    endif
endfunction

inoremap <Tab> <C-R>=<SID>J_TabWrapper()<CR>
inoremap <S-Tab> <C-R>=<SID>J_BackTabWrapper()<CR>

After loading this plugin (just restart VIM), you'll be able to use Tab while typing to auto-complete the word right before the cursor. Each time you press Tab VIM will complete with the next word above the cursor that matches the same prefix you typed. If you want to insert a <Tab> character rather than auto-completing the previous word, just insert a space before pressing Tab, VIM will erase that space and replace it with a real <Tab>.

Views