Ads by Google

Thursday, December 1, 2011

Moving buffers between windows

If you're new to emacs, it might be a good idea to read this post to know the difference between frames and windows before you can follow this post.

I had to do some fair amount of coding recently with lots of interlinked files.  With so many windows open and with my limited screen estate, I soon settled on a 3 window layout with the screen split horizontally and the top half split again into 2.  This way I could read code flowing off to the right on the bottom half while referring to the called functions in the other 2 windows on top.


But I soon found myself switching to those buffers to read a bit more on the definitions and losing my window layout.  A quick ask on gnu.emacs.help turned up this emacswiki page, the last elisp function that I reproduce below was perfect for my needs.

(defun rotate-windows ()
  "Rotate your windows"
  (interactive)
  (cond ((not (> (count-windows)1))
     (message "You can't rotate a single window!"))
    (t
     (setq i 1)
     (setq numWindows (count-windows))
     (while  (< i numWindows)
       (let* (
          (w1 (elt (window-list) i))
          (w2 (elt (window-list) (+ (% i numWindows) 1)))
         
          (b1 (window-buffer w1))
          (b2 (window-buffer w2))
         
          (s1 (window-start w1))
          (s2 (window-start w2))
          )
         (set-window-buffer w1  b2)
         (set-window-buffer w2 b1)
         (set-window-start w1 s2)
         (set-window-start w2 s1)
         (setq i (1+ i)))))))


There are a number of other options available too as mentioned by Sundar Vasan in his post. They give your more options and key bindings to use.

2 comments:

Jürgen said...

More concise, less imperative implementation:
https://gist.github.com/1415844

Anonymous said...

This is very helpful, thanks! Any suggestion on what keystrokes to bind to?