Better window splitting in Emacs

Emacs’ window-splitting functionality is an ergonomic way to view multiple files at once without having to deal with shuffling around floating windows or clicking between tabs. Anyone who does much with Emacs probably knows already that they can use C-x 2 or C-x 3 to split the window vertically or horizontally.

What always bothered me about this feature was that the newly-created window defaulted to the current buffer, which in layspeak means you had the same file or content open in both your new window and the old. The was almost (but not quite) never the behavior I wanted, since usually you split the window to have multiple buffers on screen at once. Typically, I would do this right after opening a new file or buffer to compare with whatever I already had open, so that I would have the old buffer in one window and the new buffer in another.

This is where having an extensible editor rocks; because in Emacs, if you get tired enough of a behavior, you start hacking elisp and fix it…

The fix is simply a matter of writing some custom elisp functions and overriding the default keybindings with the new functions, and adding it all to your .emacs file. Here’s the code:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Custom splitting functions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
(defun vsplit-last-buffer ()
  (interactive)
  (split-window-vertically)
  (other-window 1 nil)
  (switch-to-next-buffer)
  )
(defun hsplit-last-buffer ()
  (interactive)
  (split-window-horizontally)
  (other-window 1 nil)
  (switch-to-next-buffer)
  )
 
(global-set-key (kbd "C-x 2") 'vsplit-last-buffer)
(global-set-key (kbd "C-x 3") 'hsplit-last-buffer)

What each of these functions does is perform the regular vertical/horizontal split, then switches to the newly-created window and performs “switch-to-next-buffer”. “Next buffer” is the buffer you’d get if you did a “switch-buffer” (C-x b) and just accepted the default. Obviously, Emacs can’t (yet) read your mind and open the buffer you want every time, but “next-buffer” is most likely to be the buffer you want (at least, much more likely than the current buffer, which you already have open in another window).

Copy this code into ~/.emacs, evaluate the buffer (or just the functions), and you’re ready to roll.

I’m going to try this change for a while and see if it sticks, I’ll keep this post updated with changes.

One Thought on “Better window splitting in Emacs

  1. Rob says:

    This is exactly what I was looking for as well. Too bad I yet have to learn elisp. So thanks for sharing!

Leave a Reply

Your email address will not be published. Required fields are marked *