7

In my vimscript, I need to get a count of all buffers that are considered listed/listable (i.e. all buffers that do not have the unlisted, 'u', attribute).

What's the recommended way of deriving this value?

Xavier T.
  • 40,509
  • 10
  • 68
  • 97
Jonathan
  • 123
  • 2
  • 9

3 Answers3

16

You could use bufnr() to get the number of the last buffer, then create a list from 1 to that number and filter it removing the unlisted buffers, by using the buflisted() function as the test expression.

" All 'possible' buffers that may exist
let b_all = range(1, bufnr('$'))

" Unlisted ones
let b_unl = filter(b_all, 'buflisted(v:val)')

" Number of unlisted ones
let b_num = len(b_unl)

" Or... All at once
let b_num = len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
sidyll
  • 57,726
  • 14
  • 108
  • 151
  • I'm under the impression that this answer don't quite address the OP's question. He asked for "listed", not "unlisted". Although I see how it is related, of course. But I believe the answer would be simpler, and I'm curious to how that would be. -- Edited: it seems it do answer by filtering the unlisted "out" – DrBeco Jul 12 '17 at 16:49
4

A simple solution is using getbufinfo.

In your vimscript:

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

or test it with command:

:echo len(getbufinfo({'buflisted':1}))
hankchiutw
  • 1,546
  • 1
  • 12
  • 15
3

I would do it by calling buflisted() on the range of numbers up to the largest buffer number given by bufnr("$"). Something like this:

function! CountListedBuffers()
    let num_bufs = 0
    let idx = 1
    while idx <= bufnr("$")
        if buflisted(idx)
            let num_bufs += 1
        endif
        let idx += 1
    endwhile
    return num_bufs
endfunction
Prince Goulash
  • 15,295
  • 2
  • 46
  • 47