Vim Tips Wiki
Advertisement
Tip 873 Printable Monobook Previous Next

created February 10, 2005 · complexity basic · author Anon · version 6.0


This mapping on <Control-n> will let you cycle through all your buffers (including hidden directory listings):

:map <C-n> :exe ":buf ".((bufnr("%") % bufnr("$"))+1)<CR>

I had a problem for a long time when cycling through all the buffers since most commands (bn/bp) will skip hidden buffers.

# Example of problem.
gvim ~ /etc/motd
    gvim goes to dir ~
  :bn
    gvim goes to /etc/motd
  :bp
    but will not go back to ~, because it is hidden.
  :ls!
    ~ is there in list of the buffers 1,2
  :buf 1
    have to give it the buf number to find it.

Problem gets worse with several levels dirs navigation/browsing can't go back to old dirs.

Also this mapping works for ordinary files as expected. eg. gvim *.*, then use C-n to cycle.

Comments

This does not always work, because there might be holes in the buffer number, e.g. right now my buffer list contains buffer numbers 1, 2, 6, 9, 10 and 14.

If I use your command from my buffer #6, I get the error message "E86: Buffer 7 does not exist". A solution would be to write a function searching for the next buffer with bufexists().


So, this is my function.

function! SwitchToNextBuffer()
  let current=bufnr("%")+1
  let last=bufnr("$")
  let number=current+1
  while ! bufexists( number )
    let number=number+1
    if number > last
      let number = 1
    endif
  endwhile
  exe ":buf ".number
endfunction

The following allows cycling in both directions:

function! SwitchToNextBuffer(incr)
  let s:last = bufnr("$")
  let s:new = bufnr("%") + a:incr
  while s:new < 1 || !bufexists(s:new)
    let s:new = s:new + a:incr
    if s:new < 1
      let s:new = s:last
    elseif s:new > s:last
      let s:new = 1
    endif
  endwhile
  exe ":buf ".s:new
endfunction
nnoremap <silent> <C-N> :call SwitchToNextBuffer(1)<CR>
nnoremap <silent> <C-P> :call SwitchToNextBuffer(-1)<CR>

Advertisement