robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
10.9 KiB404 linesraw
1--- @brief
2--- Directory listing for `:edit <dir>`.
3
4local api = vim.api
5
6local M = {}
7
8--- An entry rendered as one line in a listing buffer.
9---@class (internal) nvim.dir.Entry
10---@field name string
11---@field dir boolean
12
13--- Handler for `Provider.list`; call once with either an error or entries.
14---@alias (private) nvim.dir.ListHandler fun(err: string?, entries: nvim.dir.Entry[]?)
15
16--- Source adapter that provides entries and listing actions.
17---@class (private) nvim.dir.Provider
18--- Produce entries for this listing.
19---@field list fun(buf: integer, name: string, cb: nvim.dir.ListHandler)
20--- Open an entry from the listing.
21---@field open fun(buf: integer, name: string, entry: nvim.dir.Entry)
22--- Open the parent listing.
23---@field open_parent fun(buf: integer, name: string)
24--- Run provider-specific buffer setup after a successful open.
25---@field init? fun(buf: integer, name: string)
26
27---@class (private) nvim.dir.State
28---@field gen integer
29---@field err? string
30---@field provider? nvim.dir.Provider
31
32local listing_group = api.nvim_create_augroup('nvim.dir.listing', { clear = false })
33
34---@param err any
35local function notify_error(err)
36  vim.notify('dir: ' .. tostring(err), vim.log.levels.ERROR)
37end
38
39---@param buf integer
40---@param options [string, any][]
41---@return boolean
42local function set_buf_options(buf, options)
43  for _, option in ipairs(options) do
44    if not api.nvim_buf_is_valid(buf) then
45      return false
46    end
47    api.nvim_set_option_value(option[1], option[2], { buf = buf })
48  end
49  return api.nvim_buf_is_valid(buf)
50end
51
52---@param name string
53---@return string
54local function encode_name(name)
55  return (name:gsub('\n', '\0'))
56end
57
58---@param entry nvim.dir.Entry
59---@return string
60local function entry_line(entry)
61  return encode_name(entry.name) .. (entry.dir and '/' or '')
62end
63
64---@param entry nvim.dir.Entry
65local function select_entry(entry)
66  local line = entry_line(entry)
67  vim.fn.search([[\C\m^\V]] .. vim.fn.escape(line, [[\]]) .. [[\m$]], 'cw')
68end
69
70---@param buf integer
71---@param name string
72---@param entries nvim.dir.Entry[]
73---@return boolean
74local function render_entries(buf, name, entries)
75  local lines = {} ---@type string[]
76  for i, entry in ipairs(entries) do
77    lines[i] = entry_line(entry)
78  end
79
80  if
81    not set_buf_options(buf, {
82      { 'modeline', false },
83      { 'buftype', 'nowrite' },
84      { 'buflisted', true },
85      { 'swapfile', false },
86      { 'readonly', false },
87      { 'modifiable', true },
88    })
89  then
90    return false
91  end
92  api.nvim_buf_call(buf, function()
93    api.nvim_cmd({
94      cmd = 'file',
95      args = { name },
96      mods = { keepalt = true },
97      magic = { file = false, bar = false },
98    }, {})
99  end)
100  if not api.nvim_buf_is_valid(buf) then
101    return false
102  end
103  api.nvim_buf_set_lines(buf, 0, -1, false, lines)
104  if not api.nvim_buf_is_valid(buf) then
105    return false
106  end
107  return set_buf_options(buf, {
108    { 'modified', false },
109    { 'readonly', true },
110    { 'modifiable', false },
111  })
112end
113
114--- Stop tracking a listing and remove its autocmds.
115---@param buf integer
116local function close_listing(buf)
117  if not api.nvim_buf_is_valid(buf) then
118    return
119  end
120  vim.b[buf].nvim_dir = nil
121  api.nvim_clear_autocmds({ group = listing_group, buffer = buf })
122end
123
124---@param buf integer
125---@return nvim.dir.State?
126local function get_state(buf)
127  if not api.nvim_buf_is_valid(buf) then
128    return nil
129  end
130  local state = vim.b[buf].nvim_dir
131  return type(state) == 'table' and state or nil
132end
133
134---@param buf integer
135---@return nvim.dir.Entry?
136local function current_entry(buf)
137  local state = get_state(buf)
138  if not state or not state.provider or api.nvim_get_current_buf() ~= buf then
139    return nil
140  end
141  local line = api.nvim_get_current_line()
142  if line == '' then
143    return nil
144  end
145  local dir = line:sub(-1) == '/'
146  if dir then
147    line = line:sub(1, -2)
148  end
149  if line == '' then
150    return nil
151  end
152  return { name = line:gsub('%z', '\n'), dir = dir }
153end
154
155---@type fun(buf: integer, name: string, provider: nvim.dir.Provider, restore_view?: table, setup?: boolean, select?: nvim.dir.Entry)
156local load
157
158---@param buf integer
159---@param provider nvim.dir.Provider
160local function reload(buf, provider)
161  local state = get_state(buf)
162  if not state or not state.provider then
163    return
164  end
165  local restore_view = api.nvim_get_current_buf() == buf and vim.fn.winsaveview() or nil
166  load(buf, api.nvim_buf_get_name(buf), provider, restore_view)
167end
168
169---@param buf integer
170---@param lhs string
171---@param plug string
172---@param force? boolean
173function M._map(buf, lhs, plug, force)
174  api.nvim_buf_call(buf, function()
175    if (force or vim.fn.mapcheck(lhs, 'n') == '') and vim.fn.hasmapto(plug, 'n') == 0 then
176      vim.keymap.set('n', lhs, plug, { buffer = buf, silent = true })
177    end
178  end)
179end
180
181--- Let handlers reshape the rendered listing. Unlocks the buffer for the duration and
182--- restores it afterwards, so a handler can sort, filter, or delete lines with ordinary
183--- commands.
184---@param buf integer
185---@return boolean
186local function exec_render_autocmd(buf)
187  if not set_buf_options(buf, { { 'readonly', false }, { 'modifiable', true } }) then
188    return false
189  end
190  -- Errors in handlers are reported by the autocmd machinery; swallow them here so the
191  -- buffer is never left writable.
192  pcall(api.nvim_buf_call, buf, function()
193    api.nvim_exec_autocmds('User', { pattern = 'DirReadPost', modeline = false })
194  end)
195  return set_buf_options(buf, {
196    { 'modified', false },
197    { 'readonly', true },
198    { 'modifiable', false },
199  })
200end
201
202---@param buf integer
203local function setup_render_autocmds(buf)
204  api.nvim_clear_autocmds({ group = listing_group, buffer = buf })
205  api.nvim_create_autocmd('BufReadCmd', {
206    group = listing_group,
207    buffer = buf,
208    nested = true,
209    desc = 'Reload directory listing',
210    callback = function()
211      M._reload(buf)
212    end,
213  })
214end
215
216--- Request entries and render the current list generation.
217---@param buf integer
218---@param name string
219---@param provider nvim.dir.Provider
220---@param restore_view? table
221---@param setup? boolean
222---@param select? nvim.dir.Entry
223function load(buf, name, provider, restore_view, setup, select)
224  local state = get_state(buf) or { gen = 0 }
225  local list_gen = state.gen + 1
226  state.gen = list_gen
227  vim.b[buf].nvim_dir = state
228  -- Render an empty listing (retried by "R" or :edit) if the initial load fails,
229  -- but preserve an existing listing on reload failure.
230  local first_render = state.provider == nil
231  local done = false
232
233  ---@param err string?
234  ---@param entries nvim.dir.Entry[]?
235  local function on_list(err, entries)
236    if done then
237      return
238    end
239    done = true
240    local current_state = get_state(buf)
241    if not current_state or current_state.gen ~= list_gen then
242      return
243    end
244    if err ~= nil then
245      notify_error(err)
246      if not first_render then
247        current_state.err = err
248        vim.b[buf].nvim_dir = current_state
249        return
250      end
251      entries = {}
252    end
253    ---@cast entries nvim.dir.Entry[]
254
255    if not render_entries(buf, name, entries) then
256      if first_render then
257        close_listing(buf)
258      end
259      return
260    end
261    current_state.err, current_state.provider = err, provider
262    vim.b[buf].nvim_dir = current_state
263
264    -- Runs before the cursor is placed, so handlers may reorder entries.
265    if not exec_render_autocmd(buf) then
266      return
267    end
268    if restore_view and api.nvim_get_current_buf() == buf then
269      vim.fn.winrestview(restore_view)
270    end
271    if select and api.nvim_get_current_buf() == buf then
272      select_entry(select)
273    end
274
275    if not setup then
276      return
277    end
278
279    setup_render_autocmds(buf)
280    M._map(buf, '<CR>', '<Plug>(nvim-dir-open)', true)
281    M._map(buf, '-', '<Plug>(nvim-dir-up)')
282    M._map(buf, 'R', '<Plug>(nvim-dir-reload)', true)
283    if provider.init then
284      provider.init(buf, name)
285    end
286  end
287
288  local ok, call_err = pcall(provider.list, buf, name, on_list) ---@type boolean, any
289  if not ok then
290    if done then
291      -- The handler already ran and would ignore this error: propagate it.
292      error(call_err, 0)
293    end
294    -- Route provider exceptions through the list handler so failures share one cleanup path.
295    on_list(tostring(call_err), nil)
296  end
297end
298
299--- Open {buf} as a listing named {name} using {provider}.
300---@param buf integer
301---@param name string
302---@param provider nvim.dir.Provider
303---@param select? nvim.dir.Entry
304function M.open(buf, name, provider, select)
305  buf = vim._resolve_bufnr(buf)
306  local state = get_state(buf)
307  local restore_view = state
308      and state.provider
309      and api.nvim_get_current_buf() == buf
310      and vim.fn.winsaveview()
311    or nil
312  load(buf, name, provider, restore_view, true, select)
313end
314
315---@param buf integer
316---@return nvim.dir.Provider?
317local function get_provider(buf)
318  local state = get_state(buf)
319  return state and state.provider or nil
320end
321
322---@param cmd? 'split'|'vsplit'
323function M._open_entry(cmd)
324  local buf = api.nvim_get_current_buf()
325  local provider = get_provider(buf)
326  local entry = current_entry(buf)
327  if not provider or not entry then
328    return
329  end
330  local name = api.nvim_buf_get_name(buf)
331  local win = cmd and api.nvim_get_current_win()
332  local ok, err = pcall(function()
333    if cmd then
334      api.nvim_cmd({ cmd = cmd }, {})
335    end
336    provider.open(buf, name, entry)
337  end)
338  if win and api.nvim_win_is_valid(win) then
339    api.nvim_set_current_win(win)
340  end
341  if not ok then
342    error(err, 0)
343  end
344end
345
346function M._open_parent()
347  local buf = api.nvim_get_current_buf()
348  local provider = get_provider(buf)
349  if provider then
350    provider.open_parent(buf, api.nvim_buf_get_name(buf))
351    return
352  end
353  -- Keep the global `-` mapping useful from regular file buffers.
354  require('nvim.dir.fs').open_parent_path(api.nvim_buf_get_name(buf))
355end
356
357--- Reload the existing listing with its current buffer name and provider.
358--- Replace the lines and restore the view only after a successful list; preserve the existing
359--- listing on failure. Do not rerun provider initialization or reinstall listing handlers.
360---@param buf? integer
361function M._reload(buf)
362  buf = vim._resolve_bufnr(buf)
363  local provider = get_provider(buf)
364  if provider then
365    reload(buf, provider)
366  end
367end
368
369---@param buf integer
370---@param path string
371function M.try_open(buf, path)
372  buf = vim._resolve_bufnr(buf)
373  local fs_provider = require('nvim.dir.fs')
374  if fs_provider.is_navigating() or path == '' then
375    return
376  end
377  if vim.b[buf].nvim_dir ~= nil then
378    return
379  end
380  if vim.bo[buf].buftype ~= '' then
381    return
382  end
383  if vim.bo[buf].filetype == 'netrw' or vim.b[buf].netrw_curdir ~= nil then
384    return
385  end
386
387  if vim.fn.isdirectory(path) == 0 then
388    return
389  end
390  M.open(buf, fs_provider.normalize(path), fs_provider)
391end
392
393function M.handle_startup_dirs()
394  for _, win in ipairs(api.nvim_tabpage_list_wins(0)) do
395    if api.nvim_win_is_valid(win) then
396      api.nvim_win_call(win, function()
397        local buf = api.nvim_get_current_buf()
398        M.try_open(buf, api.nvim_buf_get_name(buf))
399      end)
400    end
401  end
402end
403
404return M