Vim tip 19: working with buffers
Multiple files can be opened in Vim within the same tab page and/or in different tabs. From :h windows-intro:
- A buffer is the in-memory text of a file.
- A window is a viewport on a buffer.
- A tab page is a collection of windows.
- :e refreshes the current buffer (
:e
is short for:edit
) - :e filename open a particular file by its path, in the same window
- :e # switch back to the previous buffer, won't work if that buffer is not named
- Ctrl+6 switch back to the previous buffer, works even if that buffer is not named
- Ctrl+^ can also be used
- :e #1 open the first buffer, and so on
- :buffers show all buffers
- :ls or :files can also be used
- :bn open the next file in the buffer list (
:bn
is short for:bnext
)- opens the first buffer if you are on the last buffer
- :bp open the previous file in the buffer list (
:bp
is short for:bprevious
)- opens the last buffer if you are on the first buffer
Use :set hidden if you want to switch to another buffer even if there are unsaved changes in the current buffer. Instead of this setting, you can also use :hide edit filename to hide the current unsaved buffer. You'll still get an error if you try to quit Vim without saving such buffers, unless you use the !
modifier.
See :h 'autowrite' option if you want to automatically save changes when moving to another buffer.
See :h 22.4 and :h buffer-hidden for user and reference manuals on working with buffer list.
Video demo:
See also my Vim Reference Guide and curated list of resources for Vim.