chore: add stylua to format the codebase, and run on CI (#1055)

This commit is contained in:
Kiyan 2022-03-06 17:33:30 +01:00 committed by GitHub
parent 76d181d480
commit 0816064a8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 871 additions and 732 deletions

View File

@ -1,6 +1,12 @@
name: Linting and style checking
name: CI
on: [push, pull_request]
on:
pull_request:
branches:
- '*'
push:
branches:
- master
jobs:
luacheck:
@ -17,3 +23,12 @@ jobs:
sudo luarocks install luacheck
- name: Run luacheck
run: luacheck .
stylua:
name: stylua
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: JohnnyMorganz/stylua-action@1.0.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --color always --check lua/

6
.stylua.toml Normal file
View File

@ -0,0 +1,6 @@
column_width = 120
line_endings = "Unix"
indent_type = "Spaces"
indent_width = 2
quote_style = "AutoPreferDouble"
call_parentheses = "None"

View File

@ -1,6 +1,6 @@
# A File Explorer For Neovim Written In Lua
[![Linting and style checking](https://github.com/kyazdani42/nvim-tree.lua/actions/workflows/luacheck.yml/badge.svg)](https://github.com/kyazdani42/nvim-tree.lua/actions/workflows/luacheck.yml)
[![CI](https://github.com/kyazdani42/nvim-tree.lua/actions/workflows/ci.yml/badge.svg)](https://github.com/kyazdani42/nvim-tree.lua/actions/workflows/ci.yml)
## Notice

View File

@ -1,13 +1,13 @@
local luv = vim.loop
local api = vim.api
local lib = require'nvim-tree.lib'
local colors = require'nvim-tree.colors'
local renderer = require'nvim-tree.renderer'
local view = require'nvim-tree.view'
local utils = require'nvim-tree.utils'
local change_dir = require'nvim-tree.actions.change-dir'
local legacy = require'nvim-tree.legacy'
local lib = require "nvim-tree.lib"
local colors = require "nvim-tree.colors"
local renderer = require "nvim-tree.renderer"
local view = require "nvim-tree.view"
local utils = require "nvim-tree.utils"
local change_dir = require "nvim-tree.actions.change-dir"
local legacy = require "nvim-tree.legacy"
local _config = {}
@ -19,7 +19,7 @@ function M.focus()
end
---@deprecated
M.on_keypress = require'nvim-tree.actions'.on_keypress
M.on_keypress = require("nvim-tree.actions").on_keypress
function M.toggle(find_file, no_focus)
if view.is_visible() then
@ -56,43 +56,40 @@ function M.open_replacing_current_buffer()
return
end
local cwd = vim.fn.fnamemodify(bufname, ':p:h')
local cwd = vim.fn.fnamemodify(bufname, ":p:h")
if not TreeExplorer or cwd ~= TreeExplorer.cwd then
lib.init(cwd)
end
view.open_in_current_win({ hijack_current_buf = false, resize = false })
require"nvim-tree.renderer".draw()
require"nvim-tree.actions.find-file".fn(bufname)
view.open_in_current_win { hijack_current_buf = false, resize = false }
require("nvim-tree.renderer").draw()
require("nvim-tree.actions.find-file").fn(bufname)
end
function M.tab_change()
if view.is_visible({ any_tabpage = true }) then
if view.is_visible { any_tabpage = true } then
local bufname = vim.api.nvim_buf_get_name(0)
if bufname:match("Neogit") ~= nil or bufname:match("--graph") ~= nil then
if bufname:match "Neogit" ~= nil or bufname:match "--graph" ~= nil then
return
end
view.open({ focus_tree = false })
require"nvim-tree.renderer".draw()
view.open { focus_tree = false }
require("nvim-tree.renderer").draw()
end
end
local function find_existing_windows()
return vim.tbl_filter(
function(win)
return vim.tbl_filter(function(win)
local buf = api.nvim_win_get_buf(win)
return api.nvim_buf_get_name(buf):match("NvimTree") ~= nil
end,
api.nvim_list_wins()
)
return api.nvim_buf_get_name(buf):match "NvimTree" ~= nil
end, api.nvim_list_wins())
end
local function is_file_readable(fname)
local stat = luv.fs_stat(fname)
return stat and stat.type == "file" and luv.fs_access(fname, 'R')
return stat and stat.type == "file" and luv.fs_access(fname, "R")
end
local function update_base_dir_with_filepath(filepath, bufnr)
local ft = api.nvim_buf_get_option(bufnr, 'filetype') or ""
local ft = api.nvim_buf_get_option(bufnr, "filetype") or ""
for _, value in pairs(_config.update_focused_file.ignore_list) do
if utils.str_find(filepath, value) or utils.str_find(ft, value) then
return
@ -100,16 +97,18 @@ local function update_base_dir_with_filepath(filepath, bufnr)
end
if not vim.startswith(filepath, TreeExplorer.cwd) then
change_dir.fn(vim.fn.fnamemodify(filepath, ':p:h'))
change_dir.fn(vim.fn.fnamemodify(filepath, ":p:h"))
end
end
function M.find_file(with_open, bufnr)
if not with_open and not TreeExplorer then return end
if not with_open and not TreeExplorer then
return
end
bufnr = bufnr or api.nvim_get_current_buf()
local bufname = api.nvim_buf_get_name(bufnr)
local filepath = utils.canonical_path(vim.fn.fnamemodify(bufname, ':p'))
local filepath = utils.canonical_path(vim.fn.fnamemodify(bufname, ":p"))
if not is_file_readable(filepath) then
return
end
@ -123,7 +122,7 @@ function M.find_file(with_open, bufnr)
if _config.update_focused_file.update_cwd then
update_base_dir_with_filepath(filepath, bufnr)
end
require"nvim-tree.actions.find-file".fn(filepath)
require("nvim-tree.actions.find-file").fn(filepath)
end)
end
@ -131,11 +130,11 @@ M.resize = view.resize
local function should_abort_auto_close()
local buf = api.nvim_get_current_buf()
local buftype = api.nvim_buf_get_option(buf, 'ft')
local buftype = api.nvim_buf_get_option(buf, "ft")
local modified = vim.tbl_filter(function(b)
return api.nvim_buf_get_option(b, 'modified')
return api.nvim_buf_get_option(b, "modified")
end, api.nvim_list_bufs())
return #modified > 0 or buftype:match('Telescope') ~= nil
return #modified > 0 or buftype:match "Telescope" ~= nil
end
function M.auto_close()
@ -154,9 +153,9 @@ function M.auto_close()
return api.nvim_win_get_tabpage(w) == curtab
end, windows)
if #windows == 1 then
api.nvim_command(':silent qa!')
api.nvim_command ":silent qa!"
elseif #wins_in_tabpage == 1 then
api.nvim_command(':tabclose')
api.nvim_command ":tabclose"
end
end, 50)
end
@ -206,11 +205,11 @@ end
function M.on_enter(netrw_disabled)
local bufnr = api.nvim_get_current_buf()
local bufname = api.nvim_buf_get_name(bufnr)
local buftype = api.nvim_buf_get_option(bufnr, 'filetype')
local buftype = api.nvim_buf_get_option(bufnr, "filetype")
local ft_ignore = _config.ignore_ft_on_setup
local stats = luv.fs_stat(bufname)
local is_dir = stats and stats.type == 'directory'
local is_dir = stats and stats.type == "directory"
local cwd
if is_dir then
cwd = vim.fn.expand(bufname)
@ -236,7 +235,10 @@ function M.on_enter(netrw_disabled)
end
end
local should_hijack = _config.hijack_directories.enable and _config.hijack_directories.auto_open and is_dir and not should_be_preserved
local should_hijack = _config.hijack_directories.enable
and _config.hijack_directories.auto_open
and is_dir
and not should_be_preserved
-- Session that left a NvimTree Buffer opened, reopen with it
local existing_tree_wins = find_existing_windows()
@ -249,7 +251,7 @@ function M.on_enter(netrw_disabled)
lib.open()
if should_focus_other_window then
vim.cmd("noautocmd wincmd p")
vim.cmd "noautocmd wincmd p"
end
end
M.initialized = true
@ -348,12 +350,12 @@ local DEFAULT_OPTS = {
update_focused_file = {
enable = false,
update_cwd = false,
ignore_list = {}
ignore_list = {},
},
ignore_ft_on_setup = {},
system_open = {
cmd = nil,
args = {}
args = {},
},
diagnostics = {
enable = false,
@ -363,12 +365,12 @@ local DEFAULT_OPTS = {
info = "",
warning = "",
error = "",
}
},
},
filters = {
dotfiles = false,
custom = {},
exclude = {}
exclude = {},
},
git = {
enable = true,
@ -385,8 +387,8 @@ local DEFAULT_OPTS = {
resize_window = false,
window_picker = {
enable = true,
}
}
},
},
},
}
@ -395,7 +397,7 @@ local function merge_options(conf)
conf.hijack_directories = conf.update_to_buf_dir
conf.update_to_buf_dir = nil
end
return vim.tbl_deep_extend('force', DEFAULT_OPTS, conf or {})
return vim.tbl_deep_extend("force", DEFAULT_OPTS, conf or {})
end
function M.setup(conf)
@ -413,13 +415,13 @@ function M.setup(conf)
manage_netrw(opts.disable_netrw, opts.hijack_netrw)
require'nvim-tree.actions'.setup(opts)
require'nvim-tree.colors'.setup()
require'nvim-tree.diagnostics'.setup(opts)
require'nvim-tree.explorer'.setup(opts)
require'nvim-tree.git'.setup(opts)
require'nvim-tree.view'.setup(opts)
require'nvim-tree.lib'.setup(opts)
require("nvim-tree.actions").setup(opts)
require("nvim-tree.colors").setup()
require("nvim-tree.diagnostics").setup(opts)
require("nvim-tree.explorer").setup(opts)
require("nvim-tree.git").setup(opts)
require("nvim-tree.view").setup(opts)
require("nvim-tree.lib").setup(opts)
setup_vim_commands()
setup_autocommands(opts)

View File

@ -1,18 +1,20 @@
local a = vim.api
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local M = {
current_tab = a.nvim_get_current_tabpage(),
options = {
global = false,
change_cwd = true,
}
},
}
function M.fn(name, with_open)
if not TreeExplorer then return end
if not TreeExplorer then
return
end
local foldername = name == '..' and vim.fn.fnamemodify(utils.path_remove_trailing(TreeExplorer.cwd), ':h') or name
local foldername = name == ".." and vim.fn.fnamemodify(utils.path_remove_trailing(TreeExplorer.cwd), ":h") or name
local no_cwd_change = vim.fn.expand(foldername) == TreeExplorer.cwd
local new_tab = a.nvim_get_current_tabpage()
local is_window = (vim.v.event.scope == "window" or vim.v.event.changed_window) and new_tab == M.current_tab
@ -26,16 +28,16 @@ end
function M.force_dirchange(foldername, with_open)
if M.options.change_cwd and vim.tbl_isempty(vim.v.event) then
if M.options.global then
vim.cmd('cd '..vim.fn.fnameescape(foldername))
vim.cmd("cd " .. vim.fn.fnameescape(foldername))
else
vim.cmd('lcd '..vim.fn.fnameescape(foldername))
vim.cmd("lcd " .. vim.fn.fnameescape(foldername))
end
end
require'nvim-tree.lib'.init(foldername)
require("nvim-tree.lib").init(foldername)
if with_open then
require"nvim-tree.lib".open()
require("nvim-tree.lib").open()
else
require"nvim-tree.renderer".draw()
require("nvim-tree.renderer").draw()
end
end

View File

