Buffers
A buffer is an in-memory instance of a file (or an unnamed scratch space). Understanding buffers is essential for working with multiple files efficiently in Neovim.
Core Idea
A buffer holds file content in memory. A window displays a buffer. You can have hundreds of buffers open and only a few windows showing them.
How Buffers Work
flowchart LR
FILE1[file1.lua on disk] --> BUF1[Buffer 1]
FILE2[file2.lua on disk] --> BUF2[Buffer 2]
FILE3[file3.lua on disk] --> BUF3[Buffer 3]
BUF1 --> WIN1[Window 1 — visible]
BUF2 --> WIN2[Window 2 — visible]
BUF3 -.-> HIDDEN[Hidden — not visible]
Opening Files into Buffers
:e filename.lua → edit (open) a file
:e . → open the directory (netrw file browser)
:badd filename.lua → add file to buffer list without displaying
Navigating Buffers
:bnext :bn → next buffer
:bprev :bp → previous buffer
:bfirst :bf → first buffer
:blast :bl → last buffer
:b# → alternate (last) buffer
:b {num} → switch to buffer number
:b {partial} → switch by partial name match
Keymap Recommendations
~/.config/nvim/lua/config/keymaps.lua
vim.keymap.set('n', '<leader>bn', ':bnext<CR>', { desc = "Next buffer" })
vim.keymap.set('n', '<leader>bp', ':bprev<CR>', { desc = "Previous buffer" })
vim.keymap.set('n', '<leader>bd', ':bdelete<CR>', { desc = "Delete buffer" })
vim.keymap.set('n', '<Tab>', ':bnext<CR>', { desc = "Next buffer" })
vim.keymap.set('n', '<S-Tab>', ':bprev<CR>', { desc = "Prev buffer" })
Listing Buffers
:ls → list all buffers with their status
:buffers → same as :ls
Output example:
1 h "init.lua" line 1
2 a "options.lua" line 45
3 %a "keymaps.lua" line 12
4 # "plugins/lsp.lua" line 1
| Symbol | Meaning |
|---|---|
% | Current buffer |
# | Alternate buffer |
a | Active (visible) |
h | Hidden |
+ | Modified (unsaved) |
- | Not modifiable |
Closing Buffers
:bdelete :bd → close current buffer
:bdelete! :bd! → close without saving
:bdelete 3 → close buffer number 3
:%bdelete → close all buffers
warning
:bdelete removes the buffer but does NOT close the window. If it was the only buffer, you'll see an empty window.
Buffer-Specific Commands
:bufdo {cmd} → run command in **all** buffers
:bufdo %s/old/new/ge → replace in all open buffers + suppress errors
:bufdo update → save all modified buffers
Writing and Quitting Buffers
:w → write current buffer
:wa → write all modified buffers
:wq → write and quit
:qa → quit all windows
:qa! → quit all without saving
Buffer Types
| Buffer type | Description |
|---|---|
| Normal buffer | Regular file being edited |
| Scratch buffer | Unnamed, temporary content |
| Help buffer | :help content |
| Terminal buffer | :terminal output |
| Quickfix buffer | :copen list |
Creating a Scratch Buffer
-- Create a new empty scratch buffer
vim.keymap.set('n', '<leader>bs', function()
vim.cmd('enew')
vim.bo.buftype = 'nofile'
vim.bo.bufhidden = 'wipe'
vim.bo.swapfile = false
end, { desc = "New scratch buffer" })