2

I have opened multiple buffers and I cycle between them using :bnext and :bprevious. How can I prevent vim from cycling to the first buffer when using :bnext on the last buffer / cycling to the last buffer when using :bprevious on the first buffer?

Basically, I want the same behavior as when opening vim with multiple files in the argument list and cycling between those using :next and :Next/:previous. In that case, vim will show E165: Cannot go beyond last file when using :next on the last file and E164: Cannot go before first file when using :Next on the first file.

If that is not possible, I could make do with vim displaying a message when cycling to the first / last file, similar to the message displayed when wrapping around a search: search hit BOTTOM, continuing at TOP.

1
  • 2
    Put the relevant buffers in the arglist? – D. Ben Knoble Apr 10 at 13:22
2

Whilst there isn't a vim-native option to configure this, you can simulate it by writing your own functions to overload :bnext and :bprev.

function! Bnext()
    let bufnrs = range(1, bufnr("$"))
    call filter(bufnrs, {_, v -> buflisted(v)})
    if bufnr() == max(bufnrs)
        echo "You are at the last buffer"
    else
        bnext
    endif
endfunction

command! Bnext call Bnext()

function! Bprev()
    let bufnrs = range(1, bufnr("$"))
    call filter(bufnrs, {_, v -> buflisted(v)})
    if bufnr() == min(bufnrs)
        echo "You are at the first buffer"
    else
        bprevious
    endif
endfunction

command! Bprev call Bprev()

I have assumed that you want to filter out unlisted buffers. If you decide to go this route, some ideas for extending it are:

  • use -bang to enable/disable going to the next unlisted buffer
  • use -count to go to the nth next/previous buffer in the list
  • use :cnoreabbrev to use :Bnext when you type :bn (see here for an example)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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