Search code examples
javascriptautocompletecodemirror

Auto-complete with CodeMirrror


I am trying to implement auto-complete using CodeMirror show-hint addon, specifically with sql-hint. I want it auto-complete as I type.

What I am doing right now is,

codemirror_editor.on("change", function(instance) {
    CodeMirror.commands.autocomplete(instance);
});

But the problem is, it completes words before I even type a single letter for a word. For example after space, it gives a long list of all possible tokens. I want it to show up only if some characters are typed. Can someone please help with that?


Solution

  • This is how I solved this, after Marijn's answer.

    codemirror_editor.on("inputRead", function(instance) {
        if (instance.state.completionActive) {
            return;
        }
        var cur = instance.getCursor();
        var token = instance.getTokenAt(cur);
        var string = '';
        if (token.string.match(/^[.`\w@]\w*$/)) {
            string = token.string;
        }
        if (string.length > 0) {
            CodeMirror.commands.autocomplete(instance);
        }
    });
    

    This may be specific to SQL.

    I am answering my own question to share the actual solution for the question.