Search code examples
emacswindow

Jump to the previous window when closing the current


I have few problems with the focus jump after closing the current window in multiple-window situation. E.g. I have 3 windows (1, 2, 3) opened in the stack. I am in window 2, I horizontally split the current window (there are 1,2,3,4 windows and current is 3), I quit he window and the cursor jumps to window 3. It feels quite unintuitive. How can I make that in this scenario the focus gets to window 2?


Solution

  • Try the following function:

    (defun delete-window-select-sibling (&optional WINDOW)
      (interactive)
      (let ((sibling (or (window-prev-sibling WINDOW)
                         (window-next-sibling WINDOW))))
        (delete-window WINDOW)
        (when sibling
          (select-window sibling))))
    

    You can bind it to C-x 0 by putting it into your init file together with the following line:

    (global-set-key (kbd "C-x 0") 'delete-window-select-sibling)
    

    In my opinion, a small auxiliary function like the above is preferable to advising delete-window because some modes might rely on how the latter works.