CodeMirror编辑器:显示特定键模式后的提示,如@@

时间:2017-01-31 08:42:34

标签: javascript jquery codemirror

我使用CodeMirror作为编辑器,以show-hint.jsanyword-hint.js为例。默认情况下,按Ctrl-Space后会显示提示。

问题:

我希望CodeMirror在输入@@Ctrl-Space之后显示提示。

我已尝试过的内容:

我尝试添加extraKeys "'@'": "autocomplete""'@'-'@'": "autocomplete",但它不起作用。它适用于单个@,但不适用于@@

HTML:(另存为.html)

<!doctype html>
<title>CodeMirror: Any Word Completion Demo</title>
<meta charset="utf-8" />
<link rel=stylesheet href="https://codemirror.net/doc/docs.css">
<link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">
<link rel="stylesheet" href="https://codemirror.net/addon/hint/show-hint.css">
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/addon/hint/show-hint.js"></script>
<script src="https://codemirror.net/addon/hint/anyword-hint.js"></script>
<script src="https://codemirror.net/mode/javascript/javascript.js"></script>
<article>
  <h2>Any Word Completion Demo</h2>
  <form>
    <textarea id="code" name="code">
      function isInt(n) { return n % 1 === 0; }
    </textarea>
  </form>
  <script>
    CodeMirror.commands.autocomplete = function(cm) {
      cm.showHint({
        hint: CodeMirror.hint.anyword
      });
    };
    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
      lineNumbers: true,
      extraKeys: {
        "Ctrl-Space": "autocomplete",
        "'@'": "autocomplete",
      }
    });
  </script>
</article>

1 个答案:

答案 0 :(得分:1)

我这样解决了。如果有更好的建议,请发帖。

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  extraKeys: {
    "Ctrl-Space": "autocomplete",
    "'@'": function(cm) {
      var charTomatch = '@';
      var curretCursorPosition = cm.getCursor();
      var backwardCursorPosition = {
        line: curretCursorPosition.line,
        ch: curretCursorPosition.ch - 1
      };
      var forwardCursorPosition = {
        line: curretCursorPosition.line,
        ch: curretCursorPosition.ch + 1
      };
      var backwardCharacter = cm.getRange(backwardCursorPosition, curretCursorPosition);
      var forwardCharacter = cm.getRange(curretCursorPosition, forwardCursorPosition);
      //update text anyway
      cm.replaceRange(charTomatch, curretCursorPosition);
      //
      if (backwardCharacter === charTomatch || forwardCharacter === charTomatch) {
        CodeMirror.commands.autocomplete(cm);
      }
    }
  }
});