How to bind CodeMirror to an object model?


I have a hierarchical object model which has a text representation which I would like to edit with CodeMirror. I would like to map each object with the section of text in the CodeMirror editor and then support two-way updates between CodeMirror and the object model.

Ideally I’d like to avoid writing a lexer and build up the CodeMirror view manually and then perform low-level updates between the two representations e.g. handling each key-press is fine.

Are the any examples or tips you can provide for this type of scenario?


I don’t have much experience with object models, but I’d guess that you’d bind a "change" event handler to have changes from CodeMirror propagate into the model, and you’d use setValue (or replaceRange, depending on the granularity of your diff info) to push changes into CodeMirror (making sure you don’t react to "change" events caused by your own call, in the interest of not getting an infinite loop).

Hi marijn, thanks for the response.

Two more focussed questions you might be able to help with are:

i) Is it possible to tag a region of text with invisible meta-data e.g. an id, so that an onchange event can identify an external entity?
ii) Is it possible to control CodeMirror’s understanding of syntax without giving it a lexer? e.g. by telling it “chars x to y are of type Z”?


The markText method can be used to attach information to a range of text. If you pass it unknown options (say _data: "foo") those will be added as properties to the marker object, which you can retrieve with, for example, findMarksAt.

You can also use markText to style specific ranges of characters, but for classical-style syntax coloring, writing a mode is usually easier and more performant.

1 Like