Preserving state when switching between files

I’m trying to find the best way to switch between files so that changes and undo history are preserved. The goal is to emulate what you would expect form a traditional editor.

My initial approach was to reuse the same EditorView instance and keep and EditorState map in memory for each file and call view.setState(fileStateMap[filename]) when the file is changed. But it looks like setState resets the state itself.

Another approach could be to create an EditorView instance for each file and attach/detach to the DOM when the file is changed. Not sure how this would scale if many files are opened.

Another approach is to store the text content and the history extension in a map for each file and dispatch a ReconfigurationSpec with a tagged history extensions and changes to replace the text content.

Is there a “right” approach here or is there another approach that I’m missing?

What do you mean by that? The technique of keeping a state per ‘buffer’ is how I’d approach this myself.

If I create an initial state that represents a file, make some edits, switch to another file, and the switch back to the original file the edits are gone even though I’m calling view.setState(state); where state is the initial instance. That leads me to believe the state object is reset to its initial state without the edits. Is this the intended behavior? Do I need tell the state to “save” before switching to anther file?

I made a demo at If you make some edits and switch to another language and then switch back you can see the edits don’t persist.

My issue was that I wasn’t reassigning state on every change event so on file change it would always reassign to the initial state. Keeping one state per file seems to work well. Thanks!