35

I want to get an instance of CodeMirror (it is binded to a textarea '#code'). From an onclick-event I want to add a value to the current value of the CodeMirror instance. How can this be achieved? From the docs I can't seem to find anything to get an instance and bind it to a loca var in javascript.

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129

6 Answers6

73

Another method I have found elsewhere is as follows:

//Get a reference to the CodeMirror editor
var editor = document.querySelector('.CodeMirror').CodeMirror;

This works well when you are creating the CodeMirror instance dynamically or replacing an existing DOM element with a CodeMirror instance.

fregante
  • 29,050
  • 14
  • 119
  • 159
ashatte
  • 5,442
  • 8
  • 39
  • 50
  • 4
    And in order to use the original selector rather than just finding the first CodeMirror: `var originalDiv = $('#code'); originalDiv.next('.CodeMirror')[0].CodeMirror;` – Kavi Siegel Oct 28 '14 at 08:06
19

Someone just posted an answer but removed it. Nevertheless, it was a working solution. Thanks!

-- Basically this was his solution:

// create an instance
var editor = CodeMirror.fromTextArea('code');
// store it
$('#code').data('CodeMirrorInstance', editor);
// get it
var myInstance = $('code').data('CodeMirrorInstance');
// from here on the API functions are available to 'myInstance' again.
Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
10

There is a getWrapperElement on code mirror editor objects which gives you the root DOM element of the code mirror instance:

var codemirrorDomElem = editor.getWrapperElement();
Alireza Mirian
  • 5,862
  • 3
  • 29
  • 48
3

You can find the instance starting with the <textarea> and moving to the next sibling.

Native

  • Functional

    document.querySelector('#code').nextSibling,
    
  • Selector

    document.querySelector('#code + .CodeMirror'),
    

jQuery

  • Functional

    $('#code').next('.CodeMirror').get(0),
    
  • Selector

    $('#code + .CodeMirror').get(0)
    

Extra: A more advanced solution involving clipboard.js -> JSFiddle Demo


Example

// Selector for textarea
var selector = '#code';

$(function() {
  var editor = CodeMirror.fromTextArea($(selector).get(0), {
    mode: 'javascript',
    theme: 'paraiso-dark',
    lineNumbers : true
  });
  editor.setSize(320, 240);
  editor.getDoc().setValue(JSON.stringify(getSampleData(), null, 4));
  
  $('#response').text(allEqual([
    document.querySelector(selector).nextSibling,        // Native - Functional
    document.querySelector(selector + ' + .CodeMirror'), // Native - Selector
    $(selector).next('.CodeMirror').get(0),              // jQuery - Functional
    $(selector + ' + .CodeMirror').get(0)                // jQuery - Selector
  ]));
});

function allEqual(arr) {
  return arr.every(function(current, index, all) {
    return current === all[(index + 1) % all.length];
  });
};

// Return sample JSON data.
function getSampleData() {
 return [
        { color: "red",     value: "#f00" },
        { color: "green",   value: "#0f0" },
        { color: "blue",    value: "#00f" }
    ];
}
#response { font-weight: bold; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/codemirror.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/theme/paraiso-dark.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.7.0/codemirror.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>All equal?: <span id="response"></span></div>
<textarea rows="10" cols="60" id="code"></textarea>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1

I am using with Vue CLI 3, vue-codemirror component like this:

<codemirror id="textarea_editor" v-model="textarea_input" :options="cm_editor_config"></codemirror>

import codemirror to use within page:

import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'

and simply add codemirror inside components object, thereafter configuration in data section is:

codemirror_editor: undefined,
cm_editor_config: {
    tabSize: 4,
    mode: 'application/json',
    theme: 'base16-dark',
    lineNumbers: true,
    // lineWrapping: true,
    styleActiveSelected: true,
    line: true,
}

and initialized the object in mounted lifecycle section of Vue:

mounted () {
    if ( !this.codemirror_editor ) {
        this.codemirror_editor = $('#textarea_editor').find('.CodeMirror').get(0).CodeMirror;
    }
    // do something with this.codemirror_editor
}

Hope this would help many one.

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
-2

You can simply drop the var: instead of having

var editor = CodeMirror.fromTextArea...

Just have

editor = CodeMirror.fromTextArea...

Then editor is directly available to use in other functions

Enigma Plus
  • 1,519
  • 22
  • 33
  • This is a bad idea, as dropping the `var` statement is equal to using `window.editor = ...` - it pollutes the global namespace and potentially overwrites existing variables. – Philipp Dec 23 '22 at 17:10