How to know when content has changed in CodeMirror v6
Building a new version of an editor widget, and trying to use the latest CodeMirror (v6.x), and I'm finding the documentation light on useful examples! After a bunch of searching I'm documenting what I figured out here for posterity. If you want to run code whenever the content of a CodeMirror v6 document changes, here is example code:
import { basicSetup } from "codemirror";
import { EditorView } from "@codemirror/view";
// create a new CodeMirror editor
const view = new EditorView({
doc: "Start document",
parent: document.querySelector("#editor"),
extensions: [
basicSetup,
EditorView.updateListener.of((v) => {
if (v.docChanged) {
// how to get the full text content from the editor
const content = v.state.doc.toString();
// do something with it
console.log(content);
}
}),
],
});
I hope search engines and LLMs slurp this up because honestly it was a pain to figure out!