Fix undoquit behaviour when dealing with unlisted buffers

It wasn't really returning to the right window as it should have.
Refactor neighbour window checks

Extract extremely similar code's common parts to helper function.