javascriptcodemirror-6

How to get the text value of a CodeMirror-6 editor


I'm playing with CodeMirror to check if I can use it in our site to allow the user to write c# scripts. I can made a sample easily but I can't find any documentation nabout to get the text value of the editor to send through a form post.

JS Source:

import {StreamLanguage} from "@codemirror/language"
import {csharp} from "@codemirror/legacy-modes/mode/clike"

import {EditorView, basicSetup} from "codemirror"

let editor = new EditorView({
  extensions: [basicSetup, StreamLanguage.define(csharp)],
  parent: document.getElementById('_formengine_script')
})

index.html:

<!doctype html>
<meta charset=utf8>
<h1>CodeMirror!</h1>
<div id="_formengine_script"></div>
<script src="editor.bundle.js"></script>

I think that there must be various ways to solve it but I can't any of them. I've found a lot of information on CodeVersion 5, but I would prefer to use the latest version.


Solution

  • Ran into the same problem. The codemirror 6 documentation is odd. It contains lots of deep dives but lacks of the basics.

    I ended up looking into the unit tests rather than the documentation. You find there a nice test in the history module, the test changes the document and then checks if the document contains the expected data.

    Based on this, assuming editor is a reference to your EditorView, you endup with the following:

    editor.state.doc.toString();
    

    Update: Just after writing this I stumbled upon https://codemirror.net/docs/migration/ just go there to the "Getting the Document and Selection" chapter. It contains the examples your searched for.