5

How can I reveal a specific file (usually the current buffer) in Netrw tree view, similar to :NERDTreeFind command does for NERDTree?

To be more precise...

I have a file opened in a buffer and I use :Expore to open netrw.

I want the file I had in my active buffer to be shown in netrw (expand all directories from working dir to the file) so I can see all its sibling files and folders.

2 Answers 2

4

Here goes a simple way to do it.
You can change :Explore command to Vexplore, :Hexplore, etc.

# show file in netrw
command! ExploreFind let @/=expand("%:t") | execute 'Explore' expand("%:h") | normal n

# or as a mapping
map <Leader>f :let @/=expand("%:t") <Bar> execute 'Explore' expand("%:h") <Bar> normal n<CR>

Here goes some explanation:

  • let @/=expand("%:t") sets the last search to the current filename
  • execute 'Explore' expand("%:h") open netrw passing the current file path as an argument, to make sure it list that directory
  • normal n search for the filename in the directory listing

Got the idea from https://vim.fandom.com/wiki/Search_for_current_word_in_new_window.

Note: This doesn't do exactly the same as NERDTreeFind because it won't show the whole directory tree but it is enough for my needs.

2
  • This does not work with (quite common) set autochdir since %:h is then expanded to just a dot . and misinterpreted by netrw. With autochdir on this works for me: execute 'Explore '.fnamemodify('.', ':p')
    – bloody
    May 8 at 9:13
  • 1
    Btw. you can use \| instead of <Bar>s
    – bloody
    May 8 at 9:21
1

This version works in neovim (written in lua + vimscript) and behaves like "show in project view" in Jetbrains Idea IDE. I mean it looks like it starts from the root of a project (pwd) and open directories until your file.

vim.g.netrw_liststyle = 3
vim.keymap.set('n', '<leader>e', function ()
    local relative_path = vim.fn.expand("%:h")
    local startPos, endPos = string.find(relative_path, "/")
    if startPos == 1 then
       relative_path = "."
    end
    vim.cmd [[:let @/=expand("%:t")]]
    vim.cmd("Lexplore " .. relative_path)
    if startPos > 1 then
        while startPos ~= nil do
            startPos, endPos = string.find(relative_path, "/", endPos + 1)
            vim.cmd("call netrw#Call('NetrwBrowseUpDir', 1)")
        end
        vim.cmd("call netrw#Call('NetrwBrowseUpDir', 1)")
    end
    vim.cmd(":normal n<CR>zz")
end)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .