-- The file tree: the working directory as lines, in a window on the left. Directories open and -- close, the file you are in is followed and marked, and each row carries one mark of its git -- state. New, rename and delete are asked for in words; nothing is removed without a yes. local M = {} local ns = vim.api.nvim_create_namespace("llembas-tree") local T = { buf = nil, root = nil, open = {}, rows = {}, hidden = false, filter = "", git = {}, git_dirs = {}, git_root = nil, branch = nil, current = nil, git_job = 0, } M.SCAN_MAX = 4000 -- how many entries a filter looks through --- Asked before anything is deleted. A function of its own so that the tests can answer. function M._confirm(question) return vim.fn.confirm(question, "&Yes\n&No", 2) == 1 end --- The program that moves a file to the trash, as a command without the file, or nil. function M._trash() if vim.fn.executable("gio") == 1 then return { "gio", "trash", "--" } end if vim.fn.executable("trash-put") == 1 then return { "trash-put", "--" } end if vim.fn.executable("trash") == 1 then return { "trash" } end return nil end local function valid() return T.buf and vim.api.nvim_buf_is_valid(T.buf) end function M.win() if not valid() then return nil end for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do if vim.api.nvim_win_get_buf(w) == T.buf then return w end end end local function scan(dir) local out = {} local fd = vim.uv.fs_scandir(dir) while fd do local name, kind = vim.uv.fs_scandir_next(fd) if not name then break end if kind == "link" or not kind then local st = vim.uv.fs_stat(dir .. "/" .. name) kind = st and st.type or "file" end if name ~= ".git" and (T.hidden or name:sub(1, 1) ~= ".") then out[#out + 1] = { name = name, dir = kind == "directory", path = dir .. "/" .. name } end end table.sort(out, function(a, b) if a.dir ~= b.dir then return a.dir end local x, y = a.name:lower(), b.name:lower() if x ~= y then return x < y end return a.name < b.name end) return out end local function relative(path) if path == T.root then return "" end return path:sub(#T.root + 2) end local function build() local rows = {} if T.filter ~= "" then -- A filter is a flat list of the files whose path has the text, wherever they are. local needle, seen = T.filter:lower(), 0 local function walk(dir) for _, e in ipairs(scan(dir)) do seen = seen + 1 if seen > M.SCAN_MAX then return end if e.dir then if e.name ~= "node_modules" then walk(e.path) end elseif relative(e.path):lower():find(needle, 1, true) then rows[#rows + 1] = { path = e.path, name = relative(e.path), dir = false, depth = 0 } end end end walk(T.root) return rows end local function walk(dir, depth) for _, e in ipairs(scan(dir)) do rows[#rows + 1] = { path = e.path, name = e.name, dir = e.dir, depth = depth } if e.dir and T.open[e.path] then walk(e.path, depth + 1) end end end walk(T.root, 0) return rows end local MARK_HL = { M = "LLeMbasTreeChanged", A = "LLeMbasTreeAdded", ["?"] = "LLeMbasTreeNew", D = "LLeMbasTreeDeleted", ["!"] = "LLeMbasTreeConflict", ["•"] = "LLeMbasTreeChanged", } local function mark_of(row) if row.dir then return T.git_dirs[row.path] and "•" or " " end return T.git[row.path] or " " end --- A row as its line: the git mark, the indent, the fold mark of a directory, the name. local function line_of(row) local fold = row.dir and (T.open[row.path] and "▾ " or "▸ ") or " " -- A name is shown as text on one line, whatever bytes it has. local name = row.name:gsub("[%c]", "?") return mark_of(row) .. " " .. (" "):rep(row.depth) .. fold .. name .. (row.dir and "/" or "") end function M.render() if not valid() then return end T.rows = build() local lines = {} for i, r in ipairs(T.rows) do lines[i] = line_of(r) end if #lines == 0 then lines = { T.filter ~= "" and " (no file has that in its name)" or " (empty)" } end local win = M.win() local at = win and vim.api.nvim_win_get_cursor(win) or nil vim.bo[T.buf].modifiable = true vim.api.nvim_buf_set_lines(T.buf, 0, -1, false, lines) vim.bo[T.buf].modifiable = false vim.api.nvim_buf_clear_namespace(T.buf, ns, 0, -1) for i, r in ipairs(T.rows) do local mark = mark_of(r) if mark ~= " " then vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { end_col = #mark, hl_group = MARK_HL[mark] or "LLeMbasTreeChanged" }) end if r.dir then vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, #mark + 1, { end_col = #lines[i], hl_group = "LLeMbasTreeDirectory" }) end if r.path == T.current then vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { line_hl_group = "LLeMbasTreeCurrent" }) end end if win and at then pcall(vim.api.nvim_win_set_cursor, win, { math.min(at[1], #lines), 0 }) end if win then vim.wo[win].winbar = T.filter ~= "" and (" / " .. T.filter:gsub("%%", "%%%%")) or "" end end --- The row under the cursor of the tree's window, or nil. local function row_here() local win = M.win() if not win then return nil end return T.rows[vim.api.nvim_win_get_cursor(win)[1]] end local function go_to(path) local win = M.win() if not win then return false end for i, r in ipairs(T.rows) do if r.path == path then pcall(vim.api.nvim_win_set_cursor, win, { i, 0 }) return true end end return false end --- The window a file is opened in: the one the layout says is the code's, else any window with --- an ordinary buffer, else a new one beside the tree. local function code_win() local ok, w = pcall(function() return require("llembas.layout").code_win() end) if ok and w and vim.api.nvim_win_is_valid(w) then return w end for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do local b = vim.api.nvim_win_get_buf(win) if vim.api.nvim_win_get_config(win).relative == "" and vim.bo[b].buftype == "" then return win end end local tw = M.win() if tw then vim.api.nvim_set_current_win(tw) end vim.cmd("rightbelow vnew") local win = vim.api.nvim_get_current_win() if tw then pcall(vim.api.nvim_win_set_width, tw, M.width or 26) end return win end function M.open_file(path) local win = code_win() vim.api.nvim_set_current_win(win) local ok, err = pcall(vim.cmd.edit, vim.fn.fnameescape(path)) if not ok then vim.notify("LLeMbas: " .. tostring(err):gsub("^.-:%s*", ""), vim.log.levels.WARN) end end --- Enter on a row: a file is opened, a directory opens or closes. function M.activate(only_open) local r = row_here() if not r then return end if r.dir then if T.open[r.path] and only_open then return end T.open[r.path] = not T.open[r.path] or nil M.render() go_to(r.path) else M.open_file(r.path) end end --- ← on a row: an open directory closes; anything else goes to the directory it is in. function M.collapse() local r = row_here() if not r then return end if r.dir and T.open[r.path] then T.open[r.path] = nil M.render() return go_to(r.path) end local parent = vim.fs.dirname(r.path) if parent and parent ~= T.root then go_to(parent) end end --- The directory a new file goes into: the directory under the cursor, or the one the file under --- the cursor is in. local function dir_here() local r = row_here() if not r then return T.root end return r.dir and r.path or vim.fs.dirname(r.path) end local function inside(path) return path == T.root or vim.startswith(path, T.root .. "/") end --- A name typed by the person as a path under `base`; nil when it would leave the tree's root. local function resolve(base, name) name = vim.trim(name or "") if name == "" then return nil end local path = vim.fs.normalize(name:sub(1, 1) == "/" and name or (base .. "/" .. name)) if not inside(path) or path == T.root then return nil, "that is outside " .. T.root end return path end local function reveal(path) local dir = vim.fs.dirname(path) while dir and inside(dir) and dir ~= T.root do T.open[dir] = true dir = vim.fs.dirname(dir) end end --- Make a file, or a directory when the name ends in `/`. Asks for the name when none is given. function M.create(name) local base = dir_here() local function make(text) if not text or not text:match("%S") then return end local is_dir = vim.trim(text):sub(-1) == "/" local path, why = resolve(base, text) if not path then return vim.notify("LLeMbas: not made" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end if is_dir then vim.fn.mkdir(path, "p") T.open[path] = true else vim.fn.mkdir(vim.fs.dirname(path), "p") local f, err = io.open(path, "w") if not f then return vim.notify("LLeMbas: not made: " .. tostring(err), vim.log.levels.WARN) end f:close() end reveal(path) M.render() go_to(path) M.git_refresh() if not is_dir then M.open_file(path) end end if name then return make(name) end local shown = relative(base) vim.ui.input({ prompt = ("New file in %s/ (a name ending in / makes a directory): "):format(shown == "" and "." or shown) }, make) end --- Rename or move the row under the cursor. An open buffer of the file follows it. function M.rename(to) local r = row_here() if not r then return end local function move(text) if not text or not text:match("%S") then return end local path, why = resolve(T.root, text) if not path then return vim.notify("LLeMbas: not moved" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end if path == r.path then return end if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end vim.fn.mkdir(vim.fs.dirname(path), "p") local ok, err = vim.uv.fs_rename(r.path, path) if not ok then return vim.notify("LLeMbas: not moved: " .. tostring(err), vim.log.levels.WARN) end -- Buffers of the file, or of files under the directory, take the new name. for _, b in ipairs(vim.api.nvim_list_bufs()) do local name = vim.api.nvim_buf_get_name(b) if vim.bo[b].buftype == "" and (name == r.path or vim.startswith(name, r.path .. "/")) then local new = path .. name:sub(#r.path + 1) pcall(vim.api.nvim_buf_set_name, b, new) if vim.api.nvim_buf_is_loaded(b) then pcall(vim.api.nvim_buf_call, b, function() vim.cmd("silent! write!") end) end end end if T.open[r.path] then T.open[r.path], T.open[path] = nil, true end if T.current == r.path then T.current = path end reveal(path) M.render() go_to(path) M.git_refresh() end if to then return move(to) end vim.ui.input({ prompt = "Rename or move to: ", default = relative(r.path) }, move) end --- Delete the row under the cursor, after asking: to the trash where the system has one. function M.delete() local r = row_here() if not r then return end local name = relative(r.path) .. (r.dir and "/" or "") local trash = M._trash() local question = trash and ("Move %s to the trash?"):format(name) or ("Delete %s for good? (No trash was found on this system.)"):format(name) if not M._confirm(question) then return end local ok, why = true, nil if trash then local cmd = vim.list_extend(vim.list_slice(trash), { r.path }) local done = vim.system(cmd, { text = true }):wait(15000) ok, why = done.code == 0, vim.trim(done.stderr or "") else ok = vim.fn.delete(r.path, r.dir and "rf" or "") == 0 end if not ok then return vim.notify("LLeMbas: not deleted" .. (why and why ~= "" and (": " .. why) or ""), vim.log.levels.WARN) end for _, b in ipairs(vim.api.nvim_list_bufs()) do local bname = vim.api.nvim_buf_get_name(b) if vim.bo[b].buftype == "" and (bname == r.path or vim.startswith(bname, r.path .. "/")) and not vim.bo[b].modified then -- A window keeps its place: the buffer goes, an empty one stands in. for _, w in ipairs(vim.fn.win_findbuf(b)) do pcall(vim.api.nvim_win_call, w, function() vim.cmd("enew") end) end pcall(vim.api.nvim_buf_delete, b, {}) end end T.open[r.path] = nil M.render() M.git_refresh() end --- Show only the files whose path has `text` (empty: the tree again). function M.set_filter(text) T.filter = text or "" M.render() end --- `/`: the filter, typed on the command line and applied at every key. function M.ask_filter() local group = vim.api.nvim_create_augroup("llembas-tree-filter", { clear = true }) vim.api.nvim_create_autocmd("CmdlineChanged", { group = group, callback = function() M.set_filter(vim.fn.getcmdline()) vim.cmd("redraw") end, }) local ok, text = pcall(vim.fn.input, { prompt = "/", default = T.filter, cancelreturn = "" }) pcall(vim.api.nvim_del_augroup_by_id, group) M.set_filter(ok and text or "") end function M.toggle_hidden(on) if on == nil then T.hidden = not T.hidden else T.hidden = on end pcall(function() require("llembas.store").set("hidden_files", T.hidden) end) M.render() end function M.refresh() M.render() M.git_refresh() end --- One `git status` for the whole tree, off the main loop; the rows are marked when it answers. function M.git_refresh() if not T.root or vim.fn.executable("git") == 0 then return end T.git_job = T.git_job + 1 local job, root = T.git_job, T.root local ok = pcall(vim.system, { "git", "-C", root, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=normal" }, { text = true, env = { GIT_OPTIONAL_LOCKS = "0" } }, vim.schedule_wrap(function(done) if job ~= T.git_job or root ~= T.root then return end local git, dirs, branch = {}, {}, nil if done.code == 0 then local top = vim.trim(vim.fn.system({ "git", "-C", root, "rev-parse", "--show-toplevel" })) local parts = vim.split(done.stdout or "", "\0", { plain = true }) local i = 1 while i <= #parts do local e = parts[i] if e:sub(1, 2) == "##" then branch = e:sub(4):gsub("%.%.%..*$", ""):gsub("^No commits yet on ", "") elseif #e > 3 then local x, y, path = e:sub(1, 1), e:sub(2, 2), e:sub(4) if x == "R" or x == "C" then i = i + 1 end -- the name it had follows local mark = (x == "U" or y == "U" or (x == "A" and y == "A") or (x == "D" and y == "D")) and "!" or (x == "?" and "?") or ((x == "D" or y == "D") and "D") or ((x == "A") and "A") or "M" local full = top .. "/" .. path:gsub("/$", "") git[full] = mark local dir = full if path:sub(-1) == "/" then dirs[full] = true end while true do dir = vim.fs.dirname(dir) if not dir or #dir < #top or dirs[dir] then break end dirs[dir] = true end end i = i + 1 end end T.git, T.git_dirs, T.branch = git, dirs, branch M.render() pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false }) end)) if not ok then T.git, T.git_dirs = {}, {} end end --- The branch the tree's directory is on, or nil (not a repository, or not asked yet). function M.branch() return T.branch end --- The file in `buf` is the one you are in: its directories open, its row is marked and shown. function M.follow(buf) if not valid() or T.filter ~= "" then return end local name = vim.api.nvim_buf_get_name(buf) if name == "" or vim.bo[buf].buftype ~= "" or not T.root then return end name = vim.fs.normalize(name) if not vim.startswith(name, T.root .. "/") or name == T.current then return end T.current = name reveal(name) M.render() go_to(name) end local function buffer() if valid() then return T.buf end T.buf = vim.api.nvim_create_buf(false, true) vim.bo[T.buf].buftype = "nofile" vim.bo[T.buf].bufhidden = "hide" vim.bo[T.buf].swapfile = false vim.bo[T.buf].modeline = false vim.bo[T.buf].undolevels = -1 vim.bo[T.buf].filetype = "llembas-tree" pcall(vim.api.nvim_buf_set_name, T.buf, "llembas://tree") vim.bo[T.buf].modifiable = false require("llembas.keys").bind("tree", T.buf, { tree_open = function() M.activate(false) end, tree_close = M.collapse, tree_new = function() M.create() end, tree_rename = function() M.rename() end, tree_delete = M.delete, tree_filter = M.ask_filter, tree_hidden = function() M.toggle_hidden() end, tree_refresh = M.refresh, }) -- → only opens: an open directory stays open (Enter and l open and close). vim.keymap.set("n", "", function() M.activate(true) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file, or the directory" }) vim.keymap.set("n", "<2-LeftMouse>", function() M.activate(false) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file; open or close the directory" }) local group = vim.api.nvim_create_augroup("llembas-tree", { clear = true }) vim.api.nvim_create_autocmd("BufEnter", { group = group, callback = function(ev) M.follow(ev.buf) end }) vim.api.nvim_create_autocmd({ "BufWritePost", "FocusGained" }, { group = group, callback = function() if M.win() then M.refresh() end end }) vim.api.nvim_create_autocmd("DirChanged", { group = group, callback = function() if vim.v.event.scope == "global" and M.win() then M.set_root(vim.fn.getcwd()) end end, }) return T.buf end function M.set_root(dir) dir = vim.fs.normalize(vim.uv.fs_realpath(dir) or dir) if dir == T.root then return end T.root, T.open, T.git, T.git_dirs, T.branch, T.current, T.filter = dir, {}, {}, {}, nil, nil, "" M.refresh() end --- Open the tree's window on the left, `width` columns. Returns the window. The focus stays. function M.open(width) require("llembas.ui").setup_highlights() buffer() M.width = width or M.width or 26 local win = M.win() if win then return win end if not T.root then T.root = vim.fs.normalize(vim.uv.fs_realpath(vim.fn.getcwd()) or vim.fn.getcwd()) local remembered = require("llembas.store").get() if remembered.hidden_files ~= nil then T.hidden = remembered.hidden_files end end local back = vim.api.nvim_get_current_win() vim.cmd("topleft vertical " .. M.width .. "split") win = vim.api.nvim_get_current_win() vim.api.nvim_win_set_buf(win, T.buf) for k, v in pairs({ wrap = false, number = false, relativenumber = false, signcolumn = "no", foldcolumn = "0", list = false, cursorline = true, winfixwidth = true, spell = false, statuscolumn = "", }) do vim.api.nvim_set_option_value(k, v, { scope = "local", win = win }) end vim.wo[win].fillchars = "eob: " if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end M.render() M.git_refresh() local cur = vim.api.nvim_get_current_buf() M.follow(cur) return win end function M.close() local win = M.win() if win and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, win, true) end end function M.is_open() return M.win() ~= nil end --- The tree's lines as text, and its rows: for the tests and for anyone drawing it elsewhere. function M.lines() return valid() and vim.api.nvim_buf_get_lines(T.buf, 0, -1, false) or {} end function M.buf() return valid() and T.buf or nil end M._state = T return M