Search code examples
vimautocompleteomnicomplete

How to set different auto-completion behaviour in vim for different types of auto completions?


The default behaviour of vim is to write down the first match it found and show a drop down menu with all other. When I use it to auto complete code stuff (like function names from a library) it is often awkward to use as it chooses the longest word and drops down a long list that takes too much effort to either delete half the word or manually search the menu of similar words.

example : I use OpenCV and when I write cvCr(<Ctrl-x><Ctrl-o>) it writes cvCreate2DHMM and shows a menu with some 20-30 things in it all starting with cvCreate. Then I have to either delete half the word or search manually in the menu.

There is a trivial way to change that behaviour to only write down the longest common match like most IDEs do (it's in the manual and I know how to find it).

However when I use <Ctrl-x>s to fix a spelling error I prefer the default behaviour.

Is there a way to set the behaviour separately for different auto-completions ?


Solution

  • You mean you want to toggle longest from the 'completeopt' option?!

    You'd have to overwrite the completion triggers, and prepend a no-op :map-expr to change the option, like this:

    function! CompleteoptLongest( isEnable )
        set completeopt-=longest
        if a:isEnable
            set completeopt+=longest
        endif
        return ''
    endfunction
    :inoremap <expr> <SID>CompleteoptLongestOn CompleteoptLongest(1)
    :inoremap <expr> <SID>CompleteoptLongestOff CompleteoptLongest(0)
    
    :inoremap <script> <C-n> <SID>CompleteoptLongestOn<C-n>
    " Repeat for all other completion commands you use...
    
    :inoremap <script> <C-x><C-s> <SID>CompleteoptLongestOff<C-x><C-s>