Paul
Paul

Reputation: 313

VIM Code completion anywhere in the string

By default code completion in VIM searches from the start of the word. Is it possible to make it anywhere in the word. For example, if I have "MY_DEVICE_CTRL_ADR" and "MY_DEVICE_STAT_ADR" in the C header file, can i start typing CTRL_ and then have VIM complete it for me?

Upvotes: 10

Views: 414

Answers (1)

Prince Goulash
Prince Goulash

Reputation: 15715

Okay, this is very rough-and-ready, but it appears to work (at least in simple cases).

First of all here is a function which performs a vimgrep on a given a file. This needs to be a separate function so it can be called silently later on.

function! File_Grep( leader, file )
    try
        exe "vimgrep /" . a:leader . "/j " . a:file
    catch /.*/
        echo "no matches"
    endtry
endfunction

Now here is a custom-completion function which calls File_Grep() and returns a list of matching words. The key is the call to the add() function, which appends a match to the list if search term (a:base) appears ANYWHERE in the string. (See help complete-functions for the structure of this function.)

function! Fuzzy_Completion( findstart, base )
    if a:findstart
        " find start of completion
        let line = getline('.')
        let start = col('.') - 1
        while start > 0 && line[start - 1] =~ '\w'
            let start -= 1
        endwhile
        return start
    else
        " search for a:base in current file
        let fname = expand("%")
        silent call File_Grep( a:base, fname )
        let matches = []
        for this in getqflist()
            call add(matches, matchstr(this.text,"\\w*" . a:base . "\\w*"))
        endfor
        call setqflist([])
        return matches
    endif
endfunction

Then you just need to tell Vim to use the complete function:

set completefunc=Fuzzy_Completion

and you can use <c-x><x-u> to invoke the completion. Of course, the function could be used to search any file, rather than the current file (just modify the let fname line).

Even if this isn't the answer you were looking for, I hope it aids you in your quest!

Upvotes: 5

Related Questions