Search code examples
javascripthtmljqueryeditorcodemirror

How to simulate a keypress with button click in CodeMirror?


I made a CodeMirror based editor, but I've some problem.

<textarea id="code"></textarea>
<script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "htmlmixed",
    lineWrapping: true,
    matchBrackets: true,
    styleActiveLine: true
  });
</script>

I'm trying to simulate some keypress with button click.

<button onclick="add '<' to textarea"> &lt; </button>
<button onclick="add '</' to textarea"> &lt;/ </button>
<button onclick="trigger ctrl-space in textarea"> ctrl-space </button>
<button onclick="trigger ctrl-f in textarea"> ctrl-f </button>

Solution

  • Here is a simple snippet of what you are asking. To simulate triggering of shortcut keys, you have to call a manually all methods this shortcuts calls as mentioned in the snippet JS. There are explanations in the code. If you have some difficulty to implement this, you can share it below.

    var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
      mode: "htmlmixed",
      lineWrapping: true,
      lineNumbers: true,
      matchBrackets: true,
      styleActiveLine: true,
      extraKeys     : {
        "Ctrl-Space": "YOUR FUNCTIONS",
        // ...
      }
    });
    
    editor.getDoc().setValue("<p>2020</p>");
    
    function add(str) {
      var cm = editor.getDoc();
      var cursor = cm.getCursor();
      cm.replaceSelection(str)
      cm.setCursor(cursor.line, cursor.ch + str.length);
      console.log("Added " + str + " at line " + (cursor.line + 1) + " col " + cursor.ch);
    }
    
    function triggerCTRLSPACE() {
      // ...What <Ctrl + Space> is supposed to do.
      console.log("Ctrl + Space triggered");
    }
    
    function triggerCTRLF() {
      // ...What <Ctrl + F> is supposed to do.
      console.log("Ctrl + F triggered");
    }
    .CodeMirror {
      height: 70px !important;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/theme/tomorrow-night-eighties.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/htmlmixed/htmlmixed.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/mode/xml/xml.min.js"></script>
    
    <textarea id="code"></textarea>
    
    <button onclick="add('<')"> &lt; </button>
    <button onclick="add('</')"> &lt;/ </button>
    <button onclick="triggerCTRLSPACE()"> Ctrl-Space </button>
    <button onclick="triggerCTRLF()"> Ctrl-F </button>