Multiple files in Vim

tung's picture

Emacs was nice. Integrated, powerful, quick, easy to look things up. Shame that it locks up the windowing system under Linux. Yeah, that's a bug report for Ubuntu, but it happens to me under Arch.

So I'm back on Vim. But I do miss Emacs a bit. For one, working with multiple files was a sinch. But what about in Vim?

Multiple files in Vim were always a grey area for me. I'll just focus on one: the one I care about. Read on!

Buffers

Vim has buffers: places where text goes. They may be visible or invisible. You can swap them in and out. Easy, like in Emacs.

To open a file in a new buffer in Vim:

:hide e blah.txt

Your existing file is now hiding the background. To switch back and forth:

:bn
:bp    " or :bN

That's "buffer next" and "buffer previous". You can switch back and forth very easily

Shift+^

To see what hidden buffers you have

:ls

Short for "list".

You can switch right to a buffer with the number shown or the name, like this

:b3
:b test.txt

You can save buffers as usual with :w.

At this point, if you just try to :e (edit) a file, you'll be warned that the current file has not been saved. By default, Vim tries to bump out the buffer rather than hide it. If you want to use "hide" by default, add this to your .vimrc:

set hidden

Or just try it out by entering it as an Ex command, i.e. with colon.

Finally, if you want to remove a buffer from the buffer list

:bd

Windows

Vim can be split into panes. Vim calls them ''windows'', like Emacs. They're handy if you want something a little more direct than your windowing system's Alt+Tab, and/or want to make the most of a maximised terminal.

You can split horizontally

Ctrl+w s

and vertically

Ctrl+w v

Getting rid of a split is simple

Ctrl+w q

Now that we've split our main window into panes, time to move about

Ctrl+w arrow

That'll do it. You can also use the home-row Vim cursor keys, i.e. h j k l.

What if you want to move a window to the very top/bottom/left/right? Easy

Ctrl+w H    " move window to left edge
Ctrl+w J    " move window to bottom edge
Ctrl+w K    " move window to top edge
Ctrl+w L    " move window to right edge

That's all there is to it!

Wrap up

With buffer and window commands, multiple files should be as easy to use in Vim as they were in Emacs.

There are alternatives to buffers. The argument list is one, and recent Vim includes tab support. My approach is like that of Front Mission: it's better to stick with one approach and get decent at that, then to be a jack-of-all-trades and not really get any of them.