Vim Tips Wiki
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 :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 !, such as :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

In gvim, you can use the Buffers menu to conveniently access buffers. Or, 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>

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.

References

Comments

 TO DO 

  • Ben Armston: When ready, please remove this comment. You asked about the '/' in this mapping:
    :nmap zl :ls!<CR>:buf /

I can't see it documented anywhere, but experiment suggests that the '/' sometimes works to find a buffer by name. I think its cleverness is that if you have a buffer named "123" (i.e. a number), the command :buf /123 will switch to that buffer, while :buf 123 will give an error because you don't have buffer number 123.

However, the '/' gave me trouble in a quick test (it often wouldn't match part of a name), and I don't think it is worth bothering with. When you remove the '/', the mapping is too similar to your <F5> mapping, so I have deleted the suggestion. --JohnBeckett 02:56, 18 August 2008 (UTC)


 TO DO 

  • I've put my BufExplorer Alt-F12 info above. I think it fits better here, and I'll probably remove it from VimTip135 (and check if 135 has a link to this tip).
  • The comments at the bottom of tip 135 might be good here.

 TO DO 

  • Include (taken from comment in tip 412)
    • :wn " write current file goto next
    • :wp " write current file goto previous
    • :last " goto last
    • :first " goto first (:rew)
  • Include (from another comment in tip 412)
    • " ",1", ",2", .. ",9", ",0" to go straight to that numbered buffer (0 = 10)
    • " ",g" to toggle between two buffers (my most used probably)
    • map ,s :bN<CR> " back on the buffer list
    • map ,f :bn<CR> " forth on the buffer list
    • map ,d :buffers<CR> " a list of what's in each buffer
    • map ,g :e#<CR> " toggle between two buffers
    • map ,1 :1b<CR> " go to buffer 1
    • map ,2 :2b<CR>
    • map ,3 :3b<CR>
    • map ,4 :4b<CR>
    • map ,5 :5b<CR>
    • map ,6 :6b<CR>
    • map ,7 :7b<CR>
    • map ,8 :8b<CR>
    • map ,9 :9b<CR>
    • map ,0 :10b<CR>
Advertisement