Close all open Vim buffers except the current
During development, I often use
:ls to display open buffers. However, after a while, the list can become long. I'm going to add a custom command in my
.vimrc – which is similar to "Close others" in VS Code – that deletes all buffers, except the one I'm currently on.
command BufOnly silent! execute "%bd|e#|bd#"
command– Define a user command
BufOnly– The command name we want to use
silent!– Silence messages,
!silences errors too
execute– Execute the following string expression
Now let's breakdown the actual command. The pipes (
|) break the string into three commands:
%bd– Deletes all open buffers (
bdis short for
e#– Opens the last buffer (
eis short for
bd#– Deletes the
[No Name]buffer that gets created
After restarting Vim or sourcing the updated
.vimrc I can run
:BufOnly to clean up my
Create a binding to run the command quickly whenever needed.
" I have <leader> mapped to <Space>
nnoremap <leader>b :BufOnly<CR>