Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM Code completion anywhere in the string

Tags:

vim

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?

like image 226
Paul Avatar asked Nov 08 '11 13:11

Paul


People also ask

Does vim have code completion?

To initiate code completion enter insert mode and type Ctrl-X Ctrl-U . By default Vim will open a popup if there is more than one completion. When using omnifunc you will use Ctrl-X Ctrl-O to start code completion.


1 Answers

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!

like image 171
Prince Goulash Avatar answered Oct 14 '22 00:10

Prince Goulash