Custom autocomplete in ace-editor does not work af

2019-07-23 13:25发布

问题:

I want to use autocomplete in the ace editor. After the user types foo. I want to suggest foo.bar.

Actually I used the following code:

var langTools = ace.require("ace/ext/language_tools");

var staticWordCompleter = {
    identifierRegexps: [/[\.]/],
    getCompletions: function(editor, session, pos, prefix, callback) {
        console.log(prefix);
        if (prefix == "foo.") {
            var wordList = ["baar", "bar", "baz"];
            callback(null, wordList.map(function(word) {
                return {
                    caption: word,
                    value: word,
                    meta: "static"
                };
        }
        }));

    }
}

langTools.setCompleters([staticWordCompleter])

If I remove identifierRegexps and the if clause, the autocomplete works but not after ".".

I also read this solution but it does not work anymore: Custom autocompleter and periods (.)

回答1:

You can bind the "." and then build your wordList. You can make your wordList global and use in the getCompletions or once you bind the "." use this code to get the before item ie foo, and then insert the value into the editor.

    self.editor.commands.addCommand({
        name: "dotCommand1",
        bindKey: { win: ".", mac: "." },
        exec: function () {
            var pos = editor.selection.getCursor();
            var session = editor.session;

            var curLine = (session.getDocument().getLine(pos.row)).trim();
            var curTokens = curLine.slice(0, pos.column).split(/\s+/);
            var curCmd = curTokens[0];
            if (!curCmd) return;
            var lastToken = curTokens[curTokens.length - 1];

            editor.insert(".");                

            if (lastToken === "foo") {
                // Add your words to the list or then insert into the editor using editor.insert()
            }
        }
   });