See changes between doc generations


#1

I want to continuously scan the contents of a document, and only re-scan when things have changed. Obviously doc.changeGeneration() and doc.isClean() are great ways to tell if the document needs to be re-scanned or not.

My question is, is there a way to find out only the parts of the editor that have changed? Meaning, get all the changes between two generations?

It would be preferable to just get the invalidated line ranges, e.g., lines 12-16 have changed and require re-scanning.

Small example:

const cm = new CodeMirror(element, {});

cm.replaceSelection("asdf");
let gen = cm.doc.changeGeneration(true);
cm.replaceSelection("\nanother change");
cm.replaceSelection("foo\nbar");

// Later on
if (!cm.doc.isClean(gen)) {
  // !!! I'd like to get all the changes that have happened since `gen`.
  // !!! Meaning, "\nanother change" and "foo\nbar", etc. 
  // !!! Or, preferably just the invalidated lines: 2-3
}

I’m currently thinking of two separate approaches:

  1. Loop through cm.doc.history to find where the last generation was and read all those changes.
  2. Listen to cm.on("changes"), and collect all the change events - then scan through them for the changes since the last event.

Is there a good/better way to find all the changes/invalidated lines that have occurred since that last generation?


#2

You’ll have to listen to the "changes" event — the history doesn’t currently contain this information, at least not in a usable form.


#3

Excellent, thank you!