Search code examples
javascriptjquerycodemirror

CodeMirror editor: show hint after specific key pattern like @@


I am using CodeMirror as editor with show-hint.js and anyword-hint.js as example. By default, hints appear after pressing Ctrl-Space.

Problem:

I want CodeMirror to show hints after I type @@ along with Ctrl-Space.

What I have tried already:

I tried adding extraKeys like "'@'": "autocomplete" and "'@'-'@'": "autocomplete", but it does not work. It works with a single @, but not with @@.

HTML: (save as .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>

Solution

  • I solved it like this.If there is a better suggestion , please post.

    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);
          }
        }
      }
    });