问题
Let's say I have an object foo
that has two keys bar, baz
. I want to create a custom getCompletions
so that when I have typed foo.
then it shows bar
and baz
. How do I do that? The prefix
variable in the callback only contains the very last key pressed.
In my real example, I'd need to make an AJAX call to get the keys of foo
before doing this, that's why I need a custom auto completion.
回答1:
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.
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
}
}
});
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");
}
});
来源:https://stackoverflow.com/questions/50890809/ace-editor-autocomplete-for-an-object