I’m going to assume that the reader is an Emacs user and skip over a bunch of intro stuff. The reason you might want this is because sometimes the default behaviour of Emacs produces a window where the split is vertical and that makes the text unreadable or just against your preferences, or a window where the split is horizontal and you wish it were the other way for whatever reason.
Sure, you can push C-x 0
to close the one window and then split it again in the orientation you prefer and switch the new window to the other window that you had open before. But that’s a lot of keystrokes when you just want to switch.
The following will allow you to switch between them being horizontally and vertically split.
First, open up your ~/.emacs
file and add the following:
;; Toggle horizontal and vertical window splitting
(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))))))
(global-set-key (kbd "C-x |") 'toggle-window-split)
Then save and restart Emacs. To switch a vertically split window into a horizontally split window with the same buffers visible, all you need to do now is press: C-x |
Note: It doesn’t work when there’s more than 2 windows.