18

in vim, with

:buffers

I get the number of all buffers the same with

:ls

, but
how I can get the total number of buffers ?

Giacomo1968
  • 58,727
juanpablo
  • 7,424

5 Answers5

22

Answers so far are too hacky. Here is vim's built-in way:

len(getbufinfo({'buflisted':1}))

As always, see vim's help (:h getbufinfo()) for the official explanation.

Gid
  • 431
12

Same idea than Heptite's solution, but as a one liner. Many other things may be done this way: get the name of the buffer (thanks to map), wipeout buffers that match a pattern, https://stackoverflow.com/questions/2974192/how-can-i-pare-down-vims-buffer-list-to-only-include-active-buffers/2974600#2974600n etc.

echo len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
Luc Hermitte
  • 1,903
5

To my knowledge there is no built-in method in Vim to do this, but you could create a function:

function! NrBufs()
    let i = bufnr('$')
    let j = 0
    while i >= 1
        if buflisted(i)
            let j+=1
        endif
        let i-=1
    endwhile
    return j
endfunction

Put the above in a text file with its name ending in .vim, :source it, then you can do something like:

:let buffer_count = NrBufs()
:echo buffer_count

June 21 note: If you have a recent version of Vim as of 2017, Gid's answer below is the optimal solution.

Heptite
  • 20,411
3

Are you looking perhaps for ?

:echo(bufnr('$'))
Rook
  • 24,289
3

If you want Heptite's solution as a command, add the following to your .vimrc file:

command BufNum echo len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
Andrzej
  • 31