feat(root): cached pretty path function for statuslines

This commit is contained in:
Folke Lemaitre
2023-10-11 22:37:28 +02:00
parent 761171a872
commit 7bbd48caa0
2 changed files with 37 additions and 2 deletions

View File

@ -138,9 +138,10 @@ return {
},
},
{ "filetype", icon_only = true, separator = "", padding = { left = 1, right = 0 } },
{ "filename", path = 1, symbols = { modified = "", readonly = "", unnamed = "" } },
-- stylua: ignore
{
function()
return Util.root.pretty_path()
end,
},
},
lualine_x = {

View File

@ -144,4 +144,38 @@ function M.get()
return roots[1] and roots[1].paths[1] or vim.loop.cwd()
end
M.pretty_cache = {} ---@type table<string, string>
function M.pretty_path()
local path = vim.fn.expand("%:p") --[[@as string]]
if path == "" then
return ""
end
path = Util.norm(path)
if M.pretty_cache[path] then
return M.pretty_cache[path]
end
local cache_key = path
local cwd = M.realpath(vim.loop.cwd()) or ""
if path:find(cwd, 1, true) == 1 then
path = path:sub(#cwd + 2)
else
local roots = M.detect({ spec = { ".git" } })
local root = roots[1] and roots[1].paths[1] or nil
if root then
path = path:sub(#vim.fs.dirname(root) + 2)
end
end
local sep = package.config:sub(1, 1)
local parts = vim.split(path, "[\\/]")
if #parts > 3 then
parts = { parts[1], "", parts[#parts - 1], parts[#parts] }
end
local ret = table.concat(parts, sep)
M.pretty_cache[cache_key] = ret
return ret
end
return M