Guest User

Untitled

a guest
Dec 26th, 2022
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.00 KB | None | 0 0
  1. -- Change vim's current working directory to a parent git dir of the current
  2. -- buffer with keymaps.
  3.  
  4. local ok, Path = pcall(require, "plenary.path")
  5. if not ok then
  6.   return nil
  7. end
  8.  
  9. -- calls callback when a parent path is found. keeps searching until callback
  10. -- returns false
  11. local function find_parent_with_git(path, callback)
  12.   path = Path:new(path)
  13.   for _, parent in pairs(path:parents()) do
  14.     -- a git module or super module (containing submodules) always has a .git
  15.     -- file or directory (afaik)
  16.     local path_with_git = Path.new(parent, ".git")
  17.     if path_with_git:exists() then
  18.       if not callback(parent) then
  19.         return
  20.       end
  21.     end
  22.   end
  23. end
  24.  
  25. local function find_first_parent_with_git(path)
  26.   local first_parent
  27.   find_parent_with_git(path, function(parent)
  28.     first_parent = parent
  29.     return false
  30.   end)
  31.   return first_parent
  32. end
  33.  
  34. local function find_last_parent_with_git(path)
  35.   local last_parent
  36.   find_parent_with_git(path, function(parent)
  37.     last_parent = parent
  38.     return true
  39.   end)
  40.   return last_parent
  41. end
  42.  
  43. local function parent(path)
  44.   local parent_ = Path:new(path):parent().filename
  45.   return parent_
  46. end
  47.  
  48. local function cd_to(func, path)
  49.   local destination = func(path)
  50.   if destination and destination ~= vim.fn.getcwd() then
  51.     vim.api.nvim_set_current_dir(destination)
  52.     print('Changed cwd to: "' .. destination .. '"')
  53.   else
  54.     print("Didn't change cwd. cwd: \"" .. vim.fn.getcwd() .. '"')
  55.   end
  56. end
  57.  
  58. -- change to pwd to the current file's git module
  59. vim.keymap.set("n", "<leader>cm", function()
  60.   cd_to(find_first_parent_with_git, vim.api.nvim_buf_get_name(0))
  61. end)
  62.  
  63. -- change to pwd to the current file's git super module if it is in a git
  64. -- submodule
  65. vim.keymap.set("n", "<leader>cs", function()
  66.   cd_to(find_last_parent_with_git, vim.api.nvim_buf_get_name(0))
  67. end)
  68.  
  69. -- change to pwd to the current file's directory
  70. vim.keymap.set("n", "<leader>cd", function()
  71.   cd_to(parent, vim.api.nvim_buf_get_name(0))
  72. end)
  73.  
Advertisement
Add Comment
Please, Sign In to add comment