Search code examples
texteditorcodemirror

How to programmatically change the editors value in CodeMirror 6?


Calling console.log(editor.state.doc) reveals:

TextLeaf {
    text: ["Test Text"],
    length: 9,
    Symbol(Symbol.iterator): function
}

So the text or editors value is there, however if I call editor.state.doc.text = ["New Test Text"] I get missing text, so it doesn't seem to be the intended way to change it.

How do I actually do it?

Pseudo Code

editor.getDoc().setValue('New Test Text');


Solution

  • The necessary information can be found here: https://codemirror.net/examples/change/

    Example:

    editor.dispatch({
      changes: {from: 0, to: editor.state.doc.length, insert: 'New Test Text'}
    });
    

    editor being a EditorView instance.