Restore Emacs' Window Layouts


If you've been using Emacs for a while, I bet you must have encountered the annoying problem that your Emacs window layout gets messed up after some operations, such as looking for a help (e.g. C-h k), or checking things in the magit status buffer.

I'm happy if I can just get back to the previous layout that I had before, and guess what? Emacs happens to have that capability built in – the winner-mode package, what a surprise!

It's very simple. Actually, it only has three commands:

  1. M-x winner-mode, to enable/disable the function
  2. C-c left (winner-undo), to go back to a previous layout, execute it repeatedly to go back further
  3. C-c right (winner-redo), to go back again to a recent layout. Unfortunately, we can't execute it more than once in a row.

But for winner-undo, it's a little bit tedious to type a lot of C-c left if you have to go back a long way. Don't worry, we can avoid that with a little help of a hydra recipe:

(defhydra hydra (global-map "C-c w")
  "Navigate the time machine of the window layout"
  ("p" winner-undo "Previous layout")
  ("n" winner-redo "Next layout"))

Now, we can go a few layouts back easily. For example, typing C-c w p p will get us to the layout before the previous layout. Check out this youtube episode of mine to see how that works:

UPDATE: After I posted this, @hmelman left a comment below saying that it's possible to save typing by using built-in repeat-mode since Emacs 28, thanks man!

So here is how to do that in Emacs 28 by defining a keymap using repeat-mode, nice! And, if you're using Emacs >= 29, you don't even have to tweak anything at all!

(defvar w/winner-repeat-map
  (let ((map (make-sparse-keymap)))
    (define-key map (kbd "<left>") 'winner-undo)
    (define-key map (kbd "<right>") 'winner-redo)
    map)
  "Keymap to repeat `winner' key sequences.  Used in `repeat-mode'.")
(put 'winner-undo 'repeat-map 'w/winner-repeat-map)
(put 'winner-redo 'repeat-map 'w/winner-repeat-map)

(repeat-mode)                           ; enable it
Emacs  hydra 

See also

comments powered by Disqus