Files and Buffers
So far everything has happened in one file. Real work usually means juggling several. Vim’s model for this is buffers, splits, and tabs, and they solve slightly different problems.
Opening, saving, and quitting
You’ve already used :q! to quit without saving. Here are the commands
you’ll actually use day to day:
:wsaves the current file:w filenamesaves as a new filename:qquits (fails if there are unsaved changes):q!quits and discards unsaved changes:wq(or:x) saves and quits in one step:e filenameopens a file, either a new one or an existing one
Buffers
Every file you open with :e becomes a buffer, whether or not it’s
currently visible on screen. :ls lists all open buffers with a number
next to each one. :b 2 switches to buffer 2. :bn and :bp move to
the next and previous buffer. This is the lightest-weight way to have
several files open at once without splitting your screen.
Splits
A split shows two buffers side by side or stacked, both visible at the
same time. :sp filename opens a horizontal split, :vsp filename opens a
vertical one. Move between splits with Ctrl-w followed by a direction
key (Ctrl-w j moves to the split below, Ctrl-w l moves to the split on
the right, and so on).
Splits are useful when you want to compare two files, or reference one file while editing another, without losing sight of either.
Tabs
Vim’s tabs aren’t quite like browser tabs. A Vim tab is really a saved
layout of splits, so you can have one tab with three files side by side
and another tab with a single file, and switch between the two layouts.
:tabnew filename opens a file in a new tab. gt moves to the next tab,
gT moves to the previous one.
Most beginners get by fine with just buffers and splits and don’t reach for tabs until they’re managing a lot of simultaneous work.
Try it
Create two or three small text files in the same folder, then:
- Open one with
vim file1.txt, then use:e file2.txtto open a second file in the same window. - Run
:lsto see both buffers listed, then use:b 1to jump back to the first one. - Open both at once with
:sp file2.txt. Practice moving between the two splits withCtrl-w jandCtrl-w k. - Close one split with
:q(this closes the split, not the whole editor, as long as another window is still open). - Open a third file in a new tab with
:tabnew file3.txt, then move back and forth between tabs withgtandgT.