Search code examples
javascriptcodemirror

How can I add a character at cursor?


I'm trying to add a row of 'Hotkeys' to Code Mirror. For a normal <textarea id=code> I could do: insertAtCursor(code,'hello') With:

function insertAtCursor(textArea,text) 
{
    if (textArea.setSelectionRange)
    {
        textArea.value = textArea.value.substring(0,textArea.selectionStart) + text + textArea.value.substring(textArea.selectionStart,textArea.selectionEnd) + textArea.value.substring(textArea.selectionEnd,textArea.value.length);
    } 
    else if (document.selection && document.selection.createRange) 
    {
        textArea.focus();
        var range = document.selection.createRange();

        range.text = text + range.text;
    }
}

How could I do this with a CodeMirror instance?


Solution

  • Here's a small example where you want to insert an extra character for autocompletion. If user starts typing a ( you want to add an extra ) and set the cursor one place back so he can directly continue to type.

    editor.on('keypress', function(cm,e){
      console.log("keypress: "+e.charCode);
      if(e.charCode === 40) { //check for ( and autocomplete with ) while placing cursor inside ()
          e.preventDefault(); //ignore this key
          editor.replaceSelection("()"); //replace with ()
          editor.setCursor(editor.getCursor().line,editor.getCursor().ch-1); //set cursor back one position
          return false;
       }
    });