Vim has a built-in command to close all windows except the current one (:only), which is nice for focusing on a single buffer. Sometimes I want to cleanup my buffers by closing all of the buffers except for the current one.
This can be done with the command:
:%bdelete|edit #|normal `"
How it Works
By separating with a bar (|) we can put multiple commands on one line (see :help :bar). So our command is actually three separate commands run one after another.
%bdeleteedit #normal `"
%bdelete
The %bdelete command deletes (closes) all buffers.
Using bdelete (without the % prefix) deletes a buffer. (see :help bdelete)
The % represents from 1 up to the highest value. (see :help :%)
Since we can prefix a command with a range (e.g. :3,5bdelete will delete buffers 3 through 5), it is as if we are running :1,999bdelete except instead of 999 Vim automatically uses the largest buffer number.
edit #
The :edit {file} command opens a file for editing when that file is given as a parameter. (e.g. :edit ~/.vimrc will open my .vimrc file for editing). (see :help edit_f)
The # in this context represents the alternate filename (see :help _# and :help alternate-file). You can see the value of # with
:echo expand('#')
normal `”
The normal command allows us to execute a normal mode command from the command line. (see :help :normal).
When we run `" in normal mode we jump to the cursor position where we last exited the current buffer. (see :help `")
Summary
So when you run :%bdelete all buffers are deleted including the current buffer leaving you in a new empty buffer.
The alternate file is the last buffer you were viewing before they all closed so :edit # opens that file.
Then normal `" is the same as pressing `" in normal mode, which jumps us to our last cursor position in that buffer.
Mapping
By adding the following to our .vimrc we can use :BufOnly to close all buffers except the current buffer.
command! BufOnly execute '%bdelete|edit #|normal `"'
Related
There is a Vim plugin called BufOnly, which does the same thing with some added functionality.
This StackOverflow answer for Vim: Close All Buffers But This One was helpful in writing this.
Once I have a Preserve function (shared below) I have created something like:
In case you want to share all this follow:
https://bitbucket.org/snippets/sergio/9nbyGy