对象的 ACE 编辑器自动完成

ACE Editor AutoComplete for an Object

假设我有一个对象 foo,它有两个键 bar, baz。我想创建一个自定义 getCompletions,这样当我输入 foo. 时,它会显示 barbaz。我怎么做?回调中的 prefix 变量仅包含最后按下的键。

在我的真实示例中,在执行此操作之前,我需要进行 AJAX 调用以获取 foo 的键,这就是我需要自定义自动完成的原因。

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

例如,如果我们将wordList作为一个全局数组,然后当用户输入foo。我们可以将这两个词都添加到 wordList 中,然后在自动完成器中使用。

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
        }
    }
});

在自动完成器中,我们可以映射 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];

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

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