this is gonna be a lengthy question.

I'm developing a neovim bufferline plugin which shows a list of all the buffers in the tabline. I'm trying to implement a auto-hide feature, where the bufferline is only shown if there are two or more buffers open.

To do this, I'm currently listening to the BufAdd and BufUnload autocmds. This is what I'm using now

autocmd VimEnter,BufAdd * call myplugin#toggle(expand('<afile>'), 1)
autocmd BufUnload * call myplugin#toggle(expand('<afile>'), 2)

where the myplugin#toggle autoloaded function is

function! myplugin#toggle(filename, threshold)
  if !buflisted(a:filename) | return | endif
  let l:buffers = getbufinfo({'buflisted': 1})
  execute 'set showtabline=' . (len(l:buffers) > a:threshold ? '2' : '0')

the first line is used as a guard against unwanted events. For example, if I have two opened buffers and open the help page (:h), when I close it the toggle function gets called and the bufferline gets hidden, which I don't want.

However this is not a perfect solution. For example if I have a single buffer, opening the help page causes the bufferline to show, even after the help page is closed.

I've tried way too many different combinations of autocmd events (BufUnload vs BufDelete), parameters (<afile> vs <abuf> vs %) and conditions (buflisted, bufloaded, nvim_buf_is_valid, etc.), but none of them seem to work.

I'm drowning in autocmd hell. Can somebody help?

  • Does it work if you use a single event of BufEnter and the threshold of 1? After you close a buffer, you'll enter another one, then you can reevaluate whether to show or hide the bufferline again... – filbranden May 13 at 18:59
  • Yes but that'd be wasteful. I'd like to evaluate that function only when I need to. – noibe May 13 at 20:24
  • 1
    PS let &showtabline = len(buffers) > a:threshold ? 2 : 0, no execute necessary – D. Ben Knoble May 13 at 22:29

Your Answer

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

Browse other questions tagged or ask your own question.