Search code examples
javascriptautocompleteace-editor

Ace: move caret into the pair of brackets after custom autocompletion


I am new to Ace and I am making a JavaScript editor with it. I added autocompleters to the editor:

var functionCompleter = {
    getCompletions: function(editor, session, pos, prefix, callback) {
        var funcList = ["foo", "bar"]
        callback(null, funcList.map(function(word) {
            return {
                caption: word,
                value: word + "()",
                meta: "Custom Functions"
            };
        }));
    }
}
editor.completers.push(functionCompleter);

After autocompletion:

However I want the caret to be between the round brackets after completing, like this:

so that it would be more convenient to add function parameters

Is there anyway to do it in JavaScript? Thanks


Solution

  • After the auto-completion, you could set the cursor in between the brackets using goToLine function of Ace.

    //Once you Insert the brackets ()
    var pos = editor.selection.getCursor(); //Take the latest position on the editor
    editor.gotoLine(pos.row + 1, pos.column + 2); //This will set your cursor in between the brackets
    

    For the callback you could use the autocompletes insertMatch

    var functionCompleter = {
        getCompletions: function(editor, session, pos, prefix, callback) {
            var funcList = ["foo", "bar"]
            callback(null, funcList.map(function(word) {
                return {
                    caption: word,
                    value: word + "()",
                    meta: "Custom Functions"
    
                    completer: {
                        insertMatch: function(editor, data) {
                            console.log(data.value); // This should give the completed keyword
                            // Here you can get the position and set the cursor
                        }
                    }
                };
            }));
        }
    }
    editor.completers.push(functionCompleter);