[Emacs] Playing with buffers and windows

I always work with two windows in split mode under a single Emacs frame which are split vertically. I wanted to create an easy way to toggle between the horizontal and vertical splits for two windows and also have the capability of swapping the buffers in the two windows.

Here are two functions that do the same. Note that these will only work for two windows.

;; Swap windows
(defun swap-windows ()
  (interactive)
  (if (= (count-windows) 2)
      (let* ((this-win-buffer (window-buffer))
             (next-win-buffer (window-buffer (next-window))))
        (set-window-buffer (next-window) this-win-buffer)
        (set-window-buffer (selected-window) next-win-buffer))))

(define-key ctl-x-4-map "s" 'swap-windows)

The swap-windows() function swaps the buffers between the two windows while the toogle-window-split() toogles between the vertical and horizontal split. I think I found the toogle-window-split() on StackOverflow and wrote the swap-windows() based on that.


;; Toggle buffer splits from vertical to horizontal
(defun toggle-window-split ()
  (interactive)
  (if (= (count-windows) 2)
      (let* ((this-win-buffer (window-buffer))
             (next-win-buffer (window-buffer (next-window)))
             (this-win-edges (window-edges (selected-window)))
             (next-win-edges (window-edges (next-window)))
             (this-win-2nd (not (and (<= (car this-win-edges)
                                         (car next-win-edges))
                                     (<= (cadr this-win-edges)
                                         (cadr next-win-edges)))))
             (splitter
              (if (= (car this-win-edges)
                     (car (window-edges (next-window))))
                  'split-window-horizontally
                'split-window-vertically)))
        (delete-other-windows)
        (let ((first-win (selected-window)))
          (funcall splitter)
          (if this-win-2nd (other-window 1))
          (set-window-buffer (selected-window) this-win-buffer)
          (set-window-buffer (next-window) next-win-buffer)
          (select-window first-win)
          (if this-win-2nd (other-window 1))))))

(define-key ctl-x-4-map "t" 'toggle-window-split)