Vim Tips Wiki
Register
Advertisement
Tip 686 Printable Monobook Previous Next

created March 25, 2004 · complexity basic · author Matt Perry · version 5.7


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.

Terminology

Some of the terms used in this tip are briefly explained below. For more details see the buffer FAQ and :help windows-intro.

  • 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.

Listing buffers

The :buffers command lists the current buffers. There are two alternate names for this command :ls and :files. By default, only listed buffers will be displayed. Unlisted buffers can be included by appending !, for example :ls!.

Switching to another buffer

The command to switch to another buffer is :buffer, which is often abbreviated as :b, :bu or :buf. :buffer can be given either the name or the number of the buffer to edit.

Switching by name

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 wont 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 t_ma<tab> or req<tab> or 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 number

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>

When 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.

The <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.

The :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 buffer

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 <C-^> and :b#.

Both of these technically edit the alternate file, although this is usually the previously edited buffer.

Leaving modified buffers

If Vim is running with its default settings, or in vi compatible mode, the :buffer command won't abandon the buffer until any changes have been written. There are a few ways this can be changed.

  • A ! can be appended (:buffer!) which will discard any changes made to the buffer.
  • Setting the hidden option (:set hidden) will keep the changes to the buffer without writing them to the file. This affects all commands and all buffers.
  • Setting either the autowrite or the autowriteall options (:set autowrite or :set autowriteall) will automatically save any changes made to the buffer.

Conveniently accessing buffers

Built-in features

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 ,, to open the buffer menu.

set wildcharm=<C-Z>
nnoremap ,, :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

Plugins

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 number

If you know the buffer numbers, the following mappings are useful.

" 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 ,l :ls<CR>
nnoremap ,b :bp<CR>
nnoremap ,f :bn<CR>
nnoremap ,g :e#<CR>
nnoremap ,1 :1b<CR>
nnoremap ,2 :2b<CR>
nnoremap ,3 :3b<CR>
nnoremap ,4 :4b<CR>
nnoremap ,5 :5b<CR>
nnoremap ,6 :6b<CR>
nnoremap ,7 :7b<CR>
nnoremap ,8 :8b<CR>
nnoremap ,9 :9b<CR>
nnoremap ,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

Scripts

If the above tips don't provide what you require, there are, of course, several scripts covering buffer switching. A few of them are linked to below. Or you could search Vim Scripts for others.

Searching for "buffer" on vim.org, purpose is to give a quick overview about available scripts. Ordered by script_id .

  • bufexplorer (popular) Buffer Explorer / Browser
  • SelectBuf A fast and extensible buffer explorer.
  • selbuff Another buffer select script
  • PopupBuffer Vim global plugin for selecting buffer from PopUp menu
  • minibufexpl (popular) Elegant buffer explorer - takes very little screen space
  • FavMenu
  • mru
  • 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
  • TabBar
  • 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, clean but quick and POWERFUL buffer manager!
  • fuzzyfinder The buffer/file/MRU/favorite/etc. explorer with the fuzzy pattern
  • LustyJuggler Switch very quickly between your active buffers
  • QuickName The most convenient way navigating opened buffers, incremental search by name
  • bufmru switch to a most recently used buffer quickly

References

Comments

 TO DO 

  • Check the BufSel code. Does it do any better than the wildmenu example (from Matt on vim_use) that I just added under "Built-in features"?
    • It behaves in a significantly different way, not sure if it's better or not. It will provide a (typically) vertical list of matching buffers, each preceded by its buffer number. It then prompts the user to enter the buffer number of the buffer to switch to, although any unique identifier will work. It isn't interactive like wildmenu, so I guess it depends on which you prefer. My personal preference if for tselectbuffer.
      • The only question worth considering is whether it is desirable to keep the BufSel code in the tip. I haven't looked at it, so I can't say. If you happen to have a firm opinion, please just act on it. I suppose from your comment above that you're not so sure. However, if you are confident, you could delete everything under "Comments" (i.e. you think BufSel is worth keeping), or you could delete the BufSel section (and these comments) if you think it's of marginal value (on the simple is good principle to shorten the tip). BTW I'm signing temporary comments like this (in due course, all the comments will be removed). --JohnBeckett 03:07, 29 August 2008 (UTC)
  • I guess this tip is sufficiently long and complex without merging in 873 Cycle through buffers including hidden buffers. However, this should link to 873 somewhere, and 873 should link to this (in 873, I think a "See also" section; I'm not sure where would be best to put the link in this tip). --JohnBeckett 05:49, 29 August 2008 (UTC)
Advertisement