且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对象的 ACE 编辑器自动完成

更新时间:2023-02-04 18:23:14

getCompletions中不用前缀,你可以绑定键."然后建立你的wordList.您可以将 wordList 设为全局并在 getCompletions 中使用,或者在绑定."后使用.使用此代码获取之前的项目即 foo,然后将值插入编辑器.

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

比如,如果我们把wordList作为一个Global数组,那么当用户输入foo时.我们可以将这两个词都添加到 wordList 中,然后在 Autocompleter 中使用.

For example, If we take wordList as a Global array, and then when the user enters foo. we can add both the words into the wordList and then use in the Autocompleter.

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 (bar, baz) to the global word list so that the autocomplete can show both bar, baz
           // Append the words to wordList here
        }
    }
});

在 Autocompleter 中,我们可以映射 wordList

Inside the Autocompleter we can map the wordList

var staticWordCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {

    callback(null, wordList.map(function(word) {
        return {
            caption: word,
            value: word,
            meta: "static",
            completer: {
                insertMatch: function(editor, data) {
                    var insertedValue = data.value;
                    if(insertedValue === "bar" || insertedValue === "baz") {
                        // You can clear the world list here
                    }
                }
            }
        };
    }));
  }
}
editor.completers = [staticWordCompleter];

为了始终使用自动完成而不是等待用户输入下一个字符来调用自动完成列表,您可以在初始化期间使用以下代码片段,

In order to use the Autocompletion always instead of waiting for the user to type the next characters to invoke the autocompletion list you could use the below snippet code during the initialization,

editor.commands.on("afterExec", function (e) {
    if (e.command.name == "insertstring" && /^[\w.]$/.test(e.args)) {
        editor.execCommand("startAutocomplete");
    }
});