Showing posts with label autocompletion. Show all posts
Showing posts with label autocompletion. Show all posts

Tuesday, February 1, 2011

Some useful settings and plugins for VI Editor : Part 2 - Autocompletion

In the first part I talked about some useful settings, In this part I am going to explain how to use Autocompletion with VI editor.

To set autocompletion on, add the following settings in .vimrc file in your home directory or alternatively you can add them to /etc/vim/vimrc file, that will enable these settings for all users on the system.
   
set ofu=syntaxcomplete

Vim has autocomplete functionality for all common web development contexts. Now, If you are editing a file in vim which ends with .php, .html, .css, .js, .sql, .rb, or .py. Vim's "omnifunc" feature combined with its built-in autocomplete feature will show autocomplete options specific to the corresponding language. You can type a few words/chars and can press (in insert mode) following commands to autocomplete words from different context, vim shows a box below the cursor containing the options, with the first entry highlighted:

CTRL-X_CTRL-O - To search matching words in coding language manual
CTRL-X_CTRL-L - To search matching words in whole lines
CTRL-X_CTRL-N - To search matching words in the current file
CTRL-X_CTRL-K - To search matching words in dictionary
CTRL-X_CTRL-I - To search matching words in the current and included files
CTRL-X_CTRL-F - To search matching words in file names
CTRL-X_CTRL-] - To search matching words in tags
CTRL-N        - To search matching words in all of above

Autocompletion using the TAB key

Using above commands are little difficult. For easy use we can remap them to TAB key. Add the following function to your vimrc file. This function determines, wether we are on the start of the line text (then tab indents) or if we want to try autocompletion

func! InsertTabWrapper()
    let col = col('.') - 1
    if !col || getline('.')[col - 1] !~ '\k'
        return "\<tab>"
    else
        return "\<c-p>"
    endif
endfunction

Remap the TAB key to select action with InsertTabWrapper, add the following line in vimrc file

inoremap <buffer> <tab> <c-r>=InsertTabWrapper()<cr>

Now, when you will press a TAB key, it will check wheather you are on the start of a line, if yes it will indent your code, otherwise it will try to show you autocompletion window.


For other posts related to VIM settings and plugins you can also visit

Some useful settings and plugins for VI Editor : Part 1 - General settings
Some useful settings and plugins for VI Editor : Part 3 - PHP documentor
Some useful settings and plugins for VI Editor : Part 4 - CodeSniffer Integration
Some useful settings and plugins for VI Editor : Part 5 - Comment a code block