Shuffling Emacs windows

Emacs lets you split your screen into windows, what other applications might call panels. This can be quite handy. However, I often want to move the windows around and I couldn’t find how to do that. I asked Xah Lee, he posted the question on G+, and Mark Hepburn answered with a pointer to code that does what I wanted: buffer-move.el

(Strictly speaking the windows don’t move; the buffers move between the windows. But I think of it as moving the windows around.)

Lucas Bonnet explains how his buffer-move works:

This file is for lazy people wanting to swap buffers without
typing C-x b on each window. This is useful when you have :

+--------------+-------------+
|              |             |
|    #emacs    |    #gnus    |
|              |             |
+--------------+-------------+
|                            |
|           .emacs           |
|                            |
+----------------------------+

and you want to have :

+--------------+-------------+
|              |             |
|    #gnus     |   .emacs    |
|              |             |
+--------------+-------------+
|                            |
|           #emacs           |
|                            |
+----------------------------+

This is exactly what I had in mind. I did have one problem, however, though it wasn’t with buffer-move per se. The file defines four functions for moving buffers between windows and suggests key bindings. The author says he uses the following.

(global-set-key (kbd "<C-S-up>")     'buf-move-up)
(global-set-key (kbd "<C-S-down>")   'buf-move-down)
(global-set-key (kbd "<C-S-left>")   'buf-move-left)
(global-set-key (kbd "<C-S-right>")  'buf-move-right)

This works fine, except when one of the windows contains an org-mode buffer. Org-mode has its own bindings for control-shift-up etc.

I learned that global-set-key does not globally set a key binding! Well, it does as long as there are no conflicts. But local bindings, i.e. bindings specific to a mode, have precedent. After some searching and trail-and-error, I added the following to my .emacs to override org-mode’s local bindings.

(add-hook 'org-mode-hook '(lambda ()
   (local-set-key [C-S-up]    'buf-move-up)
   (local-set-key [C-S-down]  'buf-move-down)
   (local-set-key [C-S-left]  'buf-move-left)
   (local-set-key [C-S-right] 'buf-move-right)))

3 thoughts on “Shuffling Emacs windows

  1. Better yet, (customize-variable ‘org-replace-disputed-keys) and restart Emacs.

  2. That’s neat but what if I’d like to move window to new frame?
    I mean from ||gnus|emacs|| to ||gnus||,||emacs||.
    How do I create new frame and move current window over there?

  3. Nice article! Only downside is that I would need to re-map those functions in org-mode. Luckily, I don’t really use multiple sets of TODO keywords or increment clocks in org that way.

    @Abe, you could do that by going into that buffer and then issuing following sequence:

    C-x 5 2

Comments are closed.