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).

Thank you very much, your answer solved my problem, but I have a new problem, in collaborative mode, an old version number is cached, but when switching back to the current file, if someone edited the file, the version number is Will increase, at this time the version will not be synchronized