Search code examples
emacsdot-emacs

When opening 2 files in emacs, how can I have them appear side-by-side?


Sometimes I launch emacs from the command line with 2 files, as follows:

emacs foo.txt bar.txt

This opens the emacs window, split vertically:

foo.txt
-------
bar.txt

How can I edit my .emacs file so that they show up side-by-side, like this?:

        |
foo.txt | bar.txt
        |

EDIT: To clarify, I know how to make this happen after emacs has launched (M-x 0, M-x 3, then re-visit bar.txt in the right window). I just want emacs to split side-by-side by default when I launch it, so I don't have to.


Solution

  • Here's a function that will change a pair of vertical windows to a pair of horizontal windows:

    (defun 2-windows-vertical-to-horizontal ()
      (let ((buffers (mapcar 'window-buffer (window-list))))
        (when (= 2 (length buffers))
          (delete-other-windows)
          (set-window-buffer (split-window-horizontally) (cadr buffers)))))
    

    To do this automatically on startup, add this function to emacs-startup-hook:

    (add-hook 'emacs-startup-hook '2-windows-vertical-to-horizontal)