Emacs winner-mode to restore your 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 by some operations, such as looking for a help (e.g. C-h k), or checking things in magit.

It's ok to me if I can get back to a previous used layout. Emacs has built in a package for this package: winner-mode. It's very simple, 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, you cann't execute it more than once in a row

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, but we can improve it with the 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"))

Check out my youtube episode below to see how it works like:

UPDATE: After I posted this, @hmelman left a comment below (thanks!) that it was possible to save typing by using built-in repeat-mode since Emacs 28, so here is how to do it in Emacs 28 by defining a keymap for repeat-mode. (If you're using >= Emacs 29, you don't have to tune anything.)

(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

Nice!

Emacs  hydra 

See also

comments powered by Disqus