created 2004 · complexity basic · author Matt Perry · version 6.0
One of the keys to effective Vim usage is effective buffer management. Vim doesn't force you to click on a tab every time you want to look at another file, but if you don't know how to easily find the buffer you want, it can be just as frustrating.
- When a file is loaded into memory for editing, a new buffer is created to hold it.
- A buffer can be created to hold text that isn't related to a file, such as a directory listing.
- A window is a view port onto a buffer.
- A buffer is active if it is shown in a window.
- A buffer is hidden if it is not shown in a window.
- A buffer is a listed buffer if it is always shown in the buffer list.
- A buffer is an unlisted buffer if it is not shown in the buffer list by default.
- Each buffer is given a unique number when it is first created. It keeps this number for the duration of the Vim session.
- The name of a buffer is the name of the file that has been loaded into it, or for buffers not containing the contents of a file, it can be any string.
:buffers command lists the current buffers. There are two alternate names for this command
:files. By default, only listed buffers will be displayed. Unlisted buffers can be included by appending
!, for example
Switching to another bufferEdit
The command to switch to another buffer is
:buffer, which is often abbreviated as
:buffer can be given either the name or the number of the buffer to edit.
Switching by nameEdit
When using the buffer name as the argument to
:buffer, you don't have to specify the entire name. However, if more than one buffer matches the given argument then the buffers won't be switched.
Any fragment of the buffer name can be used to match against, although buffers which match at the beginning of their name will be selected in preference to buffers which match elsewhere in their name. For example, if you have the buffers request_manager.java and queue_manager.java then
:buffer que matches both of them, but will switch to queue_manager.java as it matches at the beginning.
Tab completion can be used to complete the buffer name,
:buffer any snippet of text
<Tab> will complete to the full buffer name if only one buffer matches any snippet of text. If more than one buffer matches, the matches will be cycled through on further presses of
<tab>. The switch will take place once
<CR> is entered with a unique buffer name. Again, any fragment of the buffer name can be used to complete the matching buffer, for example, request_manager.java can be completed using
r.java<tab>. Instead of <tab>, you can press Ctrl-D to list all matching names.
If you would prefer to be able to select the buffer from the list of partial matches the following function can be used. It will jump to the matching buffer if only one match is found, or if there are many matches it will print a list of the matching buffers in the command-line area, and allow you to select one of the matching buffers by buffer number.
function! BufSel(pattern) let bufcount = bufnr("$") let currbufnr = 1 let nummatches = 0 let firstmatchingbufnr = 0 while currbufnr <= bufcount if(bufexists(currbufnr)) let currbufname = bufname(currbufnr) if(match(currbufname, a:pattern) > -1) echo currbufnr . ": ". bufname(currbufnr) let nummatches += 1 let firstmatchingbufnr = currbufnr endif endif let currbufnr = currbufnr + 1 endwhile if(nummatches == 1) execute ":buffer ". firstmatchingbufnr elseif(nummatches > 1) let desiredbufnr = input("Enter buffer number: ") if(strlen(desiredbufnr) != 0) execute ":buffer ". desiredbufnr endif else echo "No matching buffers" endif endfunction "Bind the BufSel() function to a user-command command! -nargs=1 Bs :call BufSel("<args>")
Switching by numberEdit
If you know the number of the buffer you want to switch to, you can pass that as the argument to
:buffer, for example
:buffer 5 will switch to buffer number 5. An alternative which can be used from normal mode is buffer number
<C-^>, for example
5<C-^> will switch to buffer number 5.
When there are several buffers open in a Vim session, it can become difficult to keep track of the buffers and their respective buffer numbers. If this is the case, switching to a different file can be made easier using a simple map:
:nnoremap <F5> :buffers<CR>:buffer<Space>
F5 is pressed, a numbered list of file names is printed, and the user needs to type a single number based on the "menu" and press enter. The "menu" disappears after choosing the number so it appears only when you need it.
<Space> at the end of the map isn't required, but does help to separate the input from the "prompt". As the
:buffer command is being used to perform the switch, the buffer name could be used instead, if preferred.
:edit command can also be used to switch to a given buffer number if the argument begins with
#. For example,
:edit #5 will switch to buffer number 5. This can be used in the above map to allow the user to view the current buffers and then either enter the number you wish to switch to, or if it isn't yet loaded, delete the
# and enter the path to the file.
Switching to the previously edited bufferEdit
Often the buffer that you want to edit is the buffer that you have just left. Vim provides a couple of convenient commands to switch back to the previous buffer. These are
Both of these technically edit the alternate file, although this is usually the previously edited buffer.
Leaving modified buffersEdit
If Vim is running with its default settings, or in vi compatible mode, the
:buffer command will not abandon the buffer until any changes have been written. There are a few ways this can be changed:
!to the command to force the current buffer to be hidden, despite being modified. For example, if buffer 1 is the current buffer and it has been modified, the command
:b! 2) would hide buffer 1 (keeping its changes), and display buffer 2.
- Set the hidden option (
:set hidden) so any buffer can be hidden (keeping its changes) without first writing the buffer to a file. This affects all commands and all buffers.
- Set the confirm option (
:set confirm) so that when you tell Vim to abandon a buffer but you have unsaved changes, Vim will ask you whether to save your changes first, abandon them, or cancel the action. The choices given do not seem to allow simply hiding the buffer as in the previous options.
- Set either the autowrite or the autowriteall options (
:set autowriteall) to automatically save any changes made to the buffer before it is hidden.
Conveniently accessing buffersEdit
In gvim, you can use the Buffers menu to conveniently access buffers (tear off the menu to make an always-visible list).
Or, put the following in your vimrc:
set wildchar=<Tab> wildmenu wildmode=full
Now, pressing Tab on the command line will show a menu to complete buffer and file names. If you include the following, you can also press F10 to open the buffer menu.
set wildcharm=<C-Z> nnoremap <F10> :b <C-Z>
Try this example to see how powerful the wildmenu is.
:args vehicle.c vehicle.h car.c car.h jet.c jet.h jetcar.c jetcar.h :b <Tab> " offers all buffers in a menu :b car<Tab> " offers car.c car.h :b *car<Tab> " offers car.c jetcar.c car.h jetcar.h :b .h<Tab> " offers the *.h buffers :b .c<Tab> " offers the *.c buffers :b ar.c<Tab> " offers car.c jetcar.c :b j*c<Tab> " offers jet.c jetcar.c jetcar.h
You may want to install the BufExplorer script, and place the following in your vimrc. Pressing Alt-F12 opens a window listing the buffers, and you can press Enter on a buffer name to go to that buffer. Or, press F12 (next) or Shift-F12 (previous) to cycle through the buffers.
" Buffers - explore/next/previous: Alt-F12, F12, Shift-F12. nnoremap <silent> <M-F12> :BufExplorer<CR> nnoremap <silent> <F12> :bn<CR> nnoremap <silent> <S-F12> :bp<CR>
Mappings for buffer numberEdit
If you know the buffer numbers, the following mappings are useful. For example, typing
\1 (assuming the default backslash leader) will switch to buffer number 1.
" Mappings to access buffers (don't use "\p" because a " delay before pressing "p" would accidentally paste). " \l : list buffers " \b \f \g : go back/forward/last-used " \1 \2 \3 : go to buffer 1/2/3 etc nnoremap <Leader>l :ls<CR> nnoremap <Leader>b :bp<CR> nnoremap <Leader>f :bn<CR> nnoremap <Leader>g :e#<CR> nnoremap <Leader>1 :1b<CR> nnoremap <Leader>2 :2b<CR> nnoremap <Leader>3 :3b<CR> nnoremap <Leader>4 :4b<CR> nnoremap <Leader>5 :5b<CR> nnoremap <Leader>6 :6b<CR> nnoremap <Leader>7 :7b<CR> nnoremap <Leader>8 :8b<CR> nnoremap <Leader>9 :9b<CR> nnoremap <Leader>0 :10b<CR> " It's useful to show the buffer number in the status line. set laststatus=2 statusline=%02n:%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P
Some scripts for buffer switching are listed below, in order by the script id. You can search Vim Scripts for "buffer" to find others.
- bufexplorer A popular buffer explorer.
- SelectBuf A fast and extensible buffer explorer.
- selbuff Another buffer select script
- PopupBuffer To select a buffer from a PopUp menu.
- minibufexpl A popular and compact buffer explorer. Clickable tabs w/ `set mouse=a`
- incbufswitch Switch buffers using an incremental search.
- bufmenu2 More balanced buffers menu hierarchy.
- buflist Buffer browser.
- TinyBufferExplorer A 1-file buffer list plugin with grouping.
- bufferlist Simple, fast, and slick non-disturbing buffer list.
- bufmap Automatically maps buffers to function keys.
- buftabs Minimalistic buffer tabs saving screen space.
- bufpos Switch buffer with Alt-<number>.
- tselectbuffer A quick buffer selector/switcher.
- LustyExplorer Dynamic filesystem and buffer explorer.
- QuickBuf Very small but quick and powerful buffer manager.
- fuzzyfinder Explore buffer/file/MRU/favorite with a fuzzy pattern.
- LustyJuggler Switch very quickly between active buffers.
- QuickName Conveniently navigate buffers; incremental search by name.
- bufmru Quickly switch to most recently used buffer.
- vimuiex Commands: VxBufListSelect/VxOpenRecentFile/VxFileBrowser, with filtering and MRU
- Command-T Fast buffer and file navigation
- QuickNameBuf Quickly navigate between buffers using an incremental search by name (a combination of QuickName and QuickBuf)
- Buffergator Lists buffers in a new split, and quickly go to selected buffer in previous window, new (vertical/horizontal) split, or new tab page. Walk up and down buffer list, previewing buffers quickly without leaving buffer list.
- Buffet A fast, easy to use buffer list plugin for switching and managing buffers.buffer list contains tab and window numbers.Provides commands to load, delete, switch,horizontal/vertical/diff split open buffers and command to close opened windows.
- Cycle through buffers including hidden buffers to cycle through existing buffers, in order by buffer number
- Vim buffer FAQ
- :help buffers
- :help buffer
- :help bnext
- :help bprevious
- :help CTRL-^
- :help alternate-file
I suggest changing all mappings starting with
, to start with
<Leader> instead. I know that this is more confusing, but I strongly dislike seeing a perfectly good command — that is
, — go to waste before the user has had a chance to learn it. I think this should be done for all articles. (Spiiph 22:19, September 4, 2009 (UTC))
- Good idea. I changed this tip. I have left a few ',' mappings in the past for simplicity, but consistenly using <Leader> would be better. JohnBeckett 09:52, September 5, 2009 (UTC)
The following simple user-defined command
:Buffer allows switching a buffer in the current window
choosing it from the buffer list:
command -nargs=? -bang Buffer if <q-args> != '' | exe 'buffer '.<q-args> | else | ls<bang> | let buffer_nn=input('Which one: ') | if buffer_nn != '' | exe buffer_nn != 0 ? 'buffer '.buffer_nn : 'enew' | endif | endif
It can be abbreviated as
:lscommand and asks a user for the input which is transferred to
The command with an exclamation mark
:ls! which includes unlisted buffers in the list. Entering a zero as answer creates a new buffer with
:B. (Gmikeus 19:43, December 19, 2010 (UTC))