1

I want to detect from a BufEnter autocommand whether the buffer is a netrw directory listing.

It seems that when the autocommand is fired, the filetype is empty and there are no netrw-related buffer variables. Furthermore the bufname() is empty. However when I manually look at the filetype it is "netrw", the b:netrw_curdir variable is set, and the buffer has a name (the directory it shows).

How can I determine during the autocommand when the buffer is a netrw directory listing?

This is on Vim 9.0.1276.

2 Answers 2

2

Obviously, netrw intercepts BufEnter itself to set the things up. So upon first BufEnter it depends on which autocmd was registered first: yours or netrw's one. As you want to go after netrw you can move your code under ~/.vim/after/plugin directory, for example.

However, I'd rather switched to BufWinEnter event, as it gets triggered less often than BufEnter (only after the buffer is shown in a window for the first time, and not after every buffer switching) and after the first BufEnter event anyway. In many cases it might be just what one needs.

Also, I would consider dropping netrw at all, as it is... well, what to say, I really dislike it.

3
  • Aha, it makes sense that netrw would intercept BufEnter. I tried to work through netrw's code but I found it very unclear. I haven't used it myself for many years. I'm trying to fix an issue with vim-rooter. Commented Sep 13, 2023 at 13:41
  • BufWinEnter could work for my use case, I think. I'll try it. Commented Sep 13, 2023 at 13:42
  • BufWinEnter seems to fire before BufEnter in this case. Commented Sep 13, 2023 at 14:38
1

Thanks to Matt's answer I realised I couldn't detect a netrw directory listing in a BufEnter autocommand (unless the code is running from an after directory).

So I switched to using a Filetype netrw autocommand.

3
  • At which point you might as well use ~/.vim/after/ftplugin/netrw.vim or equivalent on your system.
    – D. Ben Knoble
    Commented Sep 14, 2023 at 18:09
  • This is all for a plugin and for some reason I thought that plugins couldn't have after/ directories. But it turns out they can :) Commented Sep 15, 2023 at 11:21
  • For a plugin, you probably don’t need after. I recommend it for personal configuration because 99% of the time it’s the right thing and it’s less confusing.
    – D. Ben Knoble
    Commented Sep 15, 2023 at 11:41

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.