Ace编辑器-当我按空白键时会触发自动完成

时间:2019-11-24 17:55:51

标签: javascript autocomplete ace-editor

在编辑器中按空格时不会触发自动完成功能,是否有按空格键时会触发自动完成功能的选项? 请看一下这个演示:


    [jsfiddle] https://jsfiddle.net/xbaha/cbfe6tx4/53/

我希望在我输入“我的名字是”时触发自动完成功能(请注意“是”后有一个空格),然后使用onchange事件添加了应该弹出的建议,但它不起作用,我必须输入字母字符,以便自动填充功能被触发。

有解决方案吗?

1 个答案:

答案 0 :(得分:0)

可以使用自定义处理程序来处理afterExec事件https://github.com/ajaxorg/ace/blob/v1.4.7/lib/ace/ext/language_tools.js#L149

,而不是使用enableLiveAutocomplete选项。

var editor;
var fieldsList = [];

function initAceEditor() {
  editor = ace.edit("aceEditor", {
    theme: "ace/theme/solarized_light",
    mode: "ace/mode/text",
    showPrintMargin: false,
    fontSize: "24px",

    minLines: 3,
    maxLines: 8,
    wrap: true,
    // do not use live autocomplete since we want to invoke more often
    // enableLiveAutocompletion: true,
    enableBasicAutocompletion: true,
  });
  var langTools = ace.require("ace/ext/language_tools");


  var stepLineCompleter = {
    getCompletions: function(editor, session, pos, prefix, callback) {
      var completions = [];
      console.log('before foreach....', this.fields, fieldsList);
      var cursor = session.selection.cursor
      var line = session.getLine(cursor.row).slice(0, cursor.column - prefix.length)
      var fieldsList
      if (line.endsWith("name is ")) {
        fieldsList = ["bob", "james", "alex", "jimmy"];
      } else {
        fieldsList = ["my name is", "completion2", "completion3", "one more"]
      }
      fieldsList.forEach(function(w) {
        completions.push({
          value: w,
        });
      });
      callback(null, completions);
    }
  }

  langTools.setCompleters([stepLineCompleter]);
  langTools.addCompleter(stepLineCompleter);
  var Autocomplete = ace.require("ace/autocomplete").Autocomplete
  var doLiveAutocomplete = function(e) {
    var editor = e.editor;
    var hasCompleter = editor.completer && editor.completer.activated;
    var session = editor.session
    var cursor = session.selection.cursor
    var line = session.getLine(cursor.row).slice(0, cursor.column)

    // We don't want to autocomplete with no prefix
    if (e.command.name === "backspace") {
      // do not hide after backspace
    } else if (e.command.name === "insertstring") {
      if (!hasCompleter) {
        // always start completer
        var completer = Autocomplete.for(editor);
        // Disable autoInsert
        completer.autoInsert = false;
        completer.showPopup(editor);
      }
    }
  };

  editor.commands.on('afterExec', doLiveAutocomplete);


}

initAceEditor()
#aceEditor {
  position: absolute;
  top: 10%;
  right: 0;
  bottom: 30%;
  left: 0;
}
<script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="https://rawgithub.com/ajaxorg/ace-builds/master/src/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>



<div id="aceEditor"></div>