Insert Text at Caret on CodeMirror Textarea

When using CodeMirror, your <textarea /> will be visually replaced by an editor provided by CodeMirror and most of your code relative to your <textarea /> won't be usable as is.

What's going on on the background is that your actual <textarea /> will first be marked with a style display: none;. Not displayed, no event binded on the <textarea /> will actually trigger. Then, CodeMirror will actually add his own code to the DOM to display a new editor at the position of your <textarea /> which is now not displayed.

For example, the HTML code for a newly initialized CodeMirror editor with the string 'Hello World' written in it would looks like:

<div class="CodeMirror-lines">
    <div style="position: relative; outline: none;">
        <div class="CodeMirror-measure">
            <div style="width: 50px; height: 50px; overflow-x: scroll;"></div>
        </div>
        <div class="CodeMirror-measure"></div>
        <div style="position: relative; z-index: 1;"></div>
        <div class="CodeMirror-cursors">
            <div class="CodeMirror-cursor" style="left: 74px; top: 0px; height: 13px;">&nbsp;</div>
        </div>
        <div class="CodeMirror-code">
            <div style="position: relative;">
                <div class="CodeMirror-gutter-wrapper" style="position: absolute; left: -29px;">
                    <div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 0px; width: 20px;">1</div>
                </div><pre><span style="padding-right: 0.1px;"><span class="cm-variable">Hello</span> <span class="cm-variable">World</span></span></pre></div>
        </div>
    </div>
</div>

Your <textarea /> is no longer being used.

CodeMirror provides natively a programming API which can be used to do what you want. Basically, the steps required are:

  • Check when the editor is focused.
  • When focused, check if a picture has previously been clicked and if a selected text is available (the alt of the image).
  • If yes, insert the selected text (the alt of the image) at the current position.

The JavaScript code associated to these steps would looks like:

// Listen to the editor focus events.
editor.on('focus', function () {
  // Only insert if a value has been previously selected.
  if (selected.length > 0) {
    // Fetch the current CodeMirror document.
    var doc = editor.getDoc();

    // Insert the text at the cursor position.
    doc.replaceSelection(selected);

    // Clear the selection so it isn't copied repeatedly.
    selected = '';
  }
});

You can check a working example on this JSFiddle.