Constantly switching files, how to ensure that the previous files can still be undone and redone?

I have a file tree, whenever I select a file and switch files, how is the previous state cached, such as undo, redo, no matter how I switch files, the previous files can be undone operations

Keep around an editor state for every file that has been opened (and create fresh states when opening a new file).