As title. When running :bn the current buffer will be switched to the next buffer. I want to get the buffer number of this buffer without changing the current buffer(or, at least, can switch back to the starting buffer)

2 Answers 2


I can't fint a build-in solution for this, here is a function using getbufinfo() that does not need to actually change buffers:

function! Next_buf()
    let l:bufs = getbufinfo({'buflisted': 1}

    let l:later = filter(l:bufs), 'v:val.bufnr > ' . bufnr())

    if len(l:later) > 0
        return l:later[0].bufnr
        return l:bufs[0].bufnr

I emulated the behavior of :bn of wrapping around at the end and filtering out hidden buffers.

  • But does the buffer with bufnr() closest to the current one really the next buffer?
    – Kindred
    May 3, 2022 at 16:29
  • 1
    @Kindred I’m not sure I understand your question. This function should behave the same as :bn, that is: return the number of the next visible buffer if any, or the first one otherwise.
    – TothP
    May 3, 2022 at 21:46

It turns out that the naive way works: (answer in Lua)

local buf_right = vim.fn.bufnr()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.