Fixing netrw

Recently I wrote about a few file management solutions in Vim and I mentioned some problems with the netrw and vinegar-vim solutions. This was bugging me so I sat down and figured out what was going on and how to handle it. I should probably also mention that I use NeoVim. I can’t say 100% that this is also an issue with regular Vim, but I suspect it is.

The main issue was the fact that I had set hidden turned on in my Vim config. When you open a directory in netrw and hidden is set to true, things get into a weird state. netrw itself opens up in a read-only buffer, and that buffer doesn’t get closed when you navigate away from it or choose a file. It doesn’t even get closed if you try to delete the buffer with :bd. However, it does go away if you delete it by its number, :bd 1.

You should be able to see this behavior if you have set hidden on and do :edit ., choose a file and then :ls. You’ll see the netrw buffer in the list. Ideally you shouldn’t.

What I found out is that this behavior doesn’t occur if you open netrw by calling :Explore. But that just opens netrw in the directory of the currently displayed file. So that’s half the problem solved, but I also wanted to be able to open netrw in the current project directory, i.e. the directory where Vim was launched from.

Some digging around brought me to this:

nnoremap - :Explore<CR>
" nnoremap <Leader>f :Explore <C-r>=getcwd()<CR><CR>
nnoremap <Leader>f :Explore .<CR>

So we have the simple - mapping which just calls :Explore. Opens the dir of the current file. netrw behaves. Great.

The next one was trickier. You can pass a directory to :Explore, but how to get the current directory and pass it to the command? <C-r>=getcwd()<CR> gets the current working directory and inserts it in the command line. Just before that, I have :Explore with a space. Then I follow it up with a final carriage return.


I was an idiot. Rather than the escape code and =getcwd() stuff, you can just :Explore .<CR>. Has the same effect. Not sure why I didn’t try that to begin with.

End Update

This opens up netrw without it getting into that weird state. Select it or close it and it goes away. For real. This makes me happy.

One more little bonus tip. If you don’t like that big banner on the top of netrw’s ui, just add the following to your config:

let g:netrw_banner = 0

You can always toggle it back on with a capital I if you need it.

Sadly, I don’t think this solution will really help if you are using vinegar-vim, because that plugin continues to call edit internally.