Skip to main content

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
:bnext   :bnnext buffer
:bprev :bpprevious buffer
:bfirst :bffirst buffer
:blast :bllast 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

:lslist 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
SymbolMeaning
%Current buffer
#Alternate buffer
aActive (visible)
hHidden
+Modified (unsaved)
-Not modifiable

Closing Buffers

:bdelete   :bdclose current buffer
:bdelete! :bd!close without saving
:bdelete 3close buffer number 3
:%bdeleteclose 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

:wwrite current buffer
:wawrite all modified buffers
:wqwrite and quit
:qaquit all windows
:qa!quit all without saving

Buffer Types

Buffer typeDescription
Normal bufferRegular file being edited
Scratch bufferUnnamed, 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" })

What's Next