Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Change vim's current working directory to a parent git dir of the current
- -- buffer with keymaps.
- local ok, Path = pcall(require, "plenary.path")
- if not ok then
- return nil
- end
- -- calls callback when a parent path is found. keeps searching until callback
- -- returns false
- local function find_parent_with_git(path, callback)
- path = Path:new(path)
- for _, parent in pairs(path:parents()) do
- -- a git module or super module (containing submodules) always has a .git
- -- file or directory (afaik)
- local path_with_git = Path.new(parent, ".git")
- if path_with_git:exists() then
- if not callback(parent) then
- return
- end
- end
- end
- end
- local function find_first_parent_with_git(path)
- local first_parent
- find_parent_with_git(path, function(parent)
- first_parent = parent
- return false
- end)
- return first_parent
- end
- local function find_last_parent_with_git(path)
- local last_parent
- find_parent_with_git(path, function(parent)
- last_parent = parent
- return true
- end)
- return last_parent
- end
- local function parent(path)
- local parent_ = Path:new(path):parent().filename
- return parent_
- end
- local function cd_to(func, path)
- local destination = func(path)
- if destination and destination ~= vim.fn.getcwd() then
- vim.api.nvim_set_current_dir(destination)
- print('Changed cwd to: "' .. destination .. '"')
- else
- print("Didn't change cwd. cwd: \"" .. vim.fn.getcwd() .. '"')
- end
- end
- -- change to pwd to the current file's git module
- vim.keymap.set("n", "<leader>cm", function()
- cd_to(find_first_parent_with_git, vim.api.nvim_buf_get_name(0))
- end)
- -- change to pwd to the current file's git super module if it is in a git
- -- submodule
- vim.keymap.set("n", "<leader>cs", function()
- cd_to(find_last_parent_with_git, vim.api.nvim_buf_get_name(0))
- end)
- -- change to pwd to the current file's directory
- vim.keymap.set("n", "<leader>cd", function()
- cd_to(parent, vim.api.nvim_buf_get_name(0))
- end)
Advertisement
Add Comment
Please, Sign In to add comment