Vim Tips Wiki
No edit summary
Line 78: Line 78:
   
 
== Comments ==
 
== Comments ==
  +
{{todo}}
  +
* If in a help buffer, :bnext switches to the next help buffer. If in a non-help buffer, :bnext switches to the next non-help buffer. Make above script work this way too. For help buffers, &buftype == "help".

Revision as of 21:40, 10 July 2008

Tip 873 Printable Monobook Previous Next

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


This tip provides a means to cycle through all of your buffers (including :help unlisted-buffer buffers such as directory listings):

Most buffer navigation commands, such as :bnext and :bprevious, skip unlisted buffers. Which can prove frustrating when buffers have been opened to view directory listings. Consider the below example.

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

The problem gets worse with several levels of directory navigation.

The simplest solution for this are the following two mappings:

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

This maps <C-n> to switch to the buffer which has a buffer number one higher than the buffer number of the active buffer. Whilst <C-p> cycles in the opposite direction.

However, this does not always work, because there might be holes in the buffer numbers. E.g. right now my buffer list contains buffer numbers 1, 2, 6, 9, 10 and 14. Using the above map for <C-n> from buffer #6, would produce the error message "E86: Buffer 7 does not exist".

A solution is to write a function searching for the next buffer with bufexists().

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>

References

Comments

 TO DO 

  • If in a help buffer, :bnext switches to the next help buffer. If in a non-help buffer, :bnext switches to the next non-help buffer. Make above script work this way too. For help buffers, &buftype == "help".