luaneovim

Neovim shortcut to provide file choice from current file without plugins?


I am looking for help with a shortcut in Neovim in Lua. It should open the completion menu for the path of the current file such that I can use Ctrl+n / Ctrl+p to move or down.

In the current code here:

vim.api.nvim_set_keymap("n", "<leader>a", ":e <C-R>=expand('%:h')<CR>/", { noremap = true, silent = true })

I have to press the shortcut and <Tab> to get to the state I want. Maybe there are even better (quicker, more intuitive) methods for file navigation w/o plugins, starting from the directory of the current file? One method I am currently using is to use Netrw (which is technically a plugin, but builtin) with this shortcut

vim.api.nvim_set_keymap("n", "<leader>e", ":e <C-R>=expand('%:p:h')<CR>/<CR>", { noremap = true, silent = true })

which is very similar.


Solution

  • This has done it for me.

    function files_inside_directory()
        local cmd = ":e <C-R>=expand('%:h')<CR>/"
        local termcode = vim.api.nvim_replace_termcodes(cmd, true, false, true)
        vim.api.nvim_feedkeys(termcode, 'n', false)
        vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<C-z>", true, false, true), 'n', false)
    end
    
    vim.api.nvim_set_keymap('n', '<leader>e', ':lua files_inside_directory()<CR>', {noremap = true, silent = true, desc="Open popupmenu inside file directory."})
    

    Since <Tab> only inserts a ^I character, this is a slight workaround to trigger the popupmenu.