A tiny Lua utility module for Neovim to get the project root path, heavily inspired(stolen 😅) from the only and the one Folke.
demo-root-nvim.mp4
Using lazy.nvim:
return {
"flashios09/root.nvim",
lazy=true,
}localroot=require("root")
print(root.get()) -- `~/.config/nvim/`- With Snacks explorer:
vim.keymap.set("n", "<leader>e", function()
require("snacks").explorer({ cwd=require("root").get() })
end, { desc="Explorer Snacks (Root dir)" })- With Snacks files picker:
vim.keymap.set("n", "<leader><space>", function()
require("snacks").picker.files({ cwd=require("root").get() })
end, { desc="Find Files (Root Dir)" })- With NeoTree:
vim.keymap.set("n", "<leader>e", function()
require("neo-tree.command").execute({ toggle=true, require("root").get() })
end, { desc="Explorer NeoTree (Root Dir)" })- With Telescope:
vim.keymap.set("n", "<leader><space>", function()
require("telescope.builtin").find_files({ cwd=require("root").get() })
end, { desc="Find Files (Root Dir)" })- With FzfLua:
vim.keymap.set("n", "<leader><space>", function()
require("fzf-lua").files({ cwd=require("root").get() })
end, { desc="Find Files (Root Dir)" })- With barbecue.nvim(see screenshot):
return {
"flashios09/barbecue.nvim",
name="barbecue",
version="*",
dependencies= {
"SmiteshP/nvim-navic",
"flashios09/root.nvim",
"nvim-tree/nvim-web-devicons",
},
config=function()
require("barbecue").setup({
-- your custom config here-- ..-- adding the project name to the barbecue lead sectionlead_custom_section=function()
localproject_name=vim.fn.fnamemodify(require("root").get(), ":t")
localproject_section= {
{ " " ..project_name.."", "BarbecueProject" },
{ "", "BarbecueProjectSeparator" },
{ "", "BarbecueNormal" },
}
returnproject_sectionend,
})
end,
}Return the buffer root directory.
Based on:
- lsp workspace folders
- lsp root_dir
- root pattern of filename of the current buffer
- root pattern of cwd
root.get() -- `"/Users/flashios09/.config/nvim/"`root.get({ buffer=1 }) -- `"/Users/flashios09/.config/nvim/"`Get the git root path if exists.
root.git() -- `"/Users/flashios09/.config/nvim/"`Get the buffer path.
root.bufpath(1) -- `"/Users/flashios09/.config/nvim/"`Normalize the buffer path.
- Replace the
~with the users home dir. - Normalize the windows path(the directory separator): replace the
\with/.
root.norm("~/.config/nvim/") -- `"/Users/flashios09/.config/nvim/"`root.norm("C:\.config\nvim\") -- `"C:/.config/nvim/"Get all the available root spec(s).
root.detect()
-- output:
{
{
paths= { "/Users/flashios09/.config/nvim" },
spec="lsp"
}, {
paths= { "/Users/flashios09/.config/nvim" },
spec= { ".git", "lua" }
}, {
paths= { "/Users/flashios09/.config/nvim" },
spec="cwd"
}
}