How do I close the current buffer in Vim?
Answer
:bdelete
Explanation
How it works
The :bdelete command (often abbreviated :bd) removes the current buffer from Vim's buffer list and closes it. If the buffer has unsaved changes, Vim will warn you and refuse to close it unless you force it with :bdelete!.
When you close a buffer, Vim will display the next buffer in the window. If there are no other buffers, the window will show an empty buffer.
You can also close a specific buffer by number or name:
:bdelete 3closes buffer number 3:bdelete file.txtcloses the buffer for file.txt:3,5bdeletecloses buffers 3 through 5
Example
Suppose you have three files open and want to close the current one:
- Run
:lsto see your buffers:1 # "main.py" line 1 2 %a "utils.py" line 5 3 "config.py" line 1 - The
%amarker showsutils.pyis active. Run:bdto close it. - Run
:lsagain to confirm it is removed from the list.
If you have unsaved changes and want to discard them, use :bd! to force-close the buffer without saving.
This is one of the most common buffer management commands and pairs well with :bnext and :bprev for navigating between buffers.