vimtricks.wiki Concise Vim tricks, one at a time.

How do I close all buffers except the current one in Vim?

Answer

:%bd | e#

Explanation

How it works

Vim does not have a built-in single command to close all buffers except the current one, but you can achieve this with a two-part command: :%bd | e#.

Here is what each part does:

  • :%bd deletes all buffers. The % range means all buffers, and :bd is short for :bdelete.
  • | e# is piped as a second command. e# re-opens the alternate file, which was your current buffer before :%bd closed everything.

The result is that all buffers are removed except the file you were editing. Your cursor position and window layout may reset, but the correct file is restored.

Example

Suppose you opened many files during a coding session:

:ls
  1      "app.py"       line 1
  2      "models.py"    line 45
  3 %a   "views.py"     line 12
  4      "urls.py"      line 1
  5      "settings.py"  line 30

You want to keep only views.py (buffer 3, the current one). Type:

:%bd | e#

Now :ls shows only:

  6 %a   "views.py"     line 1

Note that the buffer gets a new number because it was re-opened. If any buffers have unsaved changes, Vim will refuse to delete them. Use :%bd! | e# to force-close without saving.

For a more targeted approach, you can close a range of buffers: :1,5bd closes buffers 1 through 5, or :bd 1 3 5 closes specific buffer numbers.

Next

How do you yank a single word into a named register?