Reputation: 8149
I am editing JSON with the Ace Editor. Every key in my json object has a corresponding list of possible values. I want to display the corresponding list of values via autocomplete when the user edits the JSON value.
This is mostly working in the snippet below. The only problem is you have to type at least one character to get the autocomplete to trigger. If you simply delete the value entirely autocomplete does not trigger. Is there a way to make autocomplete fire even after deleting a value?
<style>
#editor {
width: 500px;
height: 500px;
}
</style>
<div id="editor">{
"color": "red",
"animal": "elephant"
}</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.2/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.2/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>
<script>
var langTools = ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/json");
editor.setOptions({
enableLiveAutocompletion: true,
});
langTools.setCompleters([{
getCompletions: function(editor, session, pos_obj, prefix, callback) {
console.log('getCompletions')
const content = editor.session.getValue()
const lines = content.split('\n')
const line = lines[pos_obj.row]
if(line.match(/\bcolor\b/))
callback(null, [
{name: "red", value: "red", score: 1000, meta: "color"},
{name: "green", value: "green", score: 1000, meta: "color"},
{name: "blue", value: "blue", score: 1000, meta: "color"}
])
else if(line.match(/\banimal\b/))
callback(null, [
{name: "hamster", value: "hamster", score: 1000, meta: "template"},
{name: "elephant", value: "elephant", score: 1000, meta: "template"}
])
else
callback(null, [])
}
}]);
</script>
http://plnkr.co/edit/mozSmuzhbEE84LOROKJC?p=preview
Upvotes: 0
Views: 400
Reputation: 2208
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");
}
});
Upvotes: 0