@ -1,26 +1,26 @@
local a = vim.api
local uv = vim.loop
local lib = require'nvim-tree.lib'
local utils = require'nvim-tree.utils'
local lib = require "nvim-tree.lib"
local utils = require "nvim-tree.utils"
local M = {}
local clipboard = {
move = {},
copy = {}
copy = {},
}
local function do_copy(source, destination)
local source_stats = uv.fs_stat(source)
if source_stats and source_stats.type == 'file' then
if source_stats and source_stats.type == "file" then
return uv.fs_copyfile(source, destination)
end
local handle = uv.fs_scandir(source)
if type(handle) == 'string' then
if type(handle) == "string" then
return false, handle
end
@ -28,12 +28,16 @@ local function do_copy(source, destination)
while true do
local name, _ = uv.fs_scandir_next(handle)
if not name then break end
if not name then
break
end
local new_name = utils.path_join({source, name})
local new_destination = utils.path_join({destination, name})
local new_name = utils.path_join { source, name }
local new_destination = utils.path_join { destination, name }
local success, msg = do_copy(new_name, new_destination)
if not success then return success, msg end
if not success then
return success, msg
end
end
return true
@ -45,37 +49,39 @@ local function do_single_paste(source, dest, action_type, action_fn)
local should_rename = false
if dest_stats then
print(dest..' already exists. Overwrite? y/n/r(ename)')
print(dest .. " already exists. Overwrite? y/n/r(ename)")
local ans = utils.get_user_input_char()
utils.clear_prompt()
should_process = ans:match('^y')
should_rename = ans:match('^r')
should_process = ans:match "^y"
should_rename = ans:match "^r"
end
if should_rename then
local new_dest = vim.fn.input('New name: ', dest)
local new_dest = vim.fn.input("New name: ", dest)
return do_single_paste(source, new_dest, action_type, action_fn)
end
if should_process then
local success, errmsg = action_fn(source, dest)
if not success then
a.nvim_err_writeln('Could not '..action_type..' '..source..' - '..errmsg)
a.nvim_err_writeln("Could not " .. action_type .. " " .. source .. " - " .. errmsg)
end
end
end
local function add_to_clipboard(node, clip)
if node.name == '..' then return end
if node.name == ".." then
return
end
for idx, _node in ipairs(clip) do
if _node.absolute_path == node.absolute_path then
table.remove(clip, idx)
return a.nvim_out_write(node.absolute_path..' removed to clipboard.\n')
return a.nvim_out_write(node.absolute_path .. " removed to clipboard.\n")
end
end
table.insert(clip, node)
a.nvim_out_write(node.absolute_path..' added to clipboard.\n')
a.nvim_out_write(node.absolute_path .. " added to clipboard.\n")
end
function M.copy(node)
@ -88,27 +94,31 @@ end
local function do_paste(node, action_type, action_fn)
node = lib.get_last_group_node(node)
if node.name == '..' then return end
if node.name == ".." then
return
end
local clip = clipboard[action_type]
if #clip == 0 then return end
if #clip == 0 then
return
end
local destination = node.absolute_path
local stats = uv.fs_stat(destination)
local is_dir = stats and stats.type == 'directory'
local is_dir = stats and stats.type == "directory"
if not is_dir then
destination = vim.fn.fnamemodify(destination, ':p:h')
destination = vim.fn.fnamemodify(destination, ":p:h")
elseif not node.open then
destination = vim.fn.fnamemodify(destination, ':p:h:h')
destination = vim.fn.fnamemodify(destination, ":p:h:h")
end
for _, _node in ipairs(clip) do
local dest = utils.path_join({destination, _node.name })
local dest = utils.path_join { destination, _node.name }
do_single_paste(_node.absolute_path, dest, action_type, action_fn)
end
clipboard[action_type] = {}
return require'nvim-tree.actions.reloaders'.reload_explorer()
return require("nvim-tree.actions.reloaders").reload_explorer()
end
local function do_cut(source, destination)
@ -122,34 +132,34 @@ end
function M.paste(node)
if clipboard.move[1] ~= nil then
return do_paste(node, 'move', do_cut)
return do_paste(node, "move", do_cut)
end
return do_paste(node, 'copy', do_copy)
return do_paste(node, "copy", do_copy)
end
function M.print_clipboard()
local content = {}
if #clipboard.move > 0 then
table.insert(content, 'Cut')
table.insert(content, "Cut")
for _, item in pairs(clipboard.move) do
table.insert(content, ' * '..item.absolute_path)
table.insert(content, " * " .. item.absolute_path)
end
end
if #clipboard.copy > 0 then
table.insert(content, 'Copy')
table.insert(content, "Copy")
for _, item in pairs(clipboard.copy) do
table.insert(content, ' * '..item.absolute_path)
table.insert(content, " * " .. item.absolute_path)
end
end
return a.nvim_out_write(table.concat(content, '\n')..'\n')
return a.nvim_out_write(table.concat(content, "\n") .. "\n")
end
local function copy_to_clipboard(content)
vim.fn.setreg('+', content)
vim.fn.setreg("+", content)
vim.fn.setreg('"', content)
return a.nvim_out_write(string.format('Copied %s to system clipboard! \n', content))
return a.nvim_out_write(string.format("Copied %s to system clipboard! \n", content))
end
function M.copy_filename(node)

View File

