1

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

1

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
    else
        return l:bufs[0].bufnr
    endif
endfunction

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

2
  • But does the buffer with bufnr() closest to the current one really the next buffer?
    – Kindred
    Commented 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
    Commented May 3, 2022 at 21:46
0

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

vim.cmd('bn')
local buf_right = vim.fn.bufnr()
vim.cmd('bp')

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.