没有输入任何内容时会自动完成Ace

时间:2018-12-14 01:53:30

标签: javascript ace-editor

我正在使用Ace Editor编辑JSON。我的json对象中的每个键都有对应的可能值列表。我想在用户编辑JSON值时通过自动完成功能显示相应的值列表。

这主要在下面的代码段中起作用。唯一的问题是,您必须至少键入一个字符才能触发自动完成功能。如果仅删除该值,则不会触发自动完成。即使删除值后,有没有办法使自动填充功能生效?

<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

1 个答案:

答案 0 :(得分:0)

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

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