@ -1,23 +1,22 @@
local a = vim.api
local uv = vim.loop
local utils = require'nvim-tree.utils'
local events = require'nvim-tree.events'
local lib = require'nvim-tree.lib'
local utils = require "nvim-tree.utils"
local events = require "nvim-tree.events"
local lib = require "nvim-tree.lib"
local M = {}
local function focus_file(file)
local _, i = utils.find_node(
TreeExplorer.nodes,
function(node) return node.absolute_path == file end
)
require'nvim-tree.view'.set_cursor({i+1, 1})
local _, i = utils.find_node(TreeExplorer.nodes, function(node)
return node.absolute_path == file
end)
require("nvim-tree.view").set_cursor { i + 1, 1 }
end
local function create_file(file)
if utils.file_exists(file) then
print(file..' already exists. Overwrite? y/n')
print(file .. " already exists. Overwrite? y/n")
local ans = utils.get_user_input_char()
utils.clear_prompt()
if ans ~= "y" then
@ -26,7 +25,7 @@ local function create_file(file)
end
local ok, fd = pcall(uv.fs_open, file, "w", 420)
if not ok then
a.nvim_err_writeln('Couldn\'t create file '..file)
a.nvim_err_writeln("Couldn't create file " .. file)
return
end
uv.fs_close(fd)
@ -46,20 +45,22 @@ local function get_containing_folder(node)
if node.nodes ~= nil and is_open then
return utils.path_add_trailing(node.absolute_path)
end
local node_name_size = #(node.name or '')
local node_name_size = #(node.name or "")
return node.absolute_path:sub(0, -node_name_size - 1)
end
local function get_input(containing_folder)
local ans = vim.fn.input('Create file ', containing_folder)
local ans = vim.fn.input("Create file ", containing_folder)
utils.clear_prompt()
if not ans or #ans == 0 or utils.file_exists(ans) then return end
if not ans or #ans == 0 or utils.file_exists(ans) then
return
end
return ans
end
function M.fn(node)
node = lib.get_last_group_node(node)
if node.name == '..' then
if node.name == ".." then
node = {
absolute_path = TreeExplorer.cwd,
nodes = TreeExplorer.nodes,
@ -69,12 +70,14 @@ function M.fn(node)
local containing_folder = get_containing_folder(node)
local file = get_input(containing_folder)
if not file then return end
if not file then
return
end
-- create a folder for each path element if the folder does not exist
-- if the answer ends with a /, create a file for the last path element
local is_last_path_file = not file:match(utils.path_separator..'$')
local path_to_create = ''
local is_last_path_file = not file:match(utils.path_separator .. "$")
local path_to_create = ""
local idx = 0
local num_nodes = get_num_nodes(utils.path_split(utils.path_remove_trailing(file)))
@ -82,27 +85,27 @@ function M.fn(node)
for path in utils.path_split(file) do
idx = idx + 1
local p = utils.path_remove_trailing(path)
if #path_to_create == 0 and vim.fn.has('win32') == 1 then
path_to_create = utils.path_join({p, path_to_create})
if #path_to_create == 0 and vim.fn.has "win32" == 1 then
path_to_create = utils.path_join { p, path_to_create }
else
path_to_create = utils.path_join({path_to_create, p})
path_to_create = utils.path_join { path_to_create, p }
end
if is_last_path_file and idx == num_nodes then
create_file(path_to_create)
elseif not utils.file_exists(path_to_create) then
local success = uv.fs_mkdir(path_to_create, 493)
if not success then
a.nvim_err_writeln('Could not create folder '..path_to_create)
a.nvim_err_writeln("Could not create folder " .. path_to_create)
is_error = true
break
end
end
end
if not is_error then
a.nvim_out_write(file..' was properly created\n')
a.nvim_out_write(file .. " was properly created\n")
end
events._dispatch_folder_created(file)
require'nvim-tree.actions.reloaders'.reload_explorer()
require("nvim-tree.actions.reloaders").reload_explorer()
focus_file(file)
end

View File

@ -1,14 +1,14 @@
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local M = {}
function M.fn(node)
if not node or node.name == ".." then
return require'nvim-tree.actions.change-dir'.fn('..')
return require("nvim-tree.actions.change-dir").fn ".."
else
local newdir = vim.fn.fnamemodify(utils.path_remove_trailing(TreeExplorer.cwd), ':h')
require'nvim-tree.actions.change-dir'.fn(newdir)
return require"nvim-tree.actions.find-file".fn(node.absolute_path)
local newdir = vim.fn.fnamemodify(utils.path_remove_trailing(TreeExplorer.cwd), ":h")
require("nvim-tree.actions.change-dir").fn(newdir)
return require("nvim-tree.actions.find-file").fn(node.absolute_path)
end
end

View File

@ -1,15 +1,15 @@
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local a = vim.api
local M = {}
local function get_formatted_lines(node)
local stats = node.fs_stat
local fpath = ' fullpath: ' .. node.absolute_path
local created_at = ' created: ' .. os.date("%x %X", stats.birthtime.sec)
local modified_at = ' modified: ' .. os.date("%x %X", stats.mtime.sec)
local accessed_at = ' accessed: ' .. os.date("%x %X", stats.atime.sec)
local size = ' size: ' .. utils.format_bytes(stats.size)
local fpath = " fullpath: " .. node.absolute_path
local created_at = " created: " .. os.date("%x %X", stats.birthtime.sec)
local modified_at = " modified: " .. os.date("%x %X", stats.mtime.sec)
local accessed_at = " accessed: " .. os.date("%x %X", stats.atime.sec)
local size = " size: " .. utils.format_bytes(stats.size)
return {
fpath,
@ -25,20 +25,22 @@ local current_popup = nil
local function setup_window(node)
local lines = get_formatted_lines(node)
local max_width = vim.fn.max(vim.tbl_map(function(n) return #n end, lines))
local max_width = vim.fn.max(vim.tbl_map(function(n)
return #n
end, lines))
local winnr = a.nvim_open_win(0, false, {
col = 1,
row = 1,
relative = "cursor",
width = max_width + 1,
height = #lines,
border = 'shadow',
border = "shadow",
noautocmd = true,
style = 'minimal'
style = "minimal",
})
current_popup = {
winnr = winnr,
file_path = node.absolute_path
file_path = node.absolute_path,
}
local bufnr = a.nvim_create_buf(false, true)
a.nvim_buf_set_lines(bufnr, 0, -1, false, lines)

View File

@ -1,12 +1,12 @@
local view = require'nvim-tree.view'
local utils = require'nvim-tree.utils'
local view = require "nvim-tree.view"
local utils = require "nvim-tree.utils"
local renderer = require "nvim-tree.renderer"
local M = {}
local function get_index_offset()
local hide_root_folder = view.View.hide_root_folder
if TreeExplorer.cwd == '/' or hide_root_folder then
if TreeExplorer.cwd == "/" or hide_root_folder then
return 0
else
return 1
@ -16,7 +16,9 @@ end
local running = {}
function M.fn(fname)
if running[fname] or not TreeExplorer then return end
if running[fname] or not TreeExplorer then
return
end
running[fname] = true
local i = get_index_offset()
@ -55,7 +57,7 @@ function M.fn(fname)
renderer.draw()
end
if index and view.is_visible() then
view.set_cursor({index, 0})
view.set_cursor { index, 0 }
end
running[fname] = false
end

View File

@ -1,9 +1,9 @@
local a = vim.api
local lib = require'nvim-tree.lib'
local view = require'nvim-tree.view'
local util = require'nvim-tree.utils'
local nvim_tree_callback = require'nvim-tree.config'.nvim_tree_callback
local lib = require "nvim-tree.lib"
local view = require "nvim-tree.view"
local util = require "nvim-tree.utils"
local nvim_tree_callback = require("nvim-tree.config").nvim_tree_callback
local M = {
mappings = {
@ -41,84 +41,90 @@ local M = {
{ key = "s", action = "system_open" },
{ key = "q", action = "close" },
{ key = "g?", action = "toggle_help" },
{ key = 'W', action = "collapse_all" },
{ key = "W", action = "collapse_all" },
{ key = "S", action = "search_node" },
{ key = ".", action = "run_file_command" },
{ key = "<C-k>", action = "toggle_file_info" }
{ key = "<C-k>", action = "toggle_file_info" },
},
custom_keypress_funcs = {},
}
local keypress_funcs = {
close = view.close,
close_node = require'nvim-tree.actions.movements'.parent_node(true),
collapse_all = require'nvim-tree.actions.collapse-all'.fn,
copy_absolute_path = require'nvim-tree.actions.copy-paste'.copy_absolute_path,
copy_name = require'nvim-tree.actions.copy-paste'.copy_filename,
copy_path = require'nvim-tree.actions.copy-paste'.copy_path,
copy = require'nvim-tree.actions.copy-paste'.copy,
create = require'nvim-tree.actions.create-file'.fn,
cut = require'nvim-tree.actions.copy-paste'.cut,
dir_up = require'nvim-tree.actions.dir-up'.fn,
first_sibling = require'nvim-tree.actions.movements'.sibling(-math.huge),
full_rename = require'nvim-tree.actions.rename-file'.fn(true),
last_sibling = require'nvim-tree.actions.movements'.sibling(math.huge),
next_git_item = require"nvim-tree.actions.movements".find_git_item('next'),
next_sibling = require'nvim-tree.actions.movements'.sibling(1),
parent_node = require'nvim-tree.actions.movements'.parent_node(false),
paste = require'nvim-tree.actions.copy-paste'.paste,
prev_git_item = require"nvim-tree.actions.movements".find_git_item('prev'),
prev_sibling = require'nvim-tree.actions.movements'.sibling(-1),
refresh = require'nvim-tree.actions.reloaders'.reload_explorer,
remove = require'nvim-tree.actions.remove-file'.fn,
rename = require'nvim-tree.actions.rename-file'.fn(false),
run_file_command = require'nvim-tree.actions.run-command'.run_file_command,
search_node = require'nvim-tree.actions.search-node'.fn,
toggle_file_info = require'nvim-tree.actions.file-popup'.toggle_file_info,
system_open = require'nvim-tree.actions.system-open'.fn,
toggle_dotfiles = require"nvim-tree.actions.toggles".dotfiles,
toggle_help = require"nvim-tree.actions.toggles".help,
toggle_ignored = require"nvim-tree.actions.toggles".ignored,
trash = require'nvim-tree.actions.trash'.fn,
close_node = require("nvim-tree.actions.movements").parent_node(true),
collapse_all = require("nvim-tree.actions.collapse-all").fn,
copy_absolute_path = require("nvim-tree.actions.copy-paste").copy_absolute_path,
copy_name = require("nvim-tree.actions.copy-paste").copy_filename,
copy_path = require("nvim-tree.actions.copy-paste").copy_path,
copy = require("nvim-tree.actions.copy-paste").copy,
create = require("nvim-tree.actions.create-file").fn,
cut = require("nvim-tree.actions.copy-paste").cut,
dir_up = require("nvim-tree.actions.dir-up").fn,
first_sibling = require("nvim-tree.actions.movements").sibling(-math.huge),
full_rename = require("nvim-tree.actions.rename-file").fn(true),
last_sibling = require("nvim-tree.actions.movements").sibling(math.huge),
next_git_item = require("nvim-tree.actions.movements").find_git_item "next",
next_sibling = require("nvim-tree.actions.movements").sibling(1),
parent_node = require("nvim-tree.actions.movements").parent_node(false),
paste = require("nvim-tree.actions.copy-paste").paste,
prev_git_item = require("nvim-tree.actions.movements").find_git_item "prev",
prev_sibling = require("nvim-tree.actions.movements").sibling(-1),
refresh = require("nvim-tree.actions.reloaders").reload_explorer,
remove = require("nvim-tree.actions.remove-file").fn,
rename = require("nvim-tree.actions.rename-file").fn(false),
run_file_command = require("nvim-tree.actions.run-command").run_file_command,
search_node = require("nvim-tree.actions.search-node").fn,
toggle_file_info = require("nvim-tree.actions.file-popup").toggle_file_info,
system_open = require("nvim-tree.actions.system-open").fn,
toggle_dotfiles = require("nvim-tree.actions.toggles").dotfiles,
toggle_help = require("nvim-tree.actions.toggles").help,
toggle_ignored = require("nvim-tree.actions.toggles").ignored,
trash = require("nvim-tree.actions.trash").fn,
}
function M.on_keypress(action)
if view.is_help_ui() and action == 'close' then
action = 'toggle_help';
if view.is_help_ui() and action == "close" then
action = "toggle_help"
end
if view.is_help_ui() and action ~= "toggle_help" then
return
end
if view.is_help_ui() and action ~= 'toggle_help' then return end
local node = lib.get_node_at_cursor()
if not node then return end
if not node then
return
end
local custom_function = M.custom_keypress_funcs[action]
local default_function = keypress_funcs[action]
if type(custom_function) == 'function' then
if type(custom_function) == "function" then
return custom_function(node)
elseif default_function then
return default_function(node)
end
if action == "preview" then
if node.name == '..' then return end
if node.name == ".." then
return
end
if not node.nodes then
return require'nvim-tree.actions.open-file'.fn('preview', node.absolute_path)
return require("nvim-tree.actions.open-file").fn("preview", node.absolute_path)
end
elseif node.name == ".." then
return require'nvim-tree.actions.change-dir'.fn("..")
return require("nvim-tree.actions.change-dir").fn ".."
elseif action == "cd" then
if node.nodes ~= nil then
require'nvim-tree.actions.change-dir'.fn(lib.get_last_group_node(node).absolute_path)
require("nvim-tree.actions.change-dir").fn(lib.get_last_group_node(node).absolute_path)
end
return
end
if node.link_to and not node.nodes then
require'nvim-tree.actions.open-file'.fn(action, node.link_to)
require("nvim-tree.actions.open-file").fn(action, node.link_to)
elseif node.nodes ~= nil then
lib.expand_or_collapse(node)
else
require'nvim-tree.actions.open-file'.fn(action, node.absolute_path)
require("nvim-tree.actions.open-file").fn(action, node.absolute_path)
end
end
@ -127,10 +133,10 @@ function M.apply_mappings(bufnr)
local mapping_rhs = b.cb or nvim_tree_callback(b.action)
if type(b.key) == "table" then
for _, key in pairs(b.key) do
a.nvim_buf_set_keymap(bufnr, b.mode or 'n', key, mapping_rhs, { noremap = true, silent = true, nowait = true })
a.nvim_buf_set_keymap(bufnr, b.mode or "n", key, mapping_rhs, { noremap = true, silent = true, nowait = true })
end
elseif mapping_rhs then
a.nvim_buf_set_keymap(bufnr, b.mode or 'n', b.key, mapping_rhs, { noremap = true, silent = true, nowait = true })
a.nvim_buf_set_keymap(bufnr, b.mode or "n", b.key, mapping_rhs, { noremap = true, silent = true, nowait = true })
end
end
end
@ -141,7 +147,7 @@ local function merge_mappings(user_mappings)
end
local function is_empty(s)
return s == ''
return s == ""
end
local user_keys = {}
@ -166,7 +172,7 @@ local function merge_mappings(user_mappings)
if not is_empty(map.action) then
M.custom_keypress_funcs[map.action] = map.action_cb
else
util.warn("action can't be empty if action_cb provided")
util.warn "action can't be empty if action_cb provided"
end
end
end
@ -209,17 +215,17 @@ end
local DEFAULT_MAPPING_CONFIG = {
custom_only = false,
list = {}
list = {},
}
function M.setup(opts)
require'nvim-tree.actions.system-open'.setup(opts.system_open)
require'nvim-tree.actions.trash'.setup(opts.trash)
require'nvim-tree.actions.open-file'.setup(opts)
require'nvim-tree.actions.change-dir'.setup(opts)
require("nvim-tree.actions.system-open").setup(opts.system_open)
require("nvim-tree.actions.trash").setup(opts.trash)
require("nvim-tree.actions.open-file").setup(opts)
require("nvim-tree.actions.change-dir").setup(opts)
local user_map_config = (opts.view or {}).mappings or {}
local options = vim.tbl_deep_extend('force', DEFAULT_MAPPING_CONFIG, user_map_config)
local options = vim.tbl_deep_extend("force", DEFAULT_MAPPING_CONFIG, user_map_config)
if options.custom_only then
M.mappings = copy_mappings(options.list)
else

View File

@ -1,8 +1,10 @@
local utils = require'nvim-tree.utils'
local view = require'nvim-tree.view'
local diagnostics = require'nvim-tree.diagnostics'
local utils = require "nvim-tree.utils"
local view = require "nvim-tree.view"
local diagnostics = require "nvim-tree.diagnostics"
local renderer = require "nvim-tree.renderer"
local lib = function() return require'nvim-tree.lib' end
local lib = function()
return require "nvim-tree.lib"
end
local M = {}
@ -24,17 +26,20 @@ local function get_line_from_node(node, find_parent)
line = line + 1
if _node.open == true and recursive then
local _, child = iter(_node.nodes, recursive)
if child ~= nil then return line, child end
if child ~= nil then
return line, child
end
end
end
end
return iter
end
function M.parent_node(should_close)
return function(node)
if node.name == '..' then return end
if node.name == ".." then
return
end
should_close = should_close or false
local altered_tree = false
@ -52,7 +57,7 @@ function M.parent_node(should_close)
altered_tree = true
end
line = view.View.hide_root_folder and line - 1 or line
view.set_cursor({line, 0})
view.set_cursor { line, 0 }
end
if altered_tree then
@ -64,7 +69,9 @@ end
function M.sibling(direction)
return function(node)
if node.name == '..' or not direction then return end
if node.name == ".." or not direction then
return
end
local iter = get_line_from_node(node, true)
local node_path = node.absolute_path
@ -100,7 +107,7 @@ function M.sibling(direction)
local target_node = parent.nodes[index]
line, _ = get_line_from_node(target_node)(TreeExplorer.nodes, true)
view.set_cursor({line, 0})
view.set_cursor { line, 0 }
end
end
@ -128,17 +135,17 @@ function M.find_git_item(where)
end
end
if where == 'prev' then
if where == "prev" then
if prev then
view.set_cursor({prev, 0})
view.set_cursor { prev, 0 }
end
else
if cur then
if nex then
view.set_cursor({nex, 0})
view.set_cursor { nex, 0 }
end
elseif first then
view.set_cursor({first, 0})
view.set_cursor { first, 0 }
end
end
end

View File

@ -1,8 +1,8 @@
local api = vim.api
local lib = require'nvim-tree.lib'
local utils = require'nvim-tree.utils'
local view = require'nvim-tree.view'
local lib = require "nvim-tree.lib"
local utils = require "nvim-tree.utils"
local view = require "nvim-tree.view"
local M = {
quit_on_open = false,
@ -11,24 +11,24 @@ local M = {
enable = true,
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
exclude = {
filetype = { "notify", "packer", "qf", "diff", "fugitive", "fugitiveblame", },
buftype = { "nofile", "terminal", "help", },
}
}
filetype = { "notify", "packer", "qf", "diff", "fugitive", "fugitiveblame" },
buftype = { "nofile", "terminal", "help" },
},
},
}
local function get_split_cmd()
local side = view.View.side
if side == 'right' then
return 'aboveleft'
if side == "right" then
return "aboveleft"
end
if side == "left" then
return 'belowright'
return "belowright"
end
if side == "top" then
return 'bot'
return "bot"
end
return 'top'
return "top"
end
---Get user to pick a window. Selectable windows are all windows in the current
@ -51,14 +51,16 @@ local function pick_window()
end
local win_config = api.nvim_win_get_config(id)
return id ~= tree_winid
and win_config.focusable
and not win_config.external
return id ~= tree_winid and win_config.focusable and not win_config.external
end, win_ids)
-- If there are no selectable windows: return. If there's only 1, return it without picking.
if #selectable == 0 then return -1 end
if #selectable == 1 then return selectable[1] end
if #selectable == 0 then
return -1
end
if #selectable == 1 then
return selectable[1]
end
local i = 1
local win_opts = {}
@ -74,21 +76,21 @@ local function pick_window()
win_opts[id] = {
statusline = ok_status and statusline or "",
winhl = ok_hl and winhl or ""
winhl = ok_hl and winhl or "",
}
win_map[char] = id
api.nvim_win_set_option(id, "statusline", "%=" .. char .. "%=")
api.nvim_win_set_option(
id, "winhl", "StatusLine:NvimTreeWindowPicker,StatusLineNC:NvimTreeWindowPicker"
)
api.nvim_win_set_option(id, "winhl", "StatusLine:NvimTreeWindowPicker,StatusLineNC:NvimTreeWindowPicker")
i = i + 1
if i > #M.window_picker.chars then break end
if i > #M.window_picker.chars then
break
end
end
vim.cmd("redraw")
print("Pick window: ")
vim.cmd "redraw"
print "Pick window: "
local _, resp = pcall(utils.get_user_input_char)
resp = (resp or ""):upper()
utils.clear_prompt()
@ -114,7 +116,7 @@ local function open_file_in_tab(filename)
if lib.target_winid > 0 and api.nvim_win_is_valid(lib.target_winid) then
api.nvim_set_current_win(lib.target_winid)
else
vim.cmd("wincmd p")
vim.cmd "wincmd p"
end
end
@ -126,13 +128,13 @@ local function open_file_in_tab(filename)
vim.cmd("edit " .. vim.fn.fnameescape(filename))
local alt_bufid = vim.fn.bufnr("#")
local alt_bufid = vim.fn.bufnr "#"
if alt_bufid ~= -1 then
api.nvim_set_current_buf(alt_bufid)
end
if not M.quit_on_open then
vim.cmd("wincmd p")
vim.cmd "wincmd p"
end
vim.cmd("tabe " .. vim.fn.fnameescape(filename))
@ -145,7 +147,7 @@ function M.fn(mode, filename)
end
if mode == "edit_in_place" then
require"nvim-tree.view".abandon_current_window()
require("nvim-tree.view").abandon_current_window()
vim.cmd("edit " .. vim.fn.fnameescape(filename))
return
end
@ -171,7 +173,9 @@ function M.fn(mode, filename)
local found = false
for _, id in ipairs(win_ids) do
if filename == api.nvim_buf_get_name(api.nvim_win_get_buf(id)) then
if mode == "preview" then return end
if mode == "preview" then
return
end
found = true
api.nvim_set_current_win(id)
break
@ -230,7 +234,7 @@ function M.setup(opts)
if opts.actions.open_file.window_picker.chars then
opts.actions.open_file.window_picker.chars = tostring(opts.actions.open_file.window_picker.chars):upper()
end
M.window_picker = vim.tbl_extend('force', M.window_picker, opts.actions.open_file.window_picker)
M.window_picker = vim.tbl_extend("force", M.window_picker, opts.actions.open_file.window_picker)
end
return M

View File

@ -2,7 +2,7 @@ local git = require "nvim-tree.git"
local diagnostics = require "nvim-tree.diagnostics"
local view = require "nvim-tree.view"
local renderer = require "nvim-tree.renderer"
local explorer_module = require'nvim-tree.explorer'
local explorer_module = require "nvim-tree.explorer"
local M = {}

View File

@ -1,8 +1,8 @@
local a = vim.api
local luv = vim.loop
local utils = require'nvim-tree.utils'
local events = require'nvim-tree.events'
local utils = require "nvim-tree.utils"
local events = require "nvim-tree.events"
local M = {}
@ -15,13 +15,13 @@ local function close_windows(windows)
end
local function clear_buffer(absolute_path)
local bufs = vim.fn.getbufinfo({bufloaded = 1, buflisted = 1})
local bufs = vim.fn.getbufinfo { bufloaded = 1, buflisted = 1 }
for _, buf in pairs(bufs) do
if buf.name == absolute_path then
if buf.hidden == 0 and #bufs > 1 then
local winnr = a.nvim_get_current_win()
a.nvim_set_current_win(buf.windows[1])
vim.cmd(':bn')
vim.cmd ":bn"
a.nvim_set_current_win(winnr)
end
a.nvim_buf_delete(buf.bufnr, { force = true })
@ -33,21 +33,27 @@ end
local function remove_dir(cwd)
local handle = luv.fs_scandir(cwd)
if type(handle) == 'string' then
if type(handle) == "string" then
return a.nvim_err_writeln(handle)
end
while true do
local name, t = luv.fs_scandir_next(handle)
if not name then break end
if not name then
break
end
local new_cwd = utils.path_join({cwd, name})
if t == 'directory' then
local new_cwd = utils.path_join { cwd, name }
if t == "directory" then
local success = remove_dir(new_cwd)
if not success then return false end
if not success then
return false
end
else
local success = luv.fs_unlink(new_cwd)
if not success then return false end
if not success then
return false
end
clear_buffer(new_cwd)
end
end
@ -55,29 +61,30 @@ local function remove_dir(cwd)
return luv.fs_rmdir(cwd)
end
function M.fn(node)
if node.name == '..' then return end
if node.name == ".." then
return
end
print("Remove " .. node.name .. " ? y/n")
local ans = utils.get_user_input_char()
utils.clear_prompt()
if ans:match('^y') then
if ans:match "^y" then
if node.nodes ~= nil and not node.link_to then
local success = remove_dir(node.absolute_path)
if not success then
return a.nvim_err_writeln('Could not remove '..node.name)
return a.nvim_err_writeln("Could not remove " .. node.name)
end
events._dispatch_folder_removed(node.absolute_path)
else
local success = luv.fs_unlink(node.absolute_path)
if not success then
return a.nvim_err_writeln('Could not remove '..node.name)
return a.nvim_err_writeln("Could not remove " .. node.name)
end
events._dispatch_file_removed(node.absolute_path)
clear_buffer(node.absolute_path)
end
require'nvim-tree.actions.reloaders'.reload_explorer()
require("nvim-tree.actions.reloaders").reload_explorer()
end
end

View File

@ -1,37 +1,39 @@
local a = vim.api
local uv = vim.loop
local lib = require'nvim-tree.lib'
local utils = require'nvim-tree.utils'
local events = require'nvim-tree.events'
local lib = require "nvim-tree.lib"
local utils = require "nvim-tree.utils"
local events = require "nvim-tree.events"
local M = {}
function M.fn(with_sub)
return function(node)
node = lib.get_last_group_node(node)
if node.name == '..' then return end
if node.name == ".." then
return
end
local namelen = node.name:len()
local abs_path = with_sub and node.absolute_path:sub(0, namelen * (-1) -1) or node.absolute_path
local abs_path = with_sub and node.absolute_path:sub(0, namelen * -1 - 1) or node.absolute_path
local new_name = vim.fn.input("Rename " .. node.name .. " to ", abs_path)
utils.clear_prompt()
if not new_name or #new_name == 0 then
return
end
if utils.file_exists(new_name) then
utils.warn("Cannot rename: file already exists")
utils.warn "Cannot rename: file already exists"
return
end
local success = uv.fs_rename(node.absolute_path, new_name)
if not success then
return a.nvim_err_writeln('Could not rename '..node.absolute_path..' to '..new_name)
return a.nvim_err_writeln("Could not rename " .. node.absolute_path .. " to " .. new_name)
end
a.nvim_out_write(node.absolute_path..''..new_name..'\n')
a.nvim_out_write(node.absolute_path .. "" .. new_name .. "\n")
utils.rename_loaded_buffers(node.absolute_path, new_name)
events._dispatch_node_renamed(abs_path, new_name)
require'nvim-tree.actions.reloaders'.reload_explorer()
require("nvim-tree.actions.reloaders").reload_explorer()
end
end

View File

@ -1,4 +1,4 @@
local utils = require("nvim-tree.utils")
local utils = require "nvim-tree.utils"
local M = {}

View File

@ -5,15 +5,17 @@ local renderer = require"nvim-tree.renderer"
local M = {}
function M.fn()
if not TreeExplorer then return end
if not TreeExplorer then
return
end
local input_path = vim.fn.input("Search node: ", "", "file")
utils.clear_prompt()
local absolute_input_path = utils.path_join({
local absolute_input_path = utils.path_join {
TreeExplorer.cwd,
input_path
})
input_path,
}
local function count_visible_nodes(nodes)
local visible_nodes = 0
@ -44,7 +46,7 @@ function M.fn()
if node.nodes then
-- e.g. user searches for "/foo/bar.txt", than directory "/foo/bar" should not match with filename
local matches = utils.str_find(absolute_input_path, node.absolute_path .. '/')
local matches = utils.str_find(absolute_input_path, node.absolute_path .. "/")
if matches then
found_something = true
@ -75,11 +77,11 @@ function M.fn()
end
if found_something and view.is_visible() then
if TreeExplorer.cwd ~= '/' and not view.View.hide_root_folder then
if TreeExplorer.cwd ~= "/" and not view.View.hide_root_folder then
index = index + 1
end
view.set_cursor({index, 0})
view.set_cursor { index, 0 }
end
end

View File

@ -2,33 +2,34 @@ local uv = vim.loop
local M = {
config = {
is_windows = vim.fn.has('win32') == 1 or vim.fn.has('win32unix') == 1,
is_macos = vim.fn.has('mac') == 1 or vim.fn.has('macunix') == 1,
is_unix = vim.fn.has('unix') == 1,
}
is_windows = vim.fn.has "win32" == 1 or vim.fn.has "win32unix" == 1,
is_macos = vim.fn.has "mac" == 1 or vim.fn.has "macunix" == 1,
is_unix = vim.fn.has "unix" == 1,
},
}
function M.fn(node)
if not M.config.system_open.cmd then
require'nvim-tree.utils'.warn("Cannot open file with system application. Unrecognized platform.")
require("nvim-tree.utils").warn "Cannot open file with system application. Unrecognized platform."
return
end
local process = {
cmd = M.config.system_open.cmd,
args = M.config.system_open.args,
errors = '\n',
stderr = uv.new_pipe(false)
errors = "\n",
stderr = uv.new_pipe(false),
}
table.insert(process.args, node.link_to or node.absolute_path)
process.handle, process.pid = uv.spawn(process.cmd,
process.handle, process.pid = uv.spawn(
process.cmd,
{ args = process.args, stdio = { nil, nil, process.stderr }, detached = true },
function(code)
process.stderr:read_stop()
process.stderr:close()
process.handle:close()
if code ~= 0 then
process.errors = process.errors .. string.format('NvimTree system_open: return code %d.', code)
process.errors = process.errors .. string.format("NvimTree system_open: return code %d.", code)
error(process.errors)
end
end
@ -38,14 +39,15 @@ function M.fn(node)
error("\n" .. process.pid .. "\nNvimTree system_open: failed to spawn process using '" .. process.cmd .. "'.")
return
end
uv.read_start(process.stderr,
function(err, data)
if err then return end
if data then process.errors = process.errors .. data end
uv.read_start(process.stderr, function(err, data)
if err then
return
end
)
if data then
process.errors = process.errors .. data
end
end)
uv.unref(process.handle)
end
function M.setup(opts)
@ -55,12 +57,12 @@ function M.setup(opts)
if M.config.is_windows then
M.config.system_open = {
cmd = "cmd",
args = {'/c', 'start', '""'}
args = { "/c", "start", '""' },
}
elseif M.config.is_macos then
M.config.system_open.cmd = 'open'
M.config.system_open.cmd = "open"
elseif M.config.is_unix then
M.config.system_open.cmd = 'xdg-open'
M.config.system_open.cmd = "xdg-open"
end
end
end

View File

@ -2,23 +2,23 @@ local a = vim.api
local M = {
config = {
is_windows = vim.fn.has('win32') == 1 or vim.fn.has('win32unix') == 1,
is_macos = vim.fn.has('mac') == 1 or vim.fn.has('macunix') == 1,
is_unix = vim.fn.has('unix') == 1,
}
is_windows = vim.fn.has "win32" == 1 or vim.fn.has "win32unix" == 1,
is_macos = vim.fn.has "mac" == 1 or vim.fn.has "macunix" == 1,
is_unix = vim.fn.has "unix" == 1,
},
}
local utils = require'nvim-tree.utils'
local events = require'nvim-tree.events'
local utils = require "nvim-tree.utils"
local events = require "nvim-tree.events"
local function clear_buffer(absolute_path)
local bufs = vim.fn.getbufinfo({bufloaded = 1, buflisted = 1})
local bufs = vim.fn.getbufinfo { bufloaded = 1, buflisted = 1 }
for _, buf in pairs(bufs) do
if buf.name == absolute_path then
if buf.hidden == 0 and #bufs > 1 then
local winnr = a.nvim_get_current_win()
a.nvim_set_current_win(buf.windows[1])
vim.cmd(':bn')
vim.cmd ":bn"
a.nvim_set_current_win(winnr)
end
vim.api.nvim_buf_delete(buf.bufnr, {})
@ -28,14 +28,20 @@ local function clear_buffer(absolute_path)
end
function M.fn(node)
if node.name == '..' then return end
if node.name == ".." then
return
end
-- configs
if M.config.is_unix then
if M.config.trash.cmd == nil then M.config.trash.cmd = 'trash' end
if M.config.trash.require_confirm == nil then M.config.trash.require_confirm = true end
if M.config.trash.cmd == nil then
M.config.trash.cmd = "trash"
end
if M.config.trash.require_confirm == nil then
M.config.trash.require_confirm = true
end
else
utils.warn('Trash is currently a UNIX only feature!')
utils.warn "Trash is currently a UNIX only feature!"
return
end
@ -54,7 +60,9 @@ function M.fn(node)
is_confirmed = false
print("Trash " .. node.name .. " ? y/n")
local ans = utils.get_user_input_char()
if ans:match('^y') then is_confirmed = true end
if ans:match "^y" then
is_confirmed = true
end
utils.clear_prompt()
end
@ -63,16 +71,15 @@ function M.fn(node)
if node.nodes ~= nil and not node.link_to then
trash_path(function()
events._dispatch_folder_removed(node.absolute_path)
require'nvim-tree.actions.reloaders'.reload_explorer()
require("nvim-tree.actions.reloaders").reload_explorer()
end)
else
trash_path(function()
events._dispatch_file_removed(node.absolute_path)
clear_buffer(node.absolute_path)
require'nvim-tree.actions.reloaders'.reload_explorer()
require("nvim-tree.actions.reloaders").reload_explorer()
end)
end
end
end

View File

@ -1,28 +1,32 @@
local api = vim.api
local icons = require'nvim-tree.renderer.icons'
local icons = require "nvim-tree.renderer.icons"
local M = {}
local function get_color_from_hl(hl_name, fallback)
local id = vim.api.nvim_get_hl_id_by_name(hl_name)
if not id then return fallback end
if not id then
return fallback
end
local foreground = vim.fn.synIDattr(vim.fn.synIDtrans(id), "fg")
if not foreground or foreground == "" then return fallback end
if not foreground or foreground == "" then
return fallback
end
return foreground
end
local function get_colors()
return {
red = vim.g.terminal_color_1 or get_color_from_hl('Keyword', 'Red'),
green = vim.g.terminal_color_2 or get_color_from_hl('Character', 'Green'),
yellow = vim.g.terminal_color_3 or get_color_from_hl('PreProc', 'Yellow'),
blue = vim.g.terminal_color_4 or get_color_from_hl('Include', 'Blue'),
purple = vim.g.terminal_color_5 or get_color_from_hl('Define', 'Purple'),
cyan = vim.g.terminal_color_6 or get_color_from_hl('Conditional', 'Cyan'),
dark_red = vim.g.terminal_color_9 or get_color_from_hl('Keyword', 'DarkRed'),
orange = vim.g.terminal_color_11 or get_color_from_hl('Number', 'Orange'),
red = vim.g.terminal_color_1 or get_color_from_hl("Keyword", "Red"),
green = vim.g.terminal_color_2 or get_color_from_hl("Character", "Green"),
yellow = vim.g.terminal_color_3 or get_color_from_hl("PreProc", "Yellow"),
blue = vim.g.terminal_color_4 or get_color_from_hl("Include", "Blue"),
purple = vim.g.terminal_color_5 or get_color_from_hl("Define", "Purple"),
cyan = vim.g.terminal_color_6 or get_color_from_hl("Conditional", "Cyan"),
dark_red = vim.g.terminal_color_9 or get_color_from_hl("Keyword", "DarkRed"),
orange = vim.g.terminal_color_11 or get_color_from_hl("Number", "Orange"),
}
end
@ -30,15 +34,15 @@ local function get_hl_groups()
local colors = get_colors()
return {
IndentMarker = { fg = '#8094b4' },
Symlink = { gui = 'bold', fg = colors.cyan },
FolderIcon = { fg = '#8094b4' },
IndentMarker = { fg = "#8094b4" },
Symlink = { gui = "bold", fg = colors.cyan },
FolderIcon = { fg = "#8094b4" },
RootFolder = { fg = colors.purple },
ExecFile = { gui = 'bold', fg = colors.green },
SpecialFile = { gui = 'bold,underline', fg = colors.yellow },
ImageFile = { gui = 'bold', fg = colors.purple },
OpenedFile = { gui = 'bold', fg = colors.green },
ExecFile = { gui = "bold", fg = colors.green },
SpecialFile = { gui = "bold,underline", fg = colors.yellow },
ImageFile = { gui = "bold", fg = colors.purple },
OpenedFile = { gui = "bold", fg = colors.green },
GitDirty = { fg = colors.dark_red },
GitDeleted = { fg = colors.dark_red },
@ -47,50 +51,50 @@ local function get_hl_groups()
GitRenamed = { fg = colors.purple },
GitNew = { fg = colors.yellow },
WindowPicker = { gui = "bold", fg = "#ededed", bg = "#4493c8" }
WindowPicker = { gui = "bold", fg = "#ededed", bg = "#4493c8" },
}
end
local function get_links()
return {
FolderName = 'Directory',
EmptyFolderName = 'Directory',
OpenedFolderName = 'Directory',
Normal = 'Normal',
NormalNC = 'NvimTreeNormal',
EndOfBuffer = 'EndOfBuffer',
CursorLine = 'CursorLine',
VertSplit = 'VertSplit',
CursorColumn = 'CursorColumn',
FileDirty = 'NvimTreeGitDirty',
FileNew = 'NvimTreeGitNew',
FileRenamed = 'NvimTreeGitRenamed',
FileMerge = 'NvimTreeGitMerge',
FileStaged = 'NvimTreeGitStaged',
FileDeleted = 'NvimTreeGitDeleted',
Popup = 'Normal',
GitIgnored = 'Comment',
FolderName = "Directory",
EmptyFolderName = "Directory",
OpenedFolderName = "Directory",
Normal = "Normal",
NormalNC = "NvimTreeNormal",
EndOfBuffer = "EndOfBuffer",
CursorLine = "CursorLine",
VertSplit = "VertSplit",
CursorColumn = "CursorColumn",
FileDirty = "NvimTreeGitDirty",
FileNew = "NvimTreeGitNew",
FileRenamed = "NvimTreeGitRenamed",
FileMerge = "NvimTreeGitMerge",
FileStaged = "NvimTreeGitStaged",
FileDeleted = "NvimTreeGitDeleted",
Popup = "Normal",
GitIgnored = "Comment",
StatusLine = "StatusLine",
StatusLineNC = "StatusLineNC",
SignColumn = 'NvimTreeNormal',
SignColumn = "NvimTreeNormal",
}
end
function M.setup()
if icons.get_config().show_file_icon and icons.get_config().has_devicons then
require'nvim-web-devicons'.setup()
require("nvim-web-devicons").setup()
end
local higlight_groups = get_hl_groups()
for k, d in pairs(higlight_groups) do
local gui = d.gui and ' gui='..d.gui or ''
local fg = d.fg and ' guifg='..d.fg or ''
local bg = d.bg and ' guibg='..d.bg or ''
api.nvim_command('hi def NvimTree'..k..gui..fg..bg)
local gui = d.gui and " gui=" .. d.gui or ""
local fg = d.fg and " guifg=" .. d.fg or ""
local bg = d.bg and " guibg=" .. d.bg or ""
api.nvim_command("hi def NvimTree" .. k .. gui .. fg .. bg)
end
local links = get_links()
for k, d in pairs(links) do
api.nvim_command('hi def link NvimTree'..k..' '..d)
api.nvim_command("hi def link NvimTree" .. k .. " " .. d)
end
end

View File

@ -1,6 +1,6 @@
local a = vim.api
local utils = require'nvim-tree.utils'
local view = require'nvim-tree.view'
local utils = require "nvim-tree.utils"
local view = require "nvim-tree.view"
local M = {}
@ -26,9 +26,11 @@ local signs = {}
local function add_sign(linenr, severity)
local buf = view.get_bufnr()
if not a.nvim_buf_is_valid(buf) or not a.nvim_buf_is_loaded(buf) then return end
if not a.nvim_buf_is_valid(buf) or not a.nvim_buf_is_loaded(buf) then
return
end
local sign_name = sign_names[severity][1]
table.insert(signs, vim.fn.sign_place(1, 'NvimTreeDiagnosticSigns', sign_name, buf, { lnum = linenr+1 }))
table.insert(signs, vim.fn.sign_place(1, "NvimTreeDiagnosticSigns", sign_name, buf, { lnum = linenr + 1 }))
end
local function from_nvim_lsp()
@ -69,8 +71,8 @@ local function from_coc()
return {}
end
local diagnostic_list = vim.fn.CocAction("diagnosticList")
if type(diagnostic_list) ~='table' or vim.tbl_isempty(diagnostic_list) then
local diagnostic_list = vim.fn.CocAction "diagnosticList"
if type(diagnostic_list) ~= "table" or vim.tbl_isempty(diagnostic_list) then
return {}
end
@ -116,7 +118,7 @@ function M.update()
return {
buffer = view.get_bufnr(),
group = "NvimTreeDiagnosticSigns",
id = sign
id = sign,
}
end, signs))
signs = {}
@ -130,12 +132,14 @@ function M.update()
return node.absolute_path == bufname
end
end)
if node then add_sign(line, severity) end
if node then
add_sign(line, severity)
end
end
end
end
local has_06 = vim.fn.has('nvim-0.6') == 1
local has_06 = vim.fn.has "nvim-0.6" == 1
local links = {
NvimTreeLspDiagnosticsError = has_06 and "DiagnosticError" or "LspDiagnosticsDefaultError",
NvimTreeLspDiagnosticsWarning = has_06 and "DiagnosticWarn" or "LspDiagnosticsDefaultWarning",

View File

@ -3,12 +3,12 @@ local M = {}
local global_handlers = {}
local Event = {
Ready = 'Ready',
NodeRenamed = 'NodeRenamed',
FileCreated = 'FileCreated',
FileRemoved = 'FileRemoved',
FolderCreated = 'FolderCreated',
FolderRemoved = 'FolderRemoved',
Ready = "Ready",
NodeRenamed = "NodeRenamed",
FileCreated = "FileCreated",
FileRemoved = "FileRemoved",
FolderCreated = "FolderCreated",
FolderRemoved = "FolderRemoved",
}
local function get_handlers(event_name)
@ -21,12 +21,11 @@ local function register_handler(event_name, handler)
global_handlers[event_name] = handlers
end
local function dispatch(event_name, payload)
for _, handler in pairs(get_handlers(event_name)) do
local success, error = pcall(handler, payload)
if not success then
vim.api.nvim_err_writeln('Handler for event ' .. event_name .. ' errored. ' .. vim.inspect(error))
vim.api.nvim_err_writeln("Handler for event " .. event_name .. " errored. " .. vim.inspect(error))
end
end
end

View File

@ -3,9 +3,7 @@ local uv = vim.loop
local M = {}
function M.has_one_child_folder(node)
return #node.nodes == 1
and node.nodes[1].nodes
and uv.fs_access(node.nodes[1].absolute_path, 'R')
return #node.nodes == 1 and node.nodes[1].nodes and uv.fs_access(node.nodes[1].absolute_path, "R")
end
return M

View File

@ -1,9 +1,9 @@
local api = vim.api
local uv = vim.loop
local utils = require'nvim-tree.utils'
local builders = require'nvim-tree.explorer.node-builders'
local common = require'nvim-tree.explorer.common'
local utils = require "nvim-tree.utils"
local builders = require "nvim-tree.explorer.node-builders"
local common = require "nvim-tree.explorer.common"
local sorters = require "nvim-tree.explorer.sorters"
local filters = require "nvim-tree.explorer.filters"
@ -14,19 +14,21 @@ local function get_type_from(type_, cwd)
end
local function populate_children(handle, cwd, node, status)
local node_ignored = node.git_status == '!!'
local node_ignored = node.git_status == "!!"
while true do
local name, t = uv.fs_scandir_next(handle)
if not name then break end
if not name then
break
end
local abs = utils.path_join({cwd, name})
local abs = utils.path_join { cwd, name }
t = get_type_from(t, abs)
if not filters.should_ignore(abs) and not filters.should_ignore_git(abs, status.files) then
if t == 'directory' and uv.fs_access(abs, 'R') then
if t == "directory" and uv.fs_access(abs, "R") then
table.insert(node.nodes, builders.folder(abs, name, status, node_ignored))
elseif t == 'file' then
elseif t == "file" then
table.insert(node.nodes, builders.file(abs, name, status, node_ignored))
elseif t == 'link' then
elseif t == "link" then
local link = builders.link(abs, name, status, node_ignored)
if link.link_to ~= nil then
table.insert(node.nodes, link)
@ -38,7 +40,7 @@ end
local function get_dir_handle(cwd)
local handle = uv.fs_scandir(cwd)
if type(handle) == 'string' then
if type(handle) == "string" then
api.nvim_err_writeln(handle)
return
end
@ -48,7 +50,9 @@ end
function M.explore(node, status)
local cwd = node.cwd or node.link_to or node.absolute_path
local handle = get_dir_handle(cwd)
if not handle then return end
if not handle then
return
end
populate_children(handle, cwd, node, status)

View File

@ -1,4 +1,4 @@
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local M = {
ignore_list = {},
@ -25,7 +25,7 @@ function M.should_ignore(path)
end
if M.config.filter_dotfiles then
if basename:sub(1, 1) == '.' then
if basename:sub(1, 1) == "." then
return true
end
end
@ -39,9 +39,9 @@ function M.should_ignore(path)
return true
end
local idx = path:match(".+()%.[^.]+$")
local idx = path:match ".+()%.[^.]+$"
if idx then
if M.ignore_list['*'..string.sub(path, idx)] == true then
if M.ignore_list["*" .. string.sub(path, idx)] == true then
return true
end
end
@ -51,7 +51,7 @@ end
function M.should_ignore_git(path, status)
return M.config.filter_ignored
and (M.config.filter_git_ignored and status and status[path] == '!!')
and (M.config.filter_git_ignored and status and status[path] == "!!")
and not is_excluded(path)
end

View File

@ -4,8 +4,8 @@ local git = require"nvim-tree.git"
local M = {}
M.explore = require"nvim-tree.explorer.explore".explore
M.reload = require"nvim-tree.explorer.reload".reload
M.explore = require("nvim-tree.explorer.explore").explore
M.reload = require("nvim-tree.explorer.reload").reload
local Explorer = {}
Explorer.__index = Explorer
@ -14,7 +14,7 @@ function Explorer.new(cwd)
cwd = uv.fs_realpath(cwd or uv.cwd())
local explorer = setmetatable({
cwd = cwd,
nodes = {}
nodes = {},
}, Explorer)
explorer:_load(explorer)
return explorer
@ -31,8 +31,8 @@ function Explorer:expand(node)
end
function M.setup(opts)
require"nvim-tree.explorer.filters".setup(opts)
require"nvim-tree.explorer.sorters".setup(opts)
require("nvim-tree.explorer.filters").setup(opts)
require("nvim-tree.explorer.sorters").setup(opts)
end
M.Explorer = Explorer

View File

@ -1,13 +1,13 @@
local uv = vim.loop
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local M = {
is_windows = vim.fn.has('win32') == 1
is_windows = vim.fn.has "win32" == 1,
}
function M.get_dir_git_status(parent_ignored, status, absolute_path)
if parent_ignored then
return '!!'
return "!!"
end
local dir_status = status.dirs and status.dirs[absolute_path]
local file_status = status.files and status.files[absolute_path]
@ -15,7 +15,7 @@ function M.get_dir_git_status(parent_ignored, status, absolute_path)
end
function M.get_git_status(parent_ignored, status, absolute_path)
return parent_ignored and '!!' or status.files and status.files[absolute_path]
return parent_ignored and "!!" or status.files and status.files[absolute_path]
end
function M.folder(absolute_path, name, status, parent_ignored)
@ -38,7 +38,7 @@ local function is_executable(absolute_path, ext)
if M.is_windows then
return utils.is_windows_exe(ext)
end
return uv.fs_access(absolute_path, 'X')
return uv.fs_access(absolute_path, "X")
end
function M.file(absolute_path, name, status, parent_ignored)
@ -63,7 +63,7 @@ function M.link(absolute_path, name, status, parent_ignored)
--- I dont know if this is needed, because in my understanding, there isnt hard links in windows, but just to be sure i changed it.
local link_to = uv.fs_realpath(absolute_path)
local open, nodes
if (link_to ~= nil) and uv.fs_stat(link_to).type == 'directory' then
if (link_to ~= nil) and uv.fs_stat(link_to).type == "directory" then
open = false
nodes = {}
end

View File

@ -1,11 +1,11 @@
local api = vim.api
local uv = vim.loop
local utils = require'nvim-tree.utils'
local builders = require'nvim-tree.explorer.node-builders'
local common = require'nvim-tree.explorer.common'
local filters = require'nvim-tree.explorer.filters'
local sorters = require'nvim-tree.explorer.sorters'
local utils = require "nvim-tree.utils"
local builders = require "nvim-tree.explorer.node-builders"
local common = require "nvim-tree.explorer.common"
local filters = require "nvim-tree.explorer.filters"
local sorters = require "nvim-tree.explorer.sorters"
local M = {}
@ -33,7 +33,7 @@ end
function M.reload(node, status)
local cwd = node.cwd or node.link_to or node.absolute_path
local handle = uv.fs_scandir(cwd)
if type(handle) == 'string' then
if type(handle) == "string" then
api.nvim_err_writeln(handle)
return
end
@ -45,22 +45,24 @@ function M.reload(node, status)
local child_names = {}
local node_ignored = node.git_status == '!!'
local node_ignored = node.git_status == "!!"
local nodes_by_path = key_by(node.nodes, "absolute_path")
while true do
local name, t = uv.fs_scandir_next(handle)
if not name then break end
if not name then
break
end
local abs = utils.path_join({cwd, name})
local abs = utils.path_join { cwd, name }
t = t or (uv.fs_stat(abs) or {}).type
if not filters.should_ignore(abs) and not filters.should_ignore_git(abs, status.files) then
child_names[abs] = true
if not nodes_by_path[abs] then
if t == 'directory' and uv.fs_access(abs, 'R') then
if t == "directory" and uv.fs_access(abs, "R") then
table.insert(node.nodes, builders.folder(abs, name, status, node_ignored))
elseif t == 'file' then
elseif t == "file" then
table.insert(node.nodes, builders.file(abs, name, status, node_ignored))
elseif t == 'link' then
elseif t == "link" then
local link = builders.link(abs, name, status, node_ignored)
if link.link_to ~= nil then
table.insert(node.nodes, link)
@ -72,10 +74,10 @@ function M.reload(node, status)
node.nodes = vim.tbl_map(
update_status(nodes_by_path, node_ignored, status),
vim.tbl_filter(
function(n) return child_names[n.absolute_path] end,
node.nodes
))
vim.tbl_filter(function(n)
return child_names[n.absolute_path]
end, node.nodes)
)
local is_root = node.cwd ~= nil
local child_folder_only = common.has_one_child_folder(node) and node.nodes[1]

View File

@ -26,7 +26,7 @@ local function merge(t, first, mid, last, comparator)
local j = 1
local k = first
while (i <= n1 and j <= n2) do
while i <= n1 and j <= n2 do
if comparator(ls[i], rs[j]) then
t[k] = ls[i]
i = i + 1
@ -51,7 +51,9 @@ local function merge(t, first, mid, last, comparator)
end
local function split_merge(t, first, last, comparator)
if (last - first) < 1 then return end
if (last - first) < 1 then
return
end
local mid = math.floor((first + last) / 2)

View File

@ -1,10 +1,10 @@
local git_utils = require'nvim-tree.git.utils'
local Runner = require'nvim-tree.git.runner'
local git_utils = require "nvim-tree.git.utils"
local Runner = require "nvim-tree.git.runner"
local M = {
config = nil,
projects = {},
cwd_to_project_root = {}
cwd_to_project_root = {},
}
function M.reload()
@ -22,7 +22,7 @@ function M.reload()
}
M.projects[project_root] = {
files = git_status,
dirs = git_utils.file_status_to_dir_status(git_status, project_root)
dirs = git_utils.file_status_to_dir_status(git_status, project_root),
}
end
@ -62,11 +62,11 @@ function M.load_project_status(cwd)
project_root = project_root,
list_untracked = git_utils.should_show_untracked(project_root),
list_ignored = true,
timeout = M.config.timeout
timeout = M.config.timeout,
}
M.projects[project_root] = {
files = git_status,
dirs = git_utils.file_status_to_dir_status(git_status, project_root)
dirs = git_utils.file_status_to_dir_status(git_status, project_root),
}
return M.projects[project_root]
end

