Skip to content

Commit d4e3834

Browse files
committed
add autocd-to-gitroot autocmd
1 parent 875b4ff commit d4e3834

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

lua/config/autocmds.lua

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,25 @@ autocmd("BufWritePre", {
9898
command = "%sort",
9999
})
100100

101+
-- Auto change to git root when opening a file or switching buffer
102+
vim.api.nvim_create_autocmd({ "BufEnter", "BufWinEnter" }, {
103+
group = augroup("autocd-to-gitroot"),
104+
callback = function()
105+
local filepath = vim.api.nvim_buf_get_name(0)
106+
if filepath == "" then
107+
return
108+
end -- skip unnamed buffers
109+
local git_root = vim.fn.systemlist("git -C " .. vim.fn.fnameescape(vim.fn.fnamemodify(filepath, ":p:h")) .. " rev-parse --show-toplevel")[1]
110+
if vim.v.shell_error == 0 and git_root ~= nil and git_root ~= "" then
111+
local current_dir = vim.fn.getcwd()
112+
if current_dir ~= git_root then
113+
vim.cmd("lcd " .. git_root)
114+
-- print("Changed directory to " .. git_root)
115+
end
116+
end
117+
end,
118+
})
119+
101120
-- Close fugitive buffers when navigating
102121
-- Probably not needed any more but leaving it here for reference
103122
-- autocmd BufReadPost fugitive://* set bufhidden=delete

0 commit comments

Comments
 (0)