kyazdani42 / nvim-tree.lua

A file explorer tree for neovim written in lua

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

question/feature: open in current dir with closed nodes

petobens opened this issue · comments

OS
Arch 5.15.11-arch2-1

Neovim version
NVIM v0.7.0-dev+764-g3e81c1f9b5

Nvim-tree version
master

Describe the bug/feature
If I use, as in the GIF, the command :NvimTreeFindFile then nvim-tree opens the tree with focus on the current file. I would like to open the directory containing that file (i.e have all nodes closed) as if I would first "cd" into the directory (in this case plugin-config) and then focus on the nvimtree_config.lua file.

Peek 2021-12-25 14-53-nvimtree

hi !
If i understand correctly, you wish to find the file, and changing the nvim-tree root to this file's containing folder ?
I believe this could be done with a little lua script and a few nvim-tree command, could you tell me if this is still relevant or did you manage to do it yourself ?

Hi! I ended up using the following two functions:

function NvimTreeConfig.find_file()
    local nvim_tree = require('nvim-tree')
    nvim_tree.find_file(true)
    local lib = require('nvim-tree.lib')
    local node = lib.get_node_at_cursor()
    local curr_file = node.name
    local parent_dir = vim.fn.fnamemodify(node.absolute_path, ':h:t')
    nvim_tree.on_keypress('close_node')
    nvim_tree.on_keypress('cd')
    if vim.fn.line('.') > 1 then
        local linenr = vim.fn.searchpos(curr_file)[1]
        vim.cmd('normal! gg' .. (linenr - 1) .. 'j')
    else
        local linenr = vim.fn.searchpos(parent_dir)[1]
        vim.cmd('normal! gg' .. (linenr - 1) .. 'j')
        nvim_tree.on_keypress('cd')
        linenr = vim.fn.searchpos(curr_file)[1]
        vim.cmd('normal! gg' .. (linenr - 1) .. 'j')
    end
end

function NvimTreeConfig.up_dir()
    local nvim_tree = require('nvim-tree')
    local lib = require('nvim-tree.lib')
    local node = lib.get_node_at_cursor()
    local parent_dir = vim.fn.fnamemodify(node.absolute_path, ':h:t')
    nvim_tree.on_keypress('close_node')
    nvim_tree.on_keypress('cd')
    local linenr = vim.fn.searchpos(parent_dir)[1]
    vim.cmd('normal! gg' .. (linenr - 1) .. 'j')
end

Dunno if this is the proper approach though

if you wish, now you can pass a function into the cb property of a mapping entry in nvim-tree setup, which takes a node as a parameter. It might simplify a bit the code.
You could've approached it in a simpler way by just going to the parent (which is available a as nvim-tree.lib function), running a cd and then rerunning find-file. But if it works as is it's good enough :)

ezoic increase your site revenue