View File

@ -1,5 +1,5 @@
local uv = vim.loop
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local Runner = {}
Runner.__index = Runner
@ -7,22 +7,22 @@ Runner.__index = Runner
function Runner:_parse_status_output(line)
local status = line:sub(1, 2)
-- removing `"` when git is returning special file status containing spaces
local path = line:sub(4, -2):gsub('^"', ''):gsub('"$', '')
local path = line:sub(4, -2):gsub('^"', ""):gsub('"$', "")
-- replacing slashes if on windows
if vim.fn.has('win32') == 1 then
path = path:gsub('/', '\\')
if vim.fn.has "win32" == 1 then
path = path:gsub("/", "\\")
end
if #status > 0 and #path > 0 then
self.output[utils.path_remove_trailing(utils.path_join({self.project_root,path}))] = status
self.output[utils.path_remove_trailing(utils.path_join { self.project_root, path })] = status
end
return #line
end
function Runner:_handle_incoming_data(prev_output, incoming)
if incoming and utils.str_find(incoming, '\n') then
if incoming and utils.str_find(incoming, "\n") then
local prev = prev_output .. incoming
local i = 1
for line in prev:gmatch('[^\n]*\n') do
for line in prev:gmatch "[^\n]*\n" do
i = i + self:_parse_status_output(line)
end
@ -33,7 +33,7 @@ function Runner:_handle_incoming_data(prev_output, incoming)
return prev_output .. incoming
end
for line in prev_output:gmatch('[^\n]*\n') do
for line in prev_output:gmatch "[^\n]*\n" do
self._parse_status_output(line)
end
@ -41,8 +41,8 @@ function Runner:_handle_incoming_data(prev_output, incoming)
end
function Runner:_getopts(stdout_handle)
local untracked = self.list_untracked and '-u' or nil
local ignored = (self.list_untracked and self.list_ignored) and '--ignored=matching' or '--ignored=no'
local untracked = self.list_untracked and "-u" or nil
local ignored = (self.list_untracked and self.list_ignored) and "--ignored=matching" or "--ignored=no"
return {
args = { "--no-optional-locks", "status", "--porcelain=v1", ignored, untracked },
cwd = self.project_root,
@ -74,14 +74,24 @@ function Runner:_run_git_job()
handle, pid = uv.spawn(
"git",
self:_getopts(stdout),
vim.schedule_wrap(function() on_finish() end)
vim.schedule_wrap(function()
on_finish()
end)
)
timer:start(self.timeout, 0, vim.schedule_wrap(function() on_finish() end))
timer:start(
self.timeout,
0,
vim.schedule_wrap(function()
on_finish()
end)
)
local output_leftover = ''
local output_leftover = ""
local function manage_output(err, data)
if err then return end
if err then
return
end
output_leftover = self:_handle_incoming_data(output_leftover, data)
end
@ -89,7 +99,10 @@ function Runner:_run_git_job()
end
function Runner:_wait()
while not vim.wait(30, function() return self._done end, 30) do end
while not vim.wait(30, function()
return self._done
end, 30) do
end
end
-- This module runs a git process, which will be killed if it takes more than timeout which defaults to 400ms
@ -100,7 +113,7 @@ function Runner.run(opts)
list_ignored = opts.list_ignored,
timeout = opts.timeout or 400,
output = {},
_done = false
_done = false,
}, Runner)
self:_run_git_job()

View File

@ -4,12 +4,12 @@ function M.get_toplevel(cwd)
local cmd = "git -C " .. vim.fn.shellescape(cwd) .. " rev-parse --show-toplevel"
local toplevel = vim.fn.system(cmd)
if not toplevel or #toplevel == 0 or toplevel:match('fatal') then
if not toplevel or #toplevel == 0 or toplevel:match "fatal" then
return nil
end
-- git always returns path with forward slashes
if vim.fn.has('win32') == 1 then
if vim.fn.has "win32" == 1 then
toplevel = toplevel:gsub("/", "\\")
end
@ -26,23 +26,23 @@ function M.should_show_untracked(cwd)
local cmd = "git -C " .. cwd .. " config --type=bool status.showUntrackedFiles"
local has_untracked = vim.fn.system(cmd)
untracked[cwd] = vim.trim(has_untracked) ~= 'false'
untracked[cwd] = vim.trim(has_untracked) ~= "false"
return untracked[cwd]
end
function M.file_status_to_dir_status(status, cwd)
local dirs = {}
for p, s in pairs(status) do
if s ~= '!!' then
local modified = vim.fn.fnamemodify(p, ':h')
if s ~= "!!" then
local modified = vim.fn.fnamemodify(p, ":h")
dirs[modified] = s
end
end
for dirname, s in pairs(dirs) do
local modified = dirname
while modified ~= cwd and modified ~= '/' do
modified = vim.fn.fnamemodify(modified, ':h')
while modified ~= cwd and modified ~= "/" do
modified = vim.fn.fnamemodify(modified, ":h")
dirs[modified] = s
end
end
@ -51,4 +51,3 @@ function M.file_status_to_dir_status(status, cwd)
end
return M

View File

@ -1,4 +1,4 @@
local utils = require'nvim-tree.utils'
local utils = require "nvim-tree.utils"
local M = {}
@ -181,16 +181,15 @@ function M.migrate_legacy_options(opts)
local msg = nil
for g, m in pairs(migrations) do
if vim.fn.exists('g:'..g) ~= 0 then
if vim.fn.exists("g:" .. g) ~= 0 then
m(opts)
msg = (msg and msg .. ", " or "Following options were moved to setup, see git.io/JPhyt: ") .. g
end
end
if msg then
require'nvim-tree.utils'.warn(msg)
require("nvim-tree.utils").warn(msg)
end
end
return M

View File

@ -1,10 +1,10 @@
local api = vim.api
local renderer = require'nvim-tree.renderer'
local diagnostics = require'nvim-tree.diagnostics'
local explorer = require'nvim-tree.explorer'
local view = require'nvim-tree.view'
local events = require'nvim-tree.events'
local renderer = require "nvim-tree.renderer"
local diagnostics = require "nvim-tree.diagnostics"
local explorer = require "nvim-tree.explorer"
local view = require "nvim-tree.view"
local events = require "nvim-tree.events"
local first_init_done = false
@ -42,7 +42,9 @@ function M.get_nodes_by_line(nodes_all, line_start)
end
function M.get_node_at_cursor()
if not TreeExplorer then return end
if not TreeExplorer then
return
end
local winnr = view.get_winnr()
local hide_root_folder = view.View.hide_root_folder
if not winnr then
@ -51,7 +53,7 @@ function M.get_node_at_cursor()
local cursor = api.nvim_win_get_cursor(view.get_winnr())
local line = cursor[1]
if view.is_help_ui() then
local help_lines = require'nvim-tree.renderer.help'.compute_lines()
local help_lines = require("nvim-tree.renderer.help").compute_lines()
local help_text = M.get_nodes_by_line(help_lines, 1)[line]
return { name = help_text }
else
@ -103,7 +105,7 @@ end
local function handle_buf_cwd(cwd)
local respect_buf_cwd = vim.g.nvim_tree_respect_buf_cwd or 0
if respect_buf_cwd == 1 and cwd ~= TreeExplorer.cwd then
require'nvim-tree.actions.change-dir'.fn(cwd)
require("nvim-tree.actions.change-dir").fn(cwd)
end
end
@ -120,13 +122,8 @@ local function should_hijack_current_buf()
local bufmodified = api.nvim_buf_get_option(bufnr, "modified")
local ft = api.nvim_buf_get_option(bufnr, "ft")
local should_hijack_unnamed = M.hijack_unnamed_buffer_when_opening
and bufname == ""
and not bufmodified
and ft == ""
local should_hijack_dir = bufname ~= ""
and vim.fn.isdirectory(bufname) == 1
and M.hijack_directories.enable
local should_hijack_unnamed = M.hijack_unnamed_buffer_when_opening and bufname == "" and not bufmodified and ft == ""
local should_hijack_dir = bufname ~= "" and vim.fn.isdirectory(bufname) == 1 and M.hijack_directories.enable
return should_hijack_dir or should_hijack_unnamed
end
@ -145,17 +142,17 @@ function M.open(cwd)
end
-- @deprecated: use nvim-tree.actions.collapse-all.fn
M.collapse_all = require'nvim-tree.actions.collapse-all'.fn
M.collapse_all = require("nvim-tree.actions.collapse-all").fn
-- @deprecated: use nvim-tree.actions.dir-up.fn
M.dir_up = require'nvim-tree.actions.dir-up'.fn
M.dir_up = require("nvim-tree.actions.dir-up").fn
-- @deprecated: use nvim-tree.actions.change-dir.fn
M.change_dir = require'nvim-tree.actions.change-dir'.fn
M.change_dir = require("nvim-tree.actions.change-dir").fn
-- @deprecated: use nvim-tree.actions.reloaders.reload_explorer
M.refresh_tree = require'nvim-tree.actions.reloaders'.reload_explorer
M.refresh_tree = require("nvim-tree.actions.reloaders").reload_explorer
-- @deprecated: use nvim-tree.actions.reloaders.reload_git
M.reload_git = require'nvim-tree.actions.reloaders'.reload_git
M.reload_git = require("nvim-tree.actions.reloaders").reload_git
-- @deprecated: use nvim-tree.actions.find-file.fn
M.set_index_and_redraw = require'nvim-tree.actions.find-file'.fn
M.set_index_and_redraw = require("nvim-tree.actions.find-file").fn
function M.setup(opts)
M.hijack_unnamed_buffer_when_opening = opts.hijack_unnamed_buffer_when_opening

View File

@ -1,19 +1,19 @@
local M = {}
function M.compute_lines()
local help_lines = {'HELP'}
local help_hl = {{'NvimTreeRootFolder', 0, 0, #help_lines[1]}}
local help_lines = { "HELP" }
local help_hl = { { "NvimTreeRootFolder", 0, 0, #help_lines[1] } }
local mappings = vim.tbl_filter(function(v)
return (v.cb ~= nil and v.cb ~= "") or (v.action ~= nil and v.action ~= "")
end, require'nvim-tree.actions'.mappings)
end, require("nvim-tree.actions").mappings)
local processed = {}
for _, b in pairs(mappings) do
local cb = b.cb
local key = b.key
local name
if cb and cb:sub(1,35) == require'nvim-tree.config'.nvim_tree_callback('test'):sub(1,35) then
name = cb:match("'[^']+'[^']*$")
name = name:match("'[^']+'")
if cb and cb:sub(1, 35) == require("nvim-tree.config").nvim_tree_callback("test"):sub(1, 35) then
name = cb:match "'[^']+'[^']*$"
name = name:match "'[^']+'"
elseif b.action then
name = b.action
else
@ -23,9 +23,7 @@ function M.compute_lines()
table.insert(processed, { key, name, true })
end
table.sort(processed, function(a, b)
return (a[3] == b[3]
and (a[2] < b[2] or (a[2] == b[2] and #a[1] < #b[1])))
or (a[3] and not b[3])
return (a[3] == b[3] and (a[2] < b[2] or (a[2] == b[2] and #a[1] < #b[1]))) or (a[3] and not b[3])
end)
local num = 0
@ -39,10 +37,10 @@ function M.compute_lines()
table.insert(help_lines, bind_string)
local hl_len = math.max(6, string.len(key)) + 2
table.insert(help_hl, {'NvimTreeFolderName', num, 0, hl_len})
table.insert(help_hl, { "NvimTreeFolderName", num, 0, hl_len })
if not builtin then
table.insert(help_hl, {'NvimTreeFileRenamed', num, hl_len, -1})
table.insert(help_hl, { "NvimTreeFileRenamed", num, hl_len, -1 })
end
end
end

View File

@ -12,7 +12,7 @@ function M.get_config()
renamed = "",
untracked = "",
deleted = "",
ignored = ""
ignored = "",
},
folder_icons = {
arrow_closed = "",
@ -47,14 +47,14 @@ function M.get_config()
end
end
local has_devicons = pcall(require, 'nvim-web-devicons')
local has_devicons = pcall(require, "nvim-web-devicons")
return {
show_file_icon = show_icons.files == 1,
show_folder_icon = show_icons.folders == 1,
show_git_icon = show_icons.git == 1,
show_folder_arrows = show_icons.folder_arrows == 1,
has_devicons = has_devicons,
icons = icons
icons = icons,
}
end

View File

@ -1,21 +1,23 @@
local utils = require'nvim-tree.utils'
local view = require'nvim-tree.view'
local _padding = require'nvim-tree.renderer.padding'
local _help = require'nvim-tree.renderer.help'
local _icons = require'nvim-tree.renderer.icons'
local utils = require "nvim-tree.utils"
local view = require "nvim-tree.view"
local _padding = require "nvim-tree.renderer.padding"
local _help = require "nvim-tree.renderer.help"
local _icons = require "nvim-tree.renderer.icons"
local api = vim.api
local lines = {}
local hl = {}
local index = 0
local namespace_id = api.nvim_create_namespace('NvimTreeHighlights')
local namespace_id = api.nvim_create_namespace "NvimTreeHighlights"
local icon_state = _icons.get_config()
local should_hl_opened_files = (vim.g.nvim_tree_highlight_opened_files or 0) ~= 0
local get_folder_icon = function() return "" end
local get_folder_icon = function()
return ""
end
local function get_trailing_length()
return vim.g.nvim_tree_add_trailing and 1 or 0
end
@ -50,15 +52,17 @@ if icon_state.show_folder_icon then
end
set_folder_hl = function(line, depth, icon_len, name_len, hl_group)
table.insert(hl, { hl_group, line, depth + icon_len, depth + icon_len + name_len + get_trailing_length() })
local hl_icon = (vim.g.nvim_tree_highlight_opened_files or 0) ~= 0 and hl_group or 'NvimTreeFolderIcon'
local hl_icon = (vim.g.nvim_tree_highlight_opened_files or 0) ~= 0 and hl_group or "NvimTreeFolderIcon"
table.insert(hl, { hl_icon, line, depth, depth + icon_len })
end
end
local get_file_icon = function() return "" end
local get_file_icon = function()
return ""
end
if icon_state.show_file_icon then
if icon_state.has_devicons then
local web_devicons = require'nvim-web-devicons'
local web_devicons = require "nvim-web-devicons"
get_file_icon = function(fname, extension, line, depth)
local icon, hl_group = web_devicons.get_icon(fname, extension)
@ -82,21 +86,27 @@ if icon_state.show_file_icon then
end
end
local get_symlink_icon = function() return icon_state.icons.symlink end
local get_symlink_icon = function()
return icon_state.icons.symlink
end
if icon_state.show_file_icon then
get_symlink_icon = function()
return #icon_state.icons.symlink > 0 and icon_state.icons.symlink .. icon_padding or ""
end
end
local get_special_icon = function() return "" end
local get_special_icon = function()
return ""
end
if icon_state.show_file_icon then
get_special_icon = function()
return #icon_state.icons.default > 0 and icon_state.icons.default .. icon_padding or ""
end
end
local get_git_icons = function() return "" end
local get_git_icons = function()
return ""
end
local get_git_hl = function() end
if vim.g.nvim_tree_git_hl == 1 then
@ -109,11 +119,11 @@ if vim.g.nvim_tree_git_hl == 1 then
[" T"] = { { hl = "NvimTreeFileDirty" } },
["MM"] = {
{ hl = "NvimTreeFileStaged" },
{ hl = "NvimTreeFileDirty" }
{ hl = "NvimTreeFileDirty" },
},
["A "] = {
{ hl = "NvimTreeFileStaged" },
{ hl = "NvimTreeFileNew" }
{ hl = "NvimTreeFileNew" },
},
["AU"] = {
{ hl = "NvimTreeFileMerge" },
@ -122,7 +132,7 @@ if vim.g.nvim_tree_git_hl == 1 then
-- not sure about this one
["AA"] = {
{ hl = "NvimTreeFileMerge" },
{ hl = "NvimTreeFileStaged" }
{ hl = "NvimTreeFileStaged" },
},
["AD"] = {
{ hl = "NvimTreeFileStaged" },
@ -133,7 +143,7 @@ if vim.g.nvim_tree_git_hl == 1 then
["AM"] = {
{ hl = "NvimTreeFileStaged" },
{ hl = "NvimTreeFileNew" },
{ hl = "NvimTreeFileDirty" }
{ hl = "NvimTreeFileDirty" },
},
["??"] = { { hl = "NvimTreeFileNew" } },
["R "] = { { hl = "NvimTreeFileRenamed" } },
@ -145,11 +155,11 @@ if vim.g.nvim_tree_git_hl == 1 then
["RD"] = { { hl = "NvimTreeFileDeleted" } },
["D "] = {
{ hl = "NvimTreeFileDeleted" },
{ hl = "NvimTreeFileStaged" }
{ hl = "NvimTreeFileStaged" },
},
["DU"] = {
{ hl = "NvimTreeFileDeleted" },
{ hl = "NvimTreeFileMerge" }
{ hl = "NvimTreeFileMerge" },
},
[" A"] = { { hl = "none" } },
["RM"] = { { hl = "NvimTreeFileRenamed" } },
@ -159,12 +169,18 @@ if vim.g.nvim_tree_git_hl == 1 then
}
get_git_hl = function(node)
local git_status = node.git_status
if not git_status then return end
if not git_status then
return
end
local icons = git_hl[git_status]
if icons == nil then
utils.warn('Unrecognized git state "'..git_status..'". Please open up an issue on https://github.com/kyazdani42/nvim-tree.lua/issues with this message.')
utils.warn(
'Unrecognized git state "'
.. git_status
.. '". Please open up an issue on https://github.com/kyazdani42/nvim-tree.lua/issues with this message.'
)
icons = git_hl.dirty
end
@ -184,7 +200,7 @@ if icon_state.show_git_icon then
[" T"] = { { icon = icon_state.icons.git_icons.unstaged, hl = "NvimTreeGitDirty" } },
["MM"] = {
{ icon = icon_state.icons.git_icons.staged, hl = "NvimTreeGitStaged" },
{ icon = icon_state.icons.git_icons.unstaged, hl = "NvimTreeGitDirty" }
{ icon = icon_state.icons.git_icons.unstaged, hl = "NvimTreeGitDirty" },
},
["MD"] = {
{ icon = icon_state.icons.git_icons.staged, hl = "NvimTreeGitStaged" },
@ -209,7 +225,7 @@ if icon_state.show_git_icon then
},
["AM"] = {
{ icon = icon_state.icons.git_icons.staged, hl = "NvimTreeGitStaged" },
{ icon = icon_state.icons.git_icons.unstaged, hl = "NvimTreeGitDirty" }
{ icon = icon_state.icons.git_icons.unstaged, hl = "NvimTreeGitDirty" },
},
["??"] = { { icon = icon_state.icons.git_icons.untracked, hl = "NvimTreeGitNew" } },
["R "] = { { icon = icon_state.icons.git_icons.renamed, hl = "NvimTreeGitRenamed" } },
@ -235,13 +251,19 @@ if icon_state.show_git_icon then
get_git_icons = function(node, line, depth, icon_len)
local git_status = node.git_status
if not git_status then return "" end
if not git_status then
return ""
end
local icon = ""
local icons = git_icon_state[git_status]
if not icons then
if vim.g.nvim_tree_git_hl ~= 1 then
utils.warn('Unrecognized git state "'..git_status..'". Please open up an issue on https://github.com/kyazdani42/nvim-tree.lua/issues with this message.')
utils.warn(
'Unrecognized git state "'
.. git_status
.. '". Please open up an issue on https://github.com/kyazdani42/nvim-tree.lua/issues with this message.'
)
end
icons = git_icon_state.dirty
end
@ -264,8 +286,9 @@ local picture = {
}
local function update_draw_data(tree, depth, markers)
local root_folder_modifier = vim.g.nvim_tree_root_folder_modifier or ':~'
local special = vim.g.nvim_tree_special_files or {
local root_folder_modifier = vim.g.nvim_tree_root_folder_modifier or ":~"
local special = vim.g.nvim_tree_special_files
or {
["Cargo.toml"] = true,
Makefile = true,
["README.md"] = true,
@ -274,13 +297,13 @@ local function update_draw_data(tree, depth, markers)
local hide_root_folder = view.View.hide_root_folder
if tree.cwd and tree.cwd ~= '/' and not hide_root_folder then
local root_name = utils.path_join({
if tree.cwd and tree.cwd ~= "/" and not hide_root_folder then
local root_name = utils.path_join {
utils.path_remove_trailing(vim.fn.fnamemodify(tree.cwd, root_folder_modifier)),
".."
})
"..",
}
table.insert(lines, root_name)
table.insert(hl, {'NvimTreeRootFolder', index, 0, string.len(root_name)})
table.insert(hl, { "NvimTreeRootFolder", index, 0, string.len(root_name) })
index = 1
end
@ -288,7 +311,7 @@ local function update_draw_data(tree, depth, markers)
local padding = _padding.get_padding(depth, idx, tree, node, markers)
local offset = string.len(padding)
if depth > 0 then
table.insert(hl, { 'NvimTreeIndentMarker', index, 0, offset })
table.insert(hl, { "NvimTreeIndentMarker", index, 0, offset })
end
local git_hl = get_git_hl(node)
@ -305,8 +328,12 @@ local function update_draw_data(tree, depth, markers)
name = name .. "/" .. next.name
next = next.group_next
end
if not has_children then folder_hl = "NvimTreeEmptyFolderName" end
if node.open then folder_hl = "NvimTreeOpenedFolderName" end
if not has_children then
folder_hl = "NvimTreeEmptyFolderName"
end
if node.open then
folder_hl = "NvimTreeOpenedFolderName"
end
if special[node.absolute_path] then
folder_hl = "NvimTreeSpecialFolderName"
end
@ -316,26 +343,25 @@ local function update_draw_data(tree, depth, markers)
end
index = index + 1
if node.open then
table.insert(lines, padding..icon..git_icon..name..(vim.g.nvim_tree_add_trailing == 1 and '/' or ''))
table.insert(lines, padding .. icon .. git_icon .. name .. (vim.g.nvim_tree_add_trailing == 1 and "/" or ""))
update_draw_data(node, depth + 2, markers)
else
table.insert(lines, padding..icon..git_icon..name..(vim.g.nvim_tree_add_trailing == 1 and '/' or ''))
table.insert(lines, padding .. icon .. git_icon .. name .. (vim.g.nvim_tree_add_trailing == 1 and "/" or ""))
end
elseif node.link_to then
local icon = get_symlink_icon()
local link_hl = git_hl or 'NvimTreeSymlink'
local arrow = vim.g.nvim_tree_symlink_arrow or ''
local link_hl = git_hl or "NvimTreeSymlink"
local arrow = vim.g.nvim_tree_symlink_arrow or ""
table.insert(hl, { link_hl, index, offset, -1 })
table.insert(lines, padding .. icon .. node.name .. arrow .. node.link_to)
index = index + 1
else
local icon
local git_icons
if special[node.absolute_path] or special[node.name] then
icon = get_special_icon()
git_icons = get_git_icons(node, index, offset, 0)
table.insert(hl, {'NvimTreeSpecialFile', index, offset+#git_icons, -1})
table.insert(hl, { "NvimTreeSpecialFile", index, offset + #git_icons, -1 })
else
icon = get_file_icon(node.name, node.extension, index, offset)
git_icons = get_git_icons(node, index, offset, #icon)
@ -343,19 +369,24 @@ local function update_draw_data(tree, depth, markers)
table.insert(lines, padding .. icon .. git_icons .. node.name)
if node.executable then
table.insert(hl, {'NvimTreeExecFile', index, offset+#icon+#git_icons, -1 })
table.insert(hl, { "NvimTreeExecFile", index, offset + #icon + #git_icons, -1 })
elseif picture[node.extension] then
table.insert(hl, {'NvimTreeImageFile', index, offset+#icon+#git_icons, -1 })
table.insert(hl, { "NvimTreeImageFile", index, offset + #icon + #git_icons, -1 })
end
if should_hl_opened_files then
if vim.fn.bufloaded(node.absolute_path) > 0 then
if vim.g.nvim_tree_highlight_opened_files == 1 then
table.insert(hl, {'NvimTreeOpenedFile', index, offset, offset+#icon }) -- highlight icon only
table.insert(hl, { "NvimTreeOpenedFile", index, offset, offset + #icon }) -- highlight icon only
elseif vim.g.nvim_tree_highlight_opened_files == 2 then
table.insert(hl, {'NvimTreeOpenedFile', index, offset+#icon+#git_icons, offset+#icon+#git_icons+#node.name }) -- highlight name only
table.insert(hl, {
"NvimTreeOpenedFile",
index,
offset + #icon + #git_icons,
offset + #icon + #git_icons + #node.name,
}) -- highlight name only
elseif vim.g.nvim_tree_highlight_opened_files == 3 then
table.insert(hl, {'NvimTreeOpenedFile', index, offset, -1 }) -- highlight whole line
table.insert(hl, { "NvimTreeOpenedFile", index, offset, -1 }) -- highlight whole line
end
end
end
@ -384,8 +415,7 @@ function M.draw()
hl = {}
icon_state = _icons.get_config()
local show_arrows =
vim.g.nvim_tree_indent_markers ~= 1
local show_arrows = vim.g.nvim_tree_indent_markers ~= 1
and icon_state.show_folder_icon
and icon_state.show_folder_arrows
_padding.reload_padding_function()
@ -394,10 +424,10 @@ function M.draw()
if view.is_help_ui() then
lines, hl = _help.compute_lines()
end
api.nvim_buf_set_option(bufnr, 'modifiable', true)
api.nvim_buf_set_option(bufnr, "modifiable", true)
api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
M.render_hl(bufnr)
api.nvim_buf_set_option(bufnr, 'modifiable', false)
api.nvim_buf_set_option(bufnr, "modifiable", false)
if cursor and #lines >= cursor[1] then
api.nvim_win_set_cursor(view.get_winnr(), cursor)
@ -405,7 +435,9 @@ function M.draw()
end
function M.render_hl(bufnr)
if not bufnr or not api.nvim_buf_is_loaded(bufnr) then return end
if not bufnr or not api.nvim_buf_is_loaded(bufnr) then
return
end
api.nvim_buf_clear_namespace(bufnr, namespace_id, 0, -1)
for _, data in ipairs(hl) do
api.nvim_buf_add_highlight(bufnr, namespace_id, data[1], data[2], data[3], data[4])

View File

@ -1,16 +1,16 @@
local M = {}
function M.get_padding(depth)
return string.rep(' ', depth)
return string.rep(" ", depth)
end
local function get_padding_arrows(icon_state)
return function(depth, _, _, node)
if node.nodes then
local icon = icon_state.icons.folder_icons[node.open and 'arrow_open' or 'arrow_closed']
return string.rep(' ', depth - 2)..icon..' '
local icon = icon_state.icons.folder_icons[node.open and "arrow_open" or "arrow_closed"]
return string.rep(" ", depth - 2) .. icon .. " "
end
return string.rep(' ', depth)
return string.rep(" ", depth)
end
end
@ -21,11 +21,11 @@ local function get_padding_indent_markers(depth, idx, tree, _, markers)
markers[rdepth] = idx ~= #tree.nodes
for i = 1, rdepth do
if idx == #tree.nodes and i == rdepth then
padding = padding..''
padding = padding .. ""
elseif markers[i] then
padding = padding..''
padding = padding .. ""
else
padding = padding..' '
padding = padding .. " "
end
end
end
@ -33,7 +33,7 @@ local function get_padding_indent_markers(depth, idx, tree, _, markers)
end
function M.reload_padding_function()
local icon_state = require'nvim-tree.renderer.icons'.get_config()
local icon_state = require("nvim-tree.renderer.icons").get_config()
if icon_state.show_folder_icon and icon_state.show_folder_arrows then
M.get_padding = get_padding_arrows(icon_state)

View File

@ -1,14 +1,14 @@
local has_notify, notify = pcall(require, 'notify')
local has_notify, notify = pcall(require, "notify")
local a = vim.api
local uv = vim.loop
local M = {}
M.is_windows = vim.fn.has("win32") == 1 or vim.fn.has("win32unix") == 1
M.is_windows = vim.fn.has "win32" == 1 or vim.fn.has "win32unix" == 1
function M.path_to_matching_str(path)
return path:gsub('(%-)', '(%%-)'):gsub('(%.)', '(%%.)'):gsub('(%_)', '(%%_)')
return path:gsub("(%-)", "(%%-)"):gsub("(%.)", "(%%.)"):gsub("(%_)", "(%%_)")
end
function M.warn(msg)
@ -27,12 +27,16 @@ end
function M.read_file(path)
local fd = uv.fs_open(path, "r", 438)
if not fd then return '' end
if not fd then
return ""
end
local stat = uv.fs_fstat(fd)
if not stat then return '' end
if not stat then
return ""
end
local data = uv.fs_read(fd, stat.size, 0)
uv.fs_close(fd)
return data or ''
return data or ""
end
local path_separator = package.config:sub(1, 1)
@ -41,7 +45,7 @@ function M.path_join(paths)
end
function M.path_split(path)
return path:gmatch('[^'..path_separator..']+'..path_separator..'?')
return path:gmatch("[^" .. path_separator .. "]+" .. path_separator .. "?")
end
---Get the basename of the given path.
@ -50,7 +54,9 @@ end
function M.path_basename(path)
path = M.path_remove_trailing(path)
local i = path:match("^.*()" .. path_separator)
if not i then return path end
if not i then
return path
end
return path:sub(i + 1, #path)
end
@ -72,14 +78,14 @@ function M.path_add_trailing(path)
end
function M.path_remove_trailing(path)
local p, _ = path:gsub(path_separator..'$', '')
local p, _ = path:gsub(path_separator .. "$", "")
return p
end
M.path_separator = path_separator
function M.clear_prompt()
vim.api.nvim_command('normal! :')
vim.api.nvim_command "normal! :"
end
function M.get_user_input_char()
@ -97,11 +103,15 @@ function M.find_node(_nodes, _fn)
local function iter(nodes, fn)
local i = 1
for _, node in ipairs(nodes) do
if fn(node) then return node, i end
if fn(node) then
return node, i
end
if node.open and #node.nodes > 0 then
local n, idx = iter(node.nodes, fn)
i = i + idx
if n then return n, i end
if n then
return n, i
end
else
i = i + 1
end
@ -109,15 +119,15 @@ function M.find_node(_nodes, _fn)
return nil, i
end
local node, i = iter(_nodes, _fn)
i = require'nvim-tree.view'.View.hide_root_folder and i - 1 or i
i = require("nvim-tree.view").View.hide_root_folder and i - 1 or i
return node, i
end
---Matching executable files in Windows.
---@param ext string
---@return boolean
local PATHEXT = vim.env.PATHEXT or ''
local wexe = vim.split(PATHEXT:gsub('%.', ''), ';')
local PATHEXT = vim.env.PATHEXT or ""
local wexe = vim.split(PATHEXT:gsub("%.", ""), ";")
local pathexts = {}
for _, v in pairs(wexe) do
pathexts[v] = true
@ -133,7 +143,9 @@ function M.rename_loaded_buffers(old_name, new_name)
if a.nvim_buf_get_name(buf) == old_name then
a.nvim_buf_set_name(buf, new_name)
-- to avoid the 'overwrite existing file' error message on write
vim.api.nvim_buf_call(buf, function() vim.cmd("silent! w!") end)
vim.api.nvim_buf_call(buf, function()
vim.cmd "silent! w!"
end)
end
end
end
@ -149,7 +161,7 @@ end
--- @param path string
--- @return string
function M.canonical_path(path)
if M.is_windows and path:match '^%a:' then
if M.is_windows and path:match "^%a:" then
return path:sub(1, 1):upper() .. path:sub(2)
end
return path
@ -176,7 +188,7 @@ function M.table_create_missing(tbl, sub)
end
function M.format_bytes(bytes)
local units = {'B', 'K', 'M', 'G', 'T'}
local units = { "B", "K", "M", "G", "T" }
bytes = math.max(bytes, 0)
local pow = math.floor((bytes and math.log(bytes) or 0) / math.log(1024))
@ -187,7 +199,7 @@ function M.format_bytes(bytes)
pow = pow + 1
return (units[pow] == nil) and (bytes .. 'B') or (value .. units[pow])
return (units[pow] == nil) and (bytes .. "B") or (value .. units[pow])
end
return M

View File

@ -13,23 +13,23 @@ M.View = {
winfixwidth = true,
winfixheight = true,
spell = false,
signcolumn = 'yes',
foldmethod = 'manual',
foldcolumn = '0',
signcolumn = "yes",
foldmethod = "manual",
foldcolumn = "0",
cursorcolumn = false,
cursorlineopt = "line",
colorcolumn = '0',
colorcolumn = "0",
wrap = false,
winhl = table.concat({
'EndOfBuffer:NvimTreeEndOfBuffer',
'Normal:NvimTreeNormal',
'CursorLine:NvimTreeCursorLine',
'VertSplit:NvimTreeVertSplit',
'StatusLine:NvimTreeStatusLine',
'StatusLineNC:NvimTreeStatuslineNC',
'SignColumn:NvimTreeSignColumn',
'NormalNC:NvimTreeNormalNC',
}, ',')
"EndOfBuffer:NvimTreeEndOfBuffer",
"Normal:NvimTreeNormal",
"CursorLine:NvimTreeCursorLine",
"VertSplit:NvimTreeVertSplit",
"StatusLine:NvimTreeStatusLine",
"StatusLineNC:NvimTreeStatuslineNC",
"SignColumn:NvimTreeSignColumn",
"NormalNC:NvimTreeNormalNC",
}, ","),
},
}
@ -37,10 +37,10 @@ local BUFNR_PER_TAB = {}
local LAST_FOCUSED_WIN = nil
local BUFFER_OPTIONS = {
swapfile = false,
buftype = 'nofile',
buftype = "nofile",
modifiable = false,
filetype = 'NvimTree',
bufhidden = 'wipe',
filetype = "NvimTree",
bufhidden = "wipe",
buflisted = false,
}
@ -55,7 +55,7 @@ end
local function wipe_rogue_buffer()
for _, bufnr in ipairs(a.nvim_list_bufs()) do
if not matches_bufnr(bufnr) and a.nvim_buf_get_name(bufnr):match("NvimTree") ~= nil then
if not matches_bufnr(bufnr) and a.nvim_buf_get_name(bufnr):match "NvimTree" ~= nil then
return pcall(a.nvim_buf_delete, bufnr, { force = true })
end
end
@ -66,17 +66,17 @@ local function create_buffer(bufnr)
local tab = a.nvim_get_current_tabpage()
BUFNR_PER_TAB[tab] = bufnr or a.nvim_create_buf(false, false)
a.nvim_buf_set_name(M.get_bufnr(), 'NvimTree_'..tab)
a.nvim_buf_set_name(M.get_bufnr(), "NvimTree_" .. tab)
for option, value in pairs(BUFFER_OPTIONS) do
vim.bo[M.get_bufnr()][option] = value
end
require'nvim-tree.actions'.apply_mappings(M.get_bufnr())
require("nvim-tree.actions").apply_mappings(M.get_bufnr())
end
local function get_size()
local width_or_height = M.is_vertical() and 'width' or 'height'
local width_or_height = M.is_vertical() and "width" or "height"
local size = M.View[width_or_height]
if type(size) == "number" then
return size
@ -89,27 +89,27 @@ local function get_size()
end
local move_tbl = {
left = 'H',
right = 'L',
bottom = 'J',
top = 'K',
left = "H",
right = "L",
bottom = "J",
top = "K",
}
-- TODO: remove this once they fix https://github.com/neovim/neovim/issues/14670
local function set_local(opt, value)
local cmd
if value == true then
cmd = string.format('setlocal %s', opt)
cmd = string.format("setlocal %s", opt)
elseif value == false then
cmd = string.format('setlocal no%s', opt)
cmd = string.format("setlocal no%s", opt)
else
cmd = string.format('setlocal %s=%s', opt, value)
cmd = string.format("setlocal %s=%s", opt, value)
end
vim.cmd(cmd)
end
local function open_window()
a.nvim_command("vsp")
a.nvim_command "vsp"
M.reposition_window()
local winnr = a.nvim_get_current_win()
local tabpage = a.nvim_get_current_tabpage()
@ -124,12 +124,9 @@ local function set_window_options_and_buffer()
end
local function get_existing_buffers()
return vim.tbl_filter(
function(buf)
return vim.tbl_filter(function(buf)
return a.nvim_buf_is_valid(buf) and vim.fn.buflisted(buf) == 1
end,
a.nvim_list_bufs()
)
end, a.nvim_list_bufs())
end
local function switch_buf_if_last_buf()
@ -143,7 +140,9 @@ local function switch_buf_if_last_buf()
end
function M.close()
if not M.is_visible() then return end
if not M.is_visible() then
return
end
switch_buf_if_last_buf()
local tree_win = M.get_winnr()
local current_win = a.nvim_get_current_win()
@ -171,7 +170,7 @@ function M.open(options)
local opts = options or { focus_tree = true }
if not opts.focus_tree then
vim.cmd("wincmd p")
vim.cmd "wincmd p"
end
end
@ -206,14 +205,14 @@ function M.resize(size)
end
if not M.View.preserve_window_proportions then
vim.cmd(":wincmd =")
vim.cmd ":wincmd ="
end
end
function M.reposition_window()
local move_to = move_tbl[M.View.side]
a.nvim_command("wincmd " .. move_to)
local resize_direction = M.is_vertical() and 'vertical ' or ''
local resize_direction = M.is_vertical() and "vertical " or ""
a.nvim_command(resize_direction .. "resize " .. get_size())
end
@ -256,7 +255,7 @@ function M.set_cursor(opts)
if M.is_visible() then
pcall(a.nvim_win_set_cursor, M.get_winnr(), opts)
-- patch until https://github.com/neovim/neovim/issues/17395 is fixed
require"nvim-tree.renderer".draw()
require("nvim-tree.renderer").draw()
end
end
@ -275,7 +274,7 @@ function M.focus(winnr, open_if_closed)
end
function M.is_vertical()
return M.View.side == 'left' or M.View.side == 'right'
return M.View.side == "left" or M.View.side == "right"
end
--- Returns the window number for nvim-tree within the tabpage specified
@ -326,7 +325,7 @@ function M._prevent_buffer_override()
local curwin = a.nvim_get_current_win()
local curbuf = a.nvim_win_get_buf(curwin)
local bufname = a.nvim_buf_get_name(curbuf)
if not bufname:match("NvimTree") then
if not bufname:match "NvimTree" then
M.View.tabpages = {}
end
if curwin ~= view_winnr or bufname == "" or curbuf == view_bufnr then
@ -337,26 +336,24 @@ function M._prevent_buffer_override()
-- might need a better patch
vim.cmd "setlocal nowinfixwidth"
vim.cmd "setlocal nowinfixheight"
M.open({ focus_tree = false })
require"nvim-tree.renderer".draw()
require"nvim-tree".find_file(false)
M.open { focus_tree = false }
require("nvim-tree.renderer").draw()
require("nvim-tree").find_file(false)
end)
end
local DEFAULT_CONFIG = {
width = 30,
height = 30,
side = 'left',
side = "left",
preserve_window_proportions = false,
number = false,
relativenumber = false,
signcolumn = 'yes'
signcolumn = "yes",
}
function M.setup(opts)
local options = vim.tbl_deep_extend('force', DEFAULT_CONFIG, opts.view or {})
local options = vim.tbl_deep_extend("force", DEFAULT_CONFIG, opts.view or {})
M.View.side = options.side
M.View.width = options.width
M.View.height = options.height