robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Nathan Zengrefactor(defaults): edit global cwd on "1-" #412544a3197f2ad

master
2.4 KiB85 linesraw
1if vim.g.loaded_nvim_dir_plugin ~= nil then
2  return
3end
4vim.g.loaded_nvim_dir_plugin = true
5
6local api = vim.api
7local nvim_on = require('vim._core.util').nvim_on
8
9vim.keymap.set('n', '<Plug>(nvim-dir-open)', function()
10  require('nvim.dir')._open_entry()
11end, { silent = true, desc = 'Open directory entry' })
12
13vim.keymap.set('n', '<Plug>(nvim-dir-up)', function()
14  if vim.v.count == 1 then
15    -- Edits global CWD
16    api.nvim_cmd({
17      cmd = 'edit',
18      args = { vim.fn.getcwd(-1, -1, -1) },
19      mods = { keepalt = vim.b.nvim_dir ~= nil },
20      magic = { file = false, bar = false },
21    }, {})
22    return
23  end
24  local dir = require('nvim.dir')
25  for _ = 1, vim.v.count1 do
26    dir._open_parent()
27  end
28end, { silent = true, desc = 'Open parent directory' })
29
30vim.keymap.set('n', '<Plug>(nvim-dir-reload)', function()
31  require('nvim.dir')._reload()
32end, { silent = true, desc = 'Reload directory' })
33
34if vim.fn.mapcheck('-', 'n') == '' and vim.fn.hasmapto('<Plug>(nvim-dir-up)', 'n') == 0 then
35  vim.keymap.set('n', '-', '<Plug>(nvim-dir-up)', { silent = true, desc = 'Open parent directory' })
36end
37
38---@param buf integer
39---@param path string
40---@return boolean
41local function should_open(buf, path)
42  if path == '' then
43    return false
44  end
45  if vim.bo[buf].buftype ~= '' and vim.b[buf].nvim_dir == nil then
46    return false
47  end
48  if vim.bo[buf].filetype == 'netrw' or vim.b[buf].netrw_curdir ~= nil then
49    return false
50  end
51  return vim.fn.isdirectory(path) == 1
52end
53
54api.nvim_create_augroup('FileExplorer', { clear = true })
55local group = api.nvim_create_augroup('nvim.dir', { clear = true })
56-- Latch on our own VimEnter, not v:vim_did_enter (set just before VimEnter
57-- autocmds), so an earlier VimEnter autocmd's BufEnter can't preempt startup.
58local vimentered = vim.v.vim_did_enter == 1
59
60nvim_on('BufEnter', group, {
61  pattern = '*',
62  desc = 'Open local directories',
63  nested = true,
64}, function(ev)
65  if vimentered and should_open(ev.buf, ev.file) then
66    require('nvim.dir').try_open(ev.buf, ev.file)
67  end
68end)
69
70nvim_on('VimEnter', group, {
71  pattern = '*',
72  desc = 'Open startup local directories',
73  nested = true,
74}, function()
75  vimentered = true
76  for _, win in ipairs(api.nvim_tabpage_list_wins(0)) do
77    if api.nvim_win_is_valid(win) then
78      local buf = api.nvim_win_get_buf(win)
79      if should_open(buf, api.nvim_buf_get_name(buf)) then
80        require('nvim.dir').handle_startup_dirs()
81        return
82      end
83    end
84  end
85end)