robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
25.5 KiB918 linesraw
1local n = require('test.functional.testnvim')()
2local t = require('test.testutil')
3
4local describe, it, after_each, pending, finally =
5  t.describe, t.it, t.after_each, t.pending, t.finally
6local api = n.api
7local command = n.command
8local eq = t.eq
9local exec_capture = n.exec_capture
10local exec_lua = n.exec_lua
11local feed = n.feed
12local fn = n.fn
13local ok = t.ok
14local poke_eventloop = n.poke_eventloop
15
16local function lines()
17  return api.nvim_buf_get_lines(0, 0, -1, true)
18end
19
20local function edit(path)
21  api.nvim_cmd({ cmd = 'edit', args = { path }, magic = { file = false, bar = false } }, {})
22end
23
24local function cd(path)
25  api.nvim_cmd({ cmd = 'cd', args = { path }, magic = { file = false, bar = false } }, {})
26end
27
28local function line_of(text)
29  for i, line in ipairs(lines()) do
30    if line == text then
31      return i
32    end
33  end
34  error(('missing line %q in %s'):format(text, vim.inspect(lines())))
35end
36
37local function bufopt(name)
38  return api.nvim_get_option_value(name, { buf = 0 })
39end
40
41local function has_syntax_group(name)
42  return exec_capture('syntax list ' .. name):find(name, 1, true) ~= nil
43end
44
45local function assert_directory(path)
46  local ffname = path:sub(-1) == '/' and path or path .. '/'
47  eq(ffname, api.nvim_buf_get_name(0))
48  eq(path, vim.fs.normalize(fn.fnamemodify(fn.bufname('%'), ':p')))
49  eq('directory', bufopt('filetype'))
50  eq(true, bufopt('buflisted'))
51end
52
53local function filesystem_root(path)
54  local root = vim.fs.normalize(vim.fs.abspath(path))
55  for parent in vim.fs.parents(root) do
56    root = parent
57  end
58  return root
59end
60
61local function write_config_plugin(path, text)
62  local plugin_file = vim.fs.joinpath(vim.fn.stdpath('config'), path)
63  vim.fs.mkdir(vim.fs.dirname(plugin_file), { parents = true })
64  finally(function()
65    os.remove(plugin_file)
66  end)
67  t.write_file(plugin_file, text)
68end
69
70---@param args? string[]
71---@return string[]
72local function with_buftype_optionset(args)
73  return vim.list_extend({
74    '--clean',
75    '--cmd',
76    'let g:nvim_dir_events = []',
77    '--cmd',
78    [[autocmd OptionSet buftype call add(g:nvim_dir_events, v:option_new)]],
79  }, args or {})
80end
81
82local function expect_buftype_optionset(path)
83  assert_directory(path)
84  eq({ 'nowrite' }, exec_lua('return vim.g.nvim_dir_events'))
85end
86
87describe('nvim.dir', function()
88  local root
89  local subdir
90  local file
91
92  local function make_fixture()
93    root = vim.fs.normalize(t.tmpname(false) .. ' space%#')
94    subdir = root .. '/subdir'
95    file = root .. '/alpha.txt'
96    t.mkdir(root)
97    t.mkdir(subdir)
98    t.write_file(file, 'alpha', true)
99    t.write_file(root .. '/.hidden', 'hidden', true)
100  end
101
102  after_each(function()
103    if root then
104      n.rmdir(root)
105    end
106    root = nil
107  end)
108
109  it('opens a startup directory argument', function()
110    make_fixture()
111    n.clear({ args = { '--clean', root } })
112
113    assert_directory(root)
114    eq(false, vim.tbl_contains(lines(), '../'))
115    eq('subdir/', lines()[1])
116    line_of('.hidden')
117    line_of('alpha.txt')
118  end)
119
120  it('3P dir-browser can handle `FileType directory` event and rename buf', function()
121    make_fixture()
122    n.clear({ args = { '--clean' } })
123    exec_lua(function()
124      _G.nvim_dir_loaded_in_filetype = nil
125      vim.api.nvim_create_autocmd('FileType', {
126        pattern = 'directory',
127        callback = function(ev)
128          _G.nvim_dir_loaded_in_filetype = package.loaded['nvim.dir'] ~= nil
129          local dir = vim.api.nvim_buf_get_name(ev.buf)
130          local browser = vim.api.nvim_create_buf(false, true)
131          vim.api.nvim_buf_set_name(browser, 'example://' .. dir)
132          vim.api.nvim_buf_set_lines(browser, 0, -1, false, {
133            'plugin browser for: ' .. dir,
134          })
135          vim.api.nvim_set_current_buf(browser)
136          vim.api.nvim_buf_delete(ev.buf, { force = true })
137        end,
138      })
139    end)
140
141    edit(root)
142
143    eq(false, exec_lua('return _G.nvim_dir_loaded_in_filetype'))
144    eq('example://' .. root .. '/', api.nvim_buf_get_name(0))
145    eq({ 'plugin browser for: ' .. root .. '/' }, lines())
146    eq(false, exec_lua([[return package.loaded['nvim.dir'] ~= nil]]))
147    eq('', exec_capture('messages'))
148  end)
149
150  it('triggers nested autocmds when opening directory buffers', function()
151    make_fixture()
152
153    n.clear({
154      args = with_buftype_optionset({ root }),
155    })
156    expect_buftype_optionset(root)
157
158    n.clear({
159      args = with_buftype_optionset(),
160    })
161    edit(root)
162    expect_buftype_optionset(root)
163  end)
164
165  it('handles nested autocmds deleting the directory buffer', function()
166    make_fixture()
167    n.clear({
168      args = {
169        '--clean',
170        '--cmd',
171        'let g:nvim_dir_wiped = 0',
172        '--cmd',
173        [[autocmd OptionSet buftype let g:nvim_dir_wiped = 1 | bwipeout!]],
174        root,
175      },
176    })
177
178    eq(1, exec_lua('return vim.g.nvim_dir_wiped'))
179    eq('', exec_capture('messages'))
180  end)
181
182  it('does not load the module until opening a directory', function()
183    make_fixture()
184    n.clear({ args = { '--clean' } })
185
186    eq(false, exec_lua([[return package.loaded['nvim.dir'] ~= nil]]))
187    edit(root)
188    eq(true, exec_lua([[return package.loaded['nvim.dir'] ~= nil]]))
189    assert_directory(root)
190  end)
191
192  it('opens a custom listing provider', function()
193    n.clear({ args = { '--clean' } })
194
195    exec_lua(function()
196      require('nvim.dir').open(0, 'custom://root', {
197        list = function(_, name, cb)
198          vim.g.nvim_dir_list_name = name
199          cb(nil, {
200            { name = 'child', dir = true },
201            { name = 'file.txt', dir = false },
202          })
203        end,
204        open = function(_, name, entry)
205          vim.g.nvim_dir_opened = entry.name .. ':' .. name
206        end,
207        open_parent = function(_, name)
208          vim.g.nvim_dir_parent = name
209        end,
210        init = function(buf)
211          vim.bo[buf].filetype = 'customdir'
212        end,
213      })
214    end)
215
216    eq('custom://root', api.nvim_buf_get_name(0))
217    eq('customdir', bufopt('filetype'))
218    eq({ 'child/', 'file.txt' }, lines())
219    eq('custom://root', exec_lua('return vim.g.nvim_dir_list_name'))
220
221    api.nvim_win_set_cursor(0, { 2, 0 })
222    api.nvim_set_option_value('modifiable', true, { buf = 0 })
223    api.nvim_set_current_line('renamed.txt')
224    feed('<CR>')
225    poke_eventloop()
226    eq('renamed.txt:custom://root', exec_lua('return vim.g.nvim_dir_opened'))
227
228    feed('-')
229    poke_eventloop()
230    eq('custom://root', exec_lua('return vim.g.nvim_dir_parent'))
231  end)
232
233  it('reports custom listing provider errors', function()
234    n.clear({ args = { '--clean' } })
235
236    exec_lua(function()
237      require('nvim.dir').open(0, 'custom://error', {
238        list = function(buf, _, cb)
239          vim.b[buf].custom_fail = (vim.b[buf].custom_fail or 0) + 1
240          if vim.b[buf].custom_fail == 1 then
241            cb('simulated error')
242          else
243            cb(nil, { { name = 'recovered.txt', dir = false } })
244          end
245        end,
246        open = function() end,
247        open_parent = function() end,
248      })
249    end)
250
251    ok(exec_capture('messages'):find('simulated error', 1, true) ~= nil)
252    -- A failed initial load renders an empty listing that "R" can retry.
253    eq('simulated error', exec_lua([[return vim.b.nvim_dir.err]]))
254    eq({ '' }, lines())
255    eq('nowrite', bufopt('buftype'))
256    eq(false, bufopt('modifiable'))
257    feed('R')
258    poke_eventloop()
259    eq({ 'recovered.txt' }, lines())
260    eq(vim.NIL, exec_lua([[return vim.b.nvim_dir.err]]))
261  end)
262
263  it('failed directory open does not repeat the error on every BufEnter', function()
264    t.skip(t.is_os('win'), 'directory permissions are POSIX-only')
265    t.skip(vim.uv.getuid() == 0, 'root ignores directory permissions')
266    n.clear({ args = { '--clean' } })
267    make_fixture()
268    local locked = root .. '/locked'
269    t.mkdir(locked)
270    finally(function()
271      vim.uv.fs_chmod(locked, tonumber('755', 8))
272    end)
273    vim.uv.fs_chmod(locked, 0)
274
275    edit(root)
276    api.nvim_win_set_cursor(0, { line_of('locked/'), 0 })
277    feed('<CR>')
278    poke_eventloop()
279    local function count_errors()
280      local _, n_errors = exec_capture('messages'):gsub('EACCES', '')
281      return n_errors
282    end
283    eq(1, count_errors())
284    ok(exec_lua([[return vim.b.nvim_dir.err]]):find('EACCES', 1, true) ~= nil)
285    eq('nowrite', bufopt('buftype'))
286    edit(file)
287    feed('<C-^>')
288    poke_eventloop()
289    eq(1, count_errors())
290    vim.uv.fs_chmod(locked, tonumber('755', 8))
291    t.write_file(locked .. '/inside.txt', 'inside', true)
292    feed('R')
293    poke_eventloop()
294    eq({ 'inside.txt' }, lines())
295  end)
296
297  it('does not swallow errors raised after the list callback', function()
298    n.clear({ args = { '--clean' } })
299
300    local err = exec_lua(function()
301      local ok_open, e = pcall(require('nvim.dir').open, 0, 'custom://late-error', {
302        list = function(_, _, cb)
303          cb(nil, { { name = 'file.txt', dir = false } })
304          error('late provider error')
305        end,
306        open = function() end,
307        open_parent = function() end,
308      })
309      return not ok_open and tostring(e) or nil
310    end)
311    ok(err ~= nil and err:find('late provider error', 1, true) ~= nil)
312    eq({ 'file.txt' }, lines())
313  end)
314
315  it('reloads custom listing providers', function()
316    n.clear({ args = { '--clean' } })
317
318    exec_lua(function()
319      require('nvim.dir').open(0, 'custom://root', {
320        list = function(buf, _, cb)
321          vim.b[buf].custom_count = (vim.b[buf].custom_count or 0) + 1
322          cb(nil, { { name = 'file' .. vim.b[buf].custom_count .. '.txt', dir = false } })
323        end,
324        open = function() end,
325        open_parent = function() end,
326      })
327    end)
328
329    eq({ 'file1.txt' }, lines())
330    feed('R')
331    poke_eventloop()
332    eq({ 'file2.txt' }, lines())
333  end)
334
335  it('fires DirReadPost for every listing', function()
336    make_fixture()
337    -- Entry order is locale-dependent: PUC Lua compares strings with strcoll().
338    n.clear({ args = { '--clean' }, env = { LC_ALL = 'C' } })
339    exec_lua(function()
340      vim.g.renders = 0
341      vim.api.nvim_create_autocmd('User', {
342        pattern = 'DirReadPost',
343        callback = function(args)
344          vim.g.renders = vim.g.renders + 1
345          vim.g.render_lines = vim.api.nvim_buf_get_lines(args.buf, 0, -1, true)
346          vim.g.render_writable = vim.bo[args.buf].modifiable and not vim.bo[args.buf].readonly
347        end,
348      })
349    end)
350
351    edit(root)
352    eq(1, exec_lua('return vim.g.renders'))
353    eq({ 'subdir/', '.hidden', 'alpha.txt' }, exec_lua('return vim.g.render_lines'))
354    -- Writable while handlers run, locked again afterwards.
355    eq(true, exec_lua('return vim.g.render_writable'))
356    eq(false, bufopt('modifiable'))
357    eq(true, bufopt('readonly'))
358    eq(false, bufopt('modified'))
359
360    feed('R')
361    poke_eventloop()
362    eq(2, exec_lua('return vim.g.renders'))
363
364    edit(root)
365    eq(3, exec_lua('return vim.g.renders'))
366
367    api.nvim_win_set_cursor(0, { line_of('subdir/'), 0 })
368    feed('<CR>')
369    poke_eventloop()
370    assert_directory(subdir)
371    eq(4, exec_lua('return vim.g.renders'))
372  end)
373
374  it('keeps the listing readonly when a handler errors', function()
375    make_fixture()
376    -- Entry order is locale-dependent: PUC Lua compares strings with strcoll().
377    n.clear({ args = { '--clean' }, env = { LC_ALL = 'C' } })
378    exec_lua(function()
379      vim.api.nvim_create_autocmd('User', {
380        pattern = 'DirReadPost',
381        callback = function()
382          error('handler error')
383        end,
384      })
385    end)
386
387    edit(root)
388
389    eq({ 'subdir/', '.hidden', 'alpha.txt' }, lines())
390    eq(false, bufopt('modifiable'))
391    eq(true, bufopt('readonly'))
392  end)
393
394  it('selects the origin entry after a handler reorders', function()
395    make_fixture()
396    n.clear({ args = { '--clean' } })
397    exec_lua(function()
398      vim.api.nvim_create_autocmd('User', {
399        pattern = 'DirReadPost',
400        callback = function()
401          vim.cmd('silent keeppatterns sort!')
402        end,
403      })
404    end)
405
406    edit(subdir)
407    feed('-')
408    poke_eventloop()
409
410    eq({ 'subdir/', 'alpha.txt', '.hidden' }, lines())
411    eq('subdir/', api.nvim_get_current_line())
412  end)
413
414  it('ignores callbacks from replaced listings', function()
415    n.clear({ args = { '--clean' } })
416
417    exec_lua(function()
418      local dir = require('nvim.dir')
419      dir.open(0, 'custom://old', {
420        list = function(_, _, cb)
421          _G.nvim_dir_stale_callback = cb
422        end,
423        open = function() end,
424        open_parent = function() end,
425      })
426      dir.open(0, 'custom://new', {
427        list = function(_, _, cb)
428          cb(nil, { { name = 'current.txt', dir = false } })
429        end,
430        open = function() end,
431        open_parent = function() end,
432      })
433    end)
434
435    eq('custom://new', api.nvim_buf_get_name(0))
436    eq({ 'current.txt' }, lines())
437
438    exec_lua(function()
439      _G.nvim_dir_stale_callback(nil, { { name = 'stale.txt', dir = false } })
440    end)
441
442    eq('custom://new', api.nvim_buf_get_name(0))
443    eq({ 'current.txt' }, lines())
444  end)
445
446  it('replaces listing providers', function()
447    n.clear({ args = { '--clean' } })
448
449    exec_lua(function()
450      local dir = require('nvim.dir')
451      local function provider(label)
452        return {
453          list = function(buf, _, cb)
454            local key = 'nvim_dir_' .. label .. '_lists'
455            vim.b[buf][key] = (vim.b[buf][key] or 0) + 1
456            vim.g.nvim_dir_provider_list = label .. ':' .. vim.b[buf][key]
457            cb(nil, { { name = label .. '.txt', dir = false } })
458          end,
459          open = function(_, _, entry)
460            vim.g.nvim_dir_provider_open = label .. ':' .. entry.name
461          end,
462          open_parent = function()
463            vim.g.nvim_dir_provider_parent = label
464          end,
465        }
466      end
467      dir.open(0, 'custom://old', provider('old'))
468      dir.open(0, 'custom://new', provider('new'))
469    end)
470
471    eq({ 'new.txt' }, lines())
472    eq('new:1', exec_lua('return vim.g.nvim_dir_provider_list'))
473    for _, plug in ipairs({
474      '<Plug>(nvim-dir-open)',
475      '<Plug>(nvim-dir-up)',
476      '<Plug>(nvim-dir-reload)',
477    }) do
478      eq(0, fn.maparg(plug, 'n', false, true).buffer)
479    end
480
481    feed('<CR>')
482    poke_eventloop()
483    eq('new:new.txt', exec_lua('return vim.g.nvim_dir_provider_open'))
484
485    feed('-')
486    poke_eventloop()
487    eq('new', exec_lua('return vim.g.nvim_dir_provider_parent'))
488
489    feed('R')
490    poke_eventloop()
491    eq('new:2', exec_lua('return vim.g.nvim_dir_provider_list'))
492  end)
493
494  it('maps [count]- to open directories', function()
495    make_fixture()
496    n.clear({ args_rm = { '--cmd' }, args = { '--clean' } })
497    local cwd = vim.fs.normalize(fn.getcwd())
498
499    edit(file)
500    feed('-')
501    poke_eventloop()
502
503    assert_directory(root)
504    line_of('alpha.txt')
505
506    -- Ensure the cursor stays on the entry we navigated up from.
507    eq('alpha.txt', api.nvim_get_current_line())
508
509    edit(file)
510    feed('1-')
511    poke_eventloop()
512
513    assert_directory(cwd)
514
515    edit(file)
516    feed('-')
517    poke_eventloop()
518    feed('1-')
519    poke_eventloop()
520    assert_directory(cwd)
521
522    edit(file)
523    feed('2-')
524    poke_eventloop()
525
526    assert_directory(vim.fs.dirname(root))
527    eq(vim.fs.basename(root) .. '/', api.nvim_get_current_line())
528  end)
529
530  it('maps - to open the current directory from a buffer with no path', function()
531    make_fixture()
532    n.clear({ args_rm = { '--cmd' }, args = { '--clean' } })
533    local cwd = fn.getcwd()
534    command('terminal')
535    eq('terminal', api.nvim_get_option_value('buftype', { buf = 0 }))
536    cd(root)
537    finally(function()
538      cd(cwd)
539    end)
540
541    feed('-')
542    poke_eventloop()
543
544    assert_directory(root)
545
546    command('enew')
547    eq('', api.nvim_buf_get_name(0))
548    feed('-')
549    poke_eventloop()
550
551    assert_directory(root)
552  end)
553
554  it('preserves a modified unnamed buffer when opening the current directory', function()
555    make_fixture()
556    n.clear({ args_rm = { '--cmd' }, args = { '--clean' } })
557    local cwd = fn.getcwd()
558    cd(root)
559    finally(function()
560      cd(cwd)
561    end)
562    local old_buf = api.nvim_get_current_buf()
563    api.nvim_buf_set_lines(old_buf, 0, -1, false, { 'unsaved' })
564
565    feed('-')
566    poke_eventloop()
567
568    assert_directory(root)
569    eq(old_buf, fn.bufnr('#'))
570    eq(true, api.nvim_buf_is_valid(old_buf))
571    eq(true, api.nvim_get_option_value('modified', { buf = old_buf }))
572    eq({ 'unsaved' }, api.nvim_buf_get_lines(old_buf, 0, -1, false))
573  end)
574
575  it('does not shadow startup plugin mappings in directory buffers', function()
576    make_fixture()
577    write_config_plugin(
578      'plugin/dirvish.lua',
579      [[
580        vim.g.dirvish_up = 0
581        vim.keymap.set('n', '-', function()
582          vim.g.dirvish_up = vim.g.dirvish_up + 1
583        end)
584        vim.keymap.set('n', 'a', '<Nop>')
585        vim.keymap.set('n', 's', '<Plug>(nvim-dir-split)')
586      ]]
587    )
588
589    -- Remove -u NONE instead of --clean, which excludes the config dir from 'runtimepath'.
590    n.clear({ args_rm = { '-u', '--cmd' } })
591
592    eq(1, fn.exists('g:loaded_nvim_dir_plugin')) -- Avoid false negatives.
593    edit(root)
594    assert_directory(root)
595    eq(0, fn.maparg('-', 'n', false, true).buffer)
596    eq('<Nop>', fn.maparg('a', 'n'))
597    eq('', fn.maparg('o', 'n'))
598
599    feed('-as')
600    poke_eventloop()
601
602    eq(1, exec_lua('return vim.g.dirvish_up'))
603    assert_directory(root)
604    eq(2, #api.nvim_list_wins())
605    feed('<C-W>p')
606    assert_directory(subdir)
607  end)
608
609  it('preserves alternate buffer when opening a parent directory', function()
610    make_fixture()
611    n.clear({ args_rm = { '--cmd' }, args = { '--clean' } })
612
613    edit(file)
614    feed('-')
615    poke_eventloop()
616
617    assert_directory(root)
618    -- Keep the alternate buffer on the file we navigated up from.
619    eq(file, api.nvim_buf_get_name(fn.bufnr('#')))
620
621    feed('-')
622    poke_eventloop()
623    assert_directory(vim.fs.dirname(root))
624    eq(file, api.nvim_buf_get_name(fn.bufnr('#')))
625
626    feed('<CR>')
627    poke_eventloop()
628    assert_directory(root)
629    eq(file, api.nvim_buf_get_name(fn.bufnr('#')))
630
631    feed('1-')
632    poke_eventloop()
633    eq(file, api.nvim_buf_get_name(fn.bufnr('#')))
634  end)
635
636  it('uses an absolute buffer name for a relative startup directory argument', function()
637    make_fixture()
638    local cwd = assert(vim.uv.cwd())
639    assert(vim.uv.chdir(root))
640    n.clear({ args = { '--clean', '.' } })
641    assert(vim.uv.chdir(cwd))
642
643    assert_directory(root)
644  end)
645
646  it('normalizes edited directory names', function()
647    make_fixture()
648    local literal = root .. '/$HOME'
649    t.mkdir(literal)
650    n.clear({ args = { '--clean' } })
651
652    edit(literal .. '///')
653
654    eq(literal .. '/', api.nvim_buf_get_name(0))
655    eq('directory', bufopt('filetype'))
656    eq({ '' }, lines())
657  end)
658
659  it('does not show a parent entry at the filesystem root', function()
660    n.clear({ args = { '--clean' } })
661    local root_dir = filesystem_root(fn.getcwd())
662
663    edit(root_dir)
664
665    assert_directory(root_dir)
666    eq(false, vim.tbl_contains(lines(), '../'))
667  end)
668
669  it('navigates entries and refreshes the listing', function()
670    make_fixture()
671    n.clear({ args = { '--clean' } })
672    local cwd = fn.getcwd()
673
674    edit(root)
675    assert_directory(root)
676    eq(vim.uv.fs_realpath(root), vim.uv.fs_realpath(fn.getcwd()))
677    eq('alpha.txt', fn.findfile('alpha.txt'))
678
679    local win = api.nvim_get_current_win()
680    for key, entry in pairs({ a = 'alpha.txt', o = 'subdir/' }) do
681      local cursor = { line_of(entry), 0 }
682      api.nvim_win_set_cursor(0, cursor)
683      feed(key)
684      poke_eventloop()
685      eq(win, api.nvim_get_current_win())
686      assert_directory(root)
687      eq(cursor, api.nvim_win_get_cursor(0))
688      eq(2, #api.nvim_list_wins())
689      eq(key == 'a' and 'row' or 'col', fn.winlayout()[1])
690      feed('<C-W>p')
691      eq(root .. '/' .. entry, api.nvim_buf_get_name(0))
692      command('close')
693    end
694
695    api.nvim_win_set_cursor(0, { line_of('alpha.txt'), 0 })
696    feed('<CR>')
697    poke_eventloop()
698    eq(file, api.nvim_buf_get_name(0))
699    eq({ 'alpha' }, lines())
700    eq(cwd, fn.getcwd())
701
702    edit(subdir)
703    assert_directory(subdir)
704    eq({ '' }, lines())
705    eq(vim.uv.fs_realpath(subdir), vim.uv.fs_realpath(fn.getcwd()))
706    feed('ao')
707    poke_eventloop()
708    eq(1, #api.nvim_list_wins())
709
710    feed('-')
711    poke_eventloop()
712    assert_directory(root)
713
714    t.write_file(root .. '/beta.txt', 'beta', true)
715    feed('R')
716    poke_eventloop()
717    line_of('beta.txt')
718  end)
719
720  it("follows global 'hidden' when abandoned", function()
721    make_fixture()
722    n.clear({ args = { '--clean' } })
723
724    command('set hidden')
725
726    edit(root)
727    local root_buf = api.nvim_get_current_buf()
728    eq('', bufopt('bufhidden'))
729
730    edit(subdir)
731    eq(true, api.nvim_buf_is_loaded(root_buf))
732    eq(1, fn.getbufinfo(root_buf)[1].hidden)
733
734    n.clear({ args = { '--clean' } })
735    command('set nohidden')
736
737    edit(root)
738    root_buf = api.nvim_get_current_buf()
739    eq('', bufopt('bufhidden'))
740
741    edit(subdir)
742    eq(false, api.nvim_buf_is_loaded(root_buf))
743  end)
744
745  it('reloads directory buffers', function()
746    make_fixture()
747    n.clear({
748      args = { '--clean', '--cmd', [[autocmd FileType directory ++once setlocal bufhidden=delete]] },
749    })
750
751    edit(root)
752    assert_directory(root)
753    eq('delete', bufopt('bufhidden'))
754    eq(true, has_syntax_group('directoryDirectory'))
755    local buf = api.nvim_get_current_buf()
756
757    t.write_file(root .. '/beta.txt', 'beta', true)
758    feed('R')
759    poke_eventloop()
760    eq('delete', bufopt('bufhidden'))
761    eq(true, has_syntax_group('directoryDirectory'))
762    line_of('beta.txt')
763
764    t.write_file(root .. '/gamma.txt', 'gamma', true)
765    command('edit')
766    eq(buf, api.nvim_get_current_buf())
767    assert_directory(root)
768    eq(true, has_syntax_group('directoryDirectory'))
769    line_of('subdir/')
770    line_of('alpha.txt')
771    line_of('gamma.txt')
772  end)
773
774  it('reports an error and keeps the buffer when reloading a removed directory', function()
775    make_fixture()
776    n.clear({ args = { '--clean' } })
777
778    edit(subdir)
779    assert_directory(subdir)
780
781    n.rmdir(subdir)
782    feed('R')
783    poke_eventloop()
784
785    ok(exec_capture('messages'):find('ENOENT', 1, true) ~= nil)
786    ok(exec_lua([[return vim.b.nvim_dir.err]]):find('ENOENT', 1, true) ~= nil)
787    assert_directory(subdir)
788  end)
789
790  it('refreshes a directory when navigated into again', function()
791    make_fixture()
792    n.clear({ args = { '--clean' } })
793
794    edit(root)
795    api.nvim_win_set_cursor(0, { line_of('subdir/'), 0 })
796    feed('<CR>')
797    poke_eventloop()
798    assert_directory(subdir)
799    eq({ '' }, lines())
800
801    t.write_file(subdir .. '/new.txt', 'new', true)
802    feed('-')
803    poke_eventloop()
804    assert_directory(root)
805
806    api.nvim_win_set_cursor(0, { line_of('subdir/'), 0 })
807    feed('<CR>')
808    poke_eventloop()
809    assert_directory(subdir)
810    line_of('new.txt')
811  end)
812
813  it('displays filenames as buffer text and opens them from the buffer', function()
814    make_fixture()
815    n.clear({ args = { '--clean' } })
816
817    edit(root)
818    line_of('.hidden')
819    line_of('subdir/')
820    api.nvim_win_set_cursor(0, { line_of('alpha.txt'), 0 })
821    feed('<CR>')
822    poke_eventloop()
823
824    eq(file, api.nvim_buf_get_name(0))
825    eq({ 'alpha' }, lines())
826  end)
827
828  it('encodes special filename characters in directory buffers', function()
829    -- Windows reserves backslash as a separator and disallows control characters in filenames.
830    -- https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
831    t.skip(t.is_os('win'), 'N/A: Windows filenames cannot contain these characters')
832    make_fixture()
833    n.clear({ args = { '--clean' } })
834
835    local name = 'line\nbreak.txt'
836    local raw_names = {
837      'back\\slash.txt',
838      'tab\tname.txt',
839      'carriage\rreturn.txt',
840      'ctrl\1name.txt',
841      'del\127name.txt',
842    }
843    for _, raw_name in ipairs(raw_names) do
844      t.write_file(root .. '/' .. raw_name, 'raw', true)
845    end
846    t.write_file(root .. '/' .. name, 'newline', true)
847
848    edit(root)
849    for _, raw_name in ipairs(raw_names) do
850      line_of(raw_name)
851    end
852    api.nvim_win_set_cursor(0, { line_of('line\0break.txt'), 0 })
853    feed('a<C-W>p')
854    poke_eventloop()
855
856    eq(root .. '/' .. name, api.nvim_buf_get_name(0))
857    eq({ 'newline' }, lines())
858  end)
859
860  it('leaves existing special buffers alone', function()
861    make_fixture()
862    n.clear({ args = { '--clean' } })
863
864    api.nvim_set_option_value('buftype', 'nofile', { buf = 0 })
865    api.nvim_buf_set_name(0, root)
866    command('doautocmd BufEnter')
867
868    eq('nofile', api.nvim_get_option_value('buftype', { buf = 0 }))
869    eq('', api.nvim_get_option_value('filetype', { buf = 0 }))
870  end)
871
872  it('coexists with netrw and can be disabled', function()
873    make_fixture()
874    n.clear({ args = { '--clean' } })
875    local cwd = fn.getcwd()
876
877    ok(fn.exists(':Explore') > 0)
878    edit(root)
879    eq('directory', api.nvim_get_option_value('filetype', { buf = 0 }))
880
881    cd(root)
882    command('Explore .')
883    cd(cwd)
884    eq('netrw', api.nvim_get_option_value('filetype', { buf = 0 }))
885
886    n.clear({
887      args = { '--clean', '--cmd', 'let g:loaded_nvim_dir_plugin = 1' },
888    })
889    edit(root)
890    eq('netrw', api.nvim_get_option_value('filetype', { buf = 0 }))
891  end)
892
893  for _, case in ipairs({
894    { command = 'edit', windows = 1, tabs = 1 },
895    { command = 'split', windows = 2, tabs = 1 },
896    { command = 'vsplit', windows = 2, tabs = 1 },
897    { command = 'tabedit', windows = 1, tabs = 2 },
898    { command = 'tabnew', windows = 1, tabs = 2 },
899  }) do
900    it(('":browse %s"'):format(case.command), function()
901      if t.is_zig_build() then
902        return pending('broken with build.zig: TMPDIR relative cwd')
903      end
904      make_fixture()
905      n.clear({ args = { '--clean' } })
906      local cwd = fn.getcwd()
907
908      cd(root)
909      command('browse ' .. case.command)
910      cd(cwd)
911
912      eq(case.windows, #api.nvim_tabpage_list_wins(0))
913      eq(case.tabs, #api.nvim_list_tabpages())
914      assert_directory(root)
915      line_of('alpha.txt')
916    end)
917  end
918end)