Vim Tips Wiki
(→‎Switching to another buffer: Merge 821. :edit #<buffer number>)
(→‎Leaving modified buffers: also mention 'confirm')
(40 intermediate revisions by 18 users not shown)
Line 1: Line 1:
{{Duplicate|821|1537}}
 
{{review}}
 
 
{{TipImported
 
{{TipImported
 
|id=686
 
|id=686
 
|previous=685
 
|previous=685
 
|next=687
 
|next=687
|created=March 25, 2004
+
|created=2004
 
|complexity=basic
 
|complexity=basic
 
|author=Matt Perry
 
|author=Matt Perry
|version=5.7
+
|version=6.0
 
|rating=24/15
 
|rating=24/15
 
|category1=
 
|category1=
 
|category2=
 
|category2=
 
}}
 
}}
One of the keys to effective Vim usage is effective buffer management. Vim
+
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.
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==
 
==Terminology==
 
Some of the terms used in this tip are briefly explained below. For more details see the [[VimTip135|buffer FAQ]] and {{help|windows-intro}}.
 
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.
 
*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 buffer can be created to hold text that isn't related to a file, such as a directory listing.
Line 34: Line 26:
   
 
==Listing buffers==
 
==Listing buffers==
  +
The <code>:buffers</code> command lists the current buffers. There are two alternate names for this command <code>:ls</code> and <code>:files</code>. By default, only listed buffers will be displayed. Unlisted buffers can be included by appending <code>!</code>, for example <code>:ls!</code>.
 
The <tt>:buffers</tt> command will list your current buffers. There are two
 
alternate names for this command <tt>:ls</tt> and <tt>:files</tt>. By
 
default, only listed buffers will be displayed. Unlisted buffers can be
 
included by prepending the command with a <tt>!</tt>, such as
 
<tt>:buffers!</tt>.
 
   
 
==Switching to another buffer==
 
==Switching to another buffer==
  +
The command to switch to another buffer is <code>:buffer</code>, which is often abbreviated as <code>:b</code>, <code>:bu</code> or <code>:buf</code>. <code>:buffer</code> can be given either the name or the number of the buffer to edit.
 
The command to switch to another buffer is <tt>:buffer</tt>, which is often
 
abbreviated as <tt>:b</tt>, <tt>:bu</tt> or <tt>:buf</tt>.
 
<tt>:buffer</tt> can be given either the name or the number of the buffer to
 
edit.
 
   
 
===Switching by name===
 
===Switching by name===
  +
When using the buffer name as the argument to <code>:buffer</code>, 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 <code>:buffer que</code> matches both of them, but will switch to queue_manager.java as it matches at the beginning.
When using the buffer name as the argument to <tt>:buffer</tt>, 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 open then <tt>:buffer
 
que</tt> 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, <code>:buffer</code> ''any snippet of text''<code><Tab></code> 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 <code><tab></code>. The switch will take place once <code><CR></code> 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 <code>t_ma<tab></code> or <code>req<tab></code> or <code>r.java<tab></code>. Instead of <tab>, you can press Ctrl-D to list all matching names.
Tab completion can be used to complete the buffer name, <tt>:buffer</tt>
 
''any snippet of text''<tt><tab></tt> 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
 
<tt><tab></tt>. The switch will take place once <tt><CR></tt> is entered
 
with a unique buffer name. Again, any fragment of the buffer name can be used
 
to complete to the matching buffer, for example, request_manager.java can be
 
completed using <tt>tma<tab></tt> or <tt>req<tab></tt> or
 
<tt>r.java<tab></tt>.
 
   
If you would prefer to be able to select the buffer from the list of partial
+
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.
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.
 
   
 
<pre>
 
<pre>
Line 111: Line 74:
   
 
===Switching by number===
 
===Switching by number===
  +
If you know the number of the buffer you want to switch to, you can pass that as the argument to <code>:buffer</code>, for example <code>:buffer 5</code> will switch to buffer number 5. An alternative which can be used from normal mode is ''buffer number''<code><C-^></code>, for example <code>5<C-^></code> 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:
If you know the number of the buffer you want to switch to, you can pass that
 
as the argument to <tt>:buffer</tt>, for example <tt>:buffer 5</tt> will
 
switch to buffer number 5. An alternative which can be used from normal mode
 
is ''buffer number''<tt><C-^></tt>, for example <tt>5<C-^></tt> 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:
 
   
 
<pre>
 
<pre>
:nnoremap <F5> :buffers<CR>:buffer<space>
+
:nnoremap <F5> :buffers<CR>:buffer<Space>
</pre>
+
</pre>
   
When <tt>F5</tt> is pressed, a numbered list of file names is printed, and
+
When <code>F5</code> 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 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 <tt><space></tt> at the end of the map isn't required, but does help to
+
The <code><Space></code> at the end of the map isn't required, but does help to separate the input from the "prompt". As the <code>:buffer</code> command is being used to perform the switch, the buffer name could be used instead, if preferred.
separate the input from the "prompt". As the <tt>:buffer</tt> command is
 
being used to perform the switch, the buffer name could be used instead, if
 
preferred.
 
   
  +
The <code>:edit</code> command can also be used to switch to a given buffer number if the argument begins with <code>#</code>. For example, <code>:edit #5</code> 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 <code>#</code> and enter the path to the file.
The <tt>:edit</tt> command can also be used to switch to a given buffer number
 
if the argument to it begins with a <tt>#</tt>, for example, <tt>:edit #5</tt>
 
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 <tt>#</tt> and enter the path
 
to the file.
 
   
 
===Switching to the previously edited buffer===
 
===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 <code><C-^></code> (or <code><C-6></code>) and <code>:b#</code>.
   
 
Both of these technically edit the alternate file, although this is usually the previously edited buffer.
Often times 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 <tt><C-^></tt> and <tt>:b#</tt>.
 
 
Both of these technically edit the alternate file, although this is usually the
 
previously edited buffer.
 
   
 
==Leaving modified buffers==
 
==Leaving modified buffers==
  +
If Vim is running with its default settings, or in vi compatible mode, the <code>:buffer</code> command will not abandon the buffer until any changes have been written. There are a few ways this can be changed:
  +
*Append <code>!</code> 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 <code>:buffer! 2</code> (or <code>:b! 2</code>) would hide buffer 1 (keeping its changes), and display buffer 2.
 
*Set the ''hidden'' option (<code>:set hidden</code>) 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 (<code>:set confirm</code>) 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 (<code>:set autowrite</code> or <code>:set autowriteall</code>) to automatically save any changes made to the buffer before it is hidden.
   
  +
==Conveniently accessing buffers==
If Vim is running with its default settings, or in Vi compatible mode, the
 
  +
===Built-in features===
<tt>:buffer</tt> command won't abandon the buffer until any changes have been
 
  +
In gvim, you can use the Buffers menu to conveniently access buffers (tear off the menu to make an always-visible list).
written. There are a few ways this can be changed.
 
   
  +
Or, put the following in your [[vimrc]]:
*A <tt>!</tt> can be prepended (<tt>:buffer!</tt>) which will discard any changes made to the buffer.
 
  +
<pre>
*Setting the ''hidden'' option (<tt>:set hidden</tt>) will keep the changes to the buffer without writing them to the file. This affects all commands and all buffers.
 
  +
set wildchar=<Tab> wildmenu wildmode=full
*Setting either the ''autowrite'' or the ''autowriteall'' options (<tt>:set autowrite</tt> or <tt>:set autowriteall</tt>) will automatically save the changes made to the buffer.
 
  +
</pre>
   
  +
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.
==Scripts==
 
  +
<pre>
  +
set wildcharm=<C-Z>
  +
nnoremap <F10> :b <C-Z>
  +
</pre>
   
  +
Try this example to see how powerful the wildmenu is.
If the above tips don't provide what you require, there are, of course, several
 
  +
<pre>
scripts covering buffer switching. A few of them are linked to below. Or you
 
  +
:args vehicle.c vehicle.h car.c car.h jet.c jet.h jetcar.c jetcar.h
could search [http://www.vim.org/scripts/index.php Vim Scripts for others].
 
  +
: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
  +
</pre>
   
  +
===Plugins===
*{{script|id=42|text=BufExplorer}}
 
  +
You may want to install the {{script|id=42|text=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.
*{{script|id=159|text=minibufexpl}}
 
  +
<pre>
  +
" 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>
  +
</pre>
  +
 
===Mappings for buffer number===
  +
If you know the buffer numbers, the following mappings are useful. For example, typing <code>\1</code> (assuming the default backslash leader) will switch to buffer number 1.
  +
<pre>
  +
" 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
  +
</pre>
  +
 
==Scripts==
  +
Some scripts for buffer switching are listed below, in order by the script id. You can search [http://www.vim.org/scripts/index.php Vim Scripts] for "buffer" to find others.
  +
*{{script|id=42|text=bufexplorer}} A popular buffer explorer.
  +
*{{script|id=107|text=SelectBuf}} A fast and extensible buffer explorer.
  +
*{{script|id=125|text=selbuff}} Another buffer select script
  +
*{{script|id=132|text=PopupBuffer}} To select a buffer from a PopUp menu.
  +
*{{script|id=159|text=minibufexpl}} A popular and compact buffer explorer. Clickable tabs w/ `set mouse=a`
 
*{{script|id=161|text=FavMenu}}
 
*{{script|id=161|text=FavMenu}}
 
*{{script|id=521|text=mru}}
 
*{{script|id=521|text=mru}}
  +
*{{script|id=685|text=incbufswitch}} Switch buffers using an incremental search.
  +
*{{script|id=921|text=bufmenu2}} More balanced buffers menu hierarchy.
 
*{{script|id=1011|text=buflist}} Buffer browser.
  +
*{{script|id=1283|text=TinyBufferExplorer}} A 1-file buffer list plugin with grouping.
  +
*{{script|id=1325|text=bufferlist}} Simple, fast, and slick non-disturbing buffer list.
 
*{{script|id=1338|text=TabBar}}
 
*{{script|id=1338|text=TabBar}}
*{{script|id=1866|text=tselectbuffer}}
+
*{{script|id=1422|text=bufmap}} Automatically maps buffers to function keys.
  +
*{{script|id=1664|text=buftabs}} Minimalistic buffer tabs saving screen space.
  +
*{{script|id=1836|text=bufpos}} Switch buffer with Alt-<number>.
  +
*{{script|id=1866|text=tselectbuffer}} A quick buffer selector/switcher.
  +
*{{script|id=1890|text=LustyExplorer}} Dynamic filesystem and buffer explorer.
  +
*{{script|id=1910|text=QuickBuf}} Very small but quick and powerful buffer manager.
  +
*{{script|id=1984|text=fuzzyfinder}} Explore buffer/file/MRU/favorite with a fuzzy pattern.
  +
*{{script|id=2050|text=LustyJuggler}} Switch very quickly between active buffers.
  +
*{{script|id=2317|text=QuickName}} Conveniently navigate buffers; incremental search by name.
  +
*{{script|id=2346|text=bufmru}} Quickly switch to most recently used buffer.
  +
*{{script|id=2606|text=vimuiex}} Commands: VxBufListSelect/VxOpenRecentFile/VxFileBrowser, with filtering and MRU
  +
*{{script|id=3025|text=Command-T}} Fast buffer and file navigation
  +
*{{script|id=3217|text=QuickNameBuf}} Quickly navigate between buffers using an incremental search by name (a combination of {{script|id=2317|text=QuickName}} and {{script|id=1910|text=QuickBuf}})
  +
*{{script|id=3619|text=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.
  +
*{{script|id=3896|text=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.
  +
  +
==See also==
  +
*[[VimTip873|Cycle through buffers including hidden buffers]] to cycle through existing buffers, in order by buffer number
   
 
==References==
 
==References==
  +
*[[VimTip135|Vim buffer FAQ]]
 
*{{help|buffers}}
 
*{{help|buffers}}
 
*{{help|buffer}}
 
*{{help|buffer}}
Line 182: Line 204:
 
*{{help|CTRL-^}}
 
*{{help|CTRL-^}}
 
*{{help|alternate-file}}
 
*{{help|alternate-file}}
*[[Vim_buffer_FAQ]]
 
   
 
==Comments==
 
==Comments==
  +
I suggest changing all mappings starting with <code>,</code> to start with <code><Leader></code> instead. I know that this is more confusing, but I strongly dislike seeing a perfectly good command &mdash; that is <code>,</code> &mdash; go to waste before the user has had a chance to learn it. I think this should be done for all articles. ([[User:Spiiph|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. [[User:JohnBeckett|JohnBeckett]] 09:52, September 5, 2009 (UTC)
   
  +
The following simple user-defined command <code>:Buffer</code> allows switching a buffer in the current window
  +
choosing it from the buffer list:
 
<pre>
 
<pre>
  +
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
" Use zl to list buffers, and go to matching buffer.
 
" Type part of bufname after / prompt.
 
:nmap zl :ls!&lt;CR&gt;:buf /
 
 
</pre>
 
</pre>
  +
<p>It can be abbreviated as <code>:B</code></p>It shows the buffer list printed out by the <code>:ls</code> command and asks a user for the input which is transferred to <code>:buffer</code> command.<p>The command with an exclamation mark <code>:B!</code> executes <code>:ls!</code> which includes unlisted buffers in the list. Entering a zero as answer creates a new buffer with <code>:enew</code> command.</p>Also a desired buffer number or part of buffer's name can be specified directly as argument to <code>:B</code> . ([[User:Gmikeus|Gmikeus]] 19:43, December 19, 2010 (UTC))
 
----
 
{{todo}}
 
*Better section titles.
 
*Expand current sections.
 
*Merge in other tips.
 
*What does the / in the above comment 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&lt;CR&gt; " back on the buffer list
 
**map ,f :bn&lt;CR&gt; " forth on the buffer list
 
**map ,d :buffers&lt;CR&gt; " a list of what's in each buffer
 
**map ,g :e#&lt;CR&gt; " toggle between two buffers
 
**map ,1 :1b&lt;CR&gt; " go to buffer 1
 
**map ,2 :2b&lt;CR&gt;
 
**map ,3 :3b&lt;CR&gt;
 
**map ,4 :4b&lt;CR&gt;
 
**map ,5 :5b&lt;CR&gt;
 
**map ,6 :6b&lt;CR&gt;
 
**map ,7 :7b&lt;CR&gt;
 
**map ,8 :8b&lt;CR&gt;
 
**map ,9 :9b&lt;CR&gt;
 
**map ,0 :10b&lt;CR&gt;
 
*Include section about 'hidden' and :buffer!
 

Revision as of 15:33, 29 July 2013

Tip 686 Printable Monobook Previous Next

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.

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 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 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-^> (or <C-6>) 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 will not abandon the buffer until any changes have been written. There are a few ways this can be changed:

  • Append ! 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 :buffer! 2 (or :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 autowrite or :set autowriteall) to automatically save any changes made to the buffer before it is hidden.

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

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

Scripts

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

See also

References

Comments

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 :B

It shows the buffer list printed out by the :ls command and asks a user for the input which is transferred to :buffer command.

The command with an exclamation mark :B! executes :ls! which includes unlisted buffers in the list. Entering a zero as answer creates a new buffer with :enew command.

Also a desired buffer number or part of buffer's name can be specified directly as argument to :B . (Gmikeus 19:43, December 19, 2010 (UTC))