Preserving selection across a call to setValue

I’m using codemirror inside of a React application (with this wrapper as a starting point:, which is working pretty well. I’m using it in ‘controlled’ mode (where a change in the props calls setValue on the underlying editor instance). One of the features of my program inserts text into the editor for you at the current cursor position, and after it does I’d like to retain the cursor position, but the call to setValue resets the selection to the beginning of the document.

Right now what I’m doing is grabbing and storing the selection value in every beforeSelectionChange event, which I then manipulate and call setSelection with, but beforeSelectionChange fires when setValue is called. Is there any way for me to tell that the cause was a setValue so I can ignore it? Or perhaps another approach I’m missing?

Why don’t you use replaceRange or replaceSelection, rather than setValue, if you want to only replace part of the document? setValue completely replaces the document, so the old selection doesn’t have a meaning anymore after it ran (the text it refers to might be gone, or lines before it might have been deleted or added, making its line offset meaningless).

Yeah, that would be nice, but it would be difficult to do the way the data flows in this React app. I’d have to just generate the diff where I currently call setValue. For now I’ve solved the issue by just setting a flag during the setValue call and ignoring changes to selection during that time, then restoring the selection afterwards.