robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
26.7 KiB816 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local tt = require('test.functional.testterm')
4local Screen = require('test.functional.ui.screen')
5
6local describe, it, before_each, after_each, finally =
7  t.describe, t.it, t.before_each, t.after_each, t.finally
8local uv = vim.uv
9local eq, eval, expect, exec = t.eq, n.eval, n.expect, n.exec
10local assert_alive = n.assert_alive
11local clear = n.clear
12local command = n.command
13local feed = n.feed
14local fn = n.fn
15local neq = t.neq
16local nvim_prog = n.nvim_prog
17local ok = t.ok
18local rmdir = n.rmdir
19local new_pipename = n.new_pipename
20local pesc = vim.pesc
21local is_os = t.is_os
22local skip = t.skip
23local set_session = n.set_session
24local async_meths = n.async_meths
25local expect_msg_seq = n.expect_msg_seq
26local pcall_err = t.pcall_err
27local mkdir = t.mkdir
28local poke_eventloop = n.poke_eventloop
29local api = n.api
30local retry = t.retry
31local write_file = t.write_file
32local expect_exitcode = tt.expect_exitcode
33
34describe(':recover', function()
35  before_each(clear)
36
37  it('fails if given a non-existent swapfile', function()
38    local swapname = 'bogus_swapfile'
39    local swapname2 = 'bogus_swapfile.swp'
40    eq(
41      'Vim(recover):E305: No swap file found for ' .. swapname,
42      pcall_err(command, 'recover ' .. swapname)
43    ) -- Should not segfault. #2117
44    -- Also check filename ending with ".swp". #9504
45    eq('Vim(recover):E306: Cannot open ' .. swapname2, pcall_err(command, 'recover ' .. swapname2)) -- Should not segfault. #2117
46    assert_alive()
47  end)
48end)
49
50describe("preserve and (R)ecover with custom 'directory'", function()
51  local swapdir = uv.cwd() .. '/Xtest_recover_dir'
52  local testfile = 'Xtest_recover_file1'
53  -- Put swapdir at the start of the 'directory' list. #1836
54  -- Note: `set swapfile` *must* go after `set directory`: otherwise it may
55  -- attempt to create a swapfile in different directory.
56  local init = [[
57    set directory^=]] .. swapdir:gsub([[\]], [[\\]]) .. [[//
58    set swapfile fileformat=unix undolevels=-1
59  ]]
60
61  local nvim0 --- @type test.Session
62  before_each(function()
63    nvim0 = n.new_session(false)
64    set_session(nvim0)
65    rmdir(swapdir)
66    mkdir(swapdir)
67  end)
68  after_each(function()
69    command('%bwipeout!')
70    rmdir(swapdir)
71  end)
72
73  --- @return string
74  local function setup_swapname()
75    exec(init)
76    command('edit! ' .. testfile)
77    feed('isometext<esc>')
78    exec('redir => g:swapname | silent swapname | redir END')
79    return eval('g:swapname'):match('[^\n]*$')
80  end
81
82  local function test_recover(swappath1)
83    -- Start another Nvim instance.
84    local nvim2 =
85      n.new_session(false, { args = { '-u', 'NONE', '-i', 'NONE', '--embed' }, merge = false })
86    set_session(nvim2)
87
88    exec(init)
89
90    -- Use the "SwapExists" event to choose the (R)ecover choice at the dialog.
91    command('autocmd SwapExists * let v:swapchoice = "r"')
92    command('silent edit! ' .. testfile)
93    exec('redir => g:swapname | silent swapname | redir END')
94
95    local swappath2 = eval('g:swapname')
96
97    expect('sometext')
98    -- swapfile from session 1 should end in .swp
99    eq(testfile .. '.swp', string.match(swappath1, '[^%%]+$'))
100    -- swapfile from session 2 should end in .swo
101    eq(testfile .. '.swo', string.match(swappath2, '[^%%]+$'))
102    -- Verify that :swapname was not truncated (:help 'shortmess').
103    ok(nil == string.find(swappath1, '%.%.%.'))
104    ok(nil == string.find(swappath2, '%.%.%.'))
105  end
106
107  it('with :preserve and SIGKILL', function()
108    local swappath1 = setup_swapname()
109    command('preserve')
110    neq(nil, uv.fs_stat(swappath1))
111    eq(0, vim.uv.kill(eval('getpid()'), 'sigkill'))
112    test_recover(swappath1)
113  end)
114
115  it('closing stdio channel without :preserve #22096', function()
116    local swappath1 = setup_swapname()
117    nvim0:close()
118    neq(nil, uv.fs_stat(swappath1))
119    test_recover(swappath1)
120  end)
121
122  it('killing TUI process without :preserve #22096', function()
123    -- Windows(#38669): inner server could attach to the outer Nvim terminal's console
124    -- and die abruptly when the outer terminal job closed, leaving an unreadable swapfile
125    skip(is_os('win'), 'unreadable swapfile on Windows after TUI process exit')
126
127    local screen0 = Screen.new()
128    local child_server = new_pipename()
129    fn.jobstart({ nvim_prog, '-u', 'NONE', '-i', 'NONE', '--listen', child_server }, {
130      term = true,
131      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
132    })
133    screen0:expect({ any = pesc('[No Name]') }) -- Wait for the child process to start.
134    local child_session = n.connect(child_server)
135    set_session(child_session)
136    local swappath1 = setup_swapname()
137    set_session(nvim0)
138    -- n.exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigterm')]])
139    command('call chanclose(&channel)') -- Kill the child process.
140    -- Wait for the child process to stop.
141    screen0:expect({ any = '%[Process exited 1%]' })
142    neq(nil, uv.fs_stat(swappath1))
143    test_recover(swappath1)
144  end)
145
146  for _, ext in ipairs({ false, true }) do
147    it('manual :recover with multiple swapfiles' .. (ext and 'with ext_messages' or ''), function()
148      local swappath1 = setup_swapname()
149      eq('.swp', swappath1:match('%.[^.]+$'))
150      nvim0:close()
151      neq(nil, uv.fs_stat(swappath1))
152      local swappath2 = swappath1:gsub('%.swp$', '.swo')
153      eq(true, uv.fs_copyfile(swappath1, swappath2))
154      clear()
155      exec(init)
156      local screen, msg = Screen.new(256, 40, { ext_messages = ext }), nil
157      feed(':recover! ' .. testfile .. '<CR>')
158      if ext then
159        screen:expect({
160          cmdline = {
161            {
162              content = { { '' } },
163              pos = 0,
164              -- Default vim.ui.select prompt.
165              prompt = 'Type number and <Enter> (q or empty cancels): ',
166            },
167          },
168          condition = function()
169            msg = msg or screen.messages[1]
170            -- Concatenate all chunks (each chunk is { 'text' } or { hl_id, 'text', 'group' }).
171            local text = ''
172            for _, chunk in ipairs(msg.content) do
173              text = text .. (#chunk >= 2 and chunk[2] or chunk[1])
174            end
175            -- New ui.select-driven prompt; rich info from format_item.
176            eq(true, text:match('Select a swapfile:') ~= nil)
177            eq(true, text:match('%.swo') ~= nil)
178            eq(true, text:match('%.swp') ~= nil)
179            eq(true, text:match('host name:') ~= nil)
180            eq('confirm', msg.kind)
181            screen.messages = {}
182          end,
183        })
184      else
185        screen:expect({
186          any = {
187            vim.pesc('Select a swapfile:'),
188            '\n1:.*%.swo',
189            '\n2:.*%.swp',
190            'host name:',
191            vim.pesc('Type number and <Enter> (q or empty cancels): ^'),
192          },
193          none = vim.pesc('{18:^@}'),
194        })
195      end
196      feed('2<CR>')
197      if ext then
198        screen:expect({
199          any = { 'sometext' },
200          condition = function()
201            eq('wmsg', screen.messages[1].kind)
202            eq(true, screen.messages[1].content[1][2]:match('Using.*Original') ~= nil)
203            eq('wmsg', screen.messages[1].kind)
204            eq(true, screen.messages[2].content[1][2]:match('Recovery.*You might.*You may') ~= nil)
205            screen.messages = {}
206          end,
207        })
208      else
209        screen:expect({
210          any = {
211            vim.pesc('\nRecovery completed.'),
212            vim.pesc('\n{6:Press ENTER or type command to continue}^'),
213          },
214        })
215      end
216      feed('<CR>')
217      expect('sometext')
218    end)
219  end
220end)
221
222describe('swapfile detection', function()
223  local swapdir = uv.cwd() .. '/Xtest_swapdialog_dir'
224  local nvim0 --- @type test.Session
225  -- Put swapdir at the start of the 'directory' list. #1836
226  -- Note: `set swapfile` *must* go after `set directory`: otherwise it may
227  -- attempt to create a swapfile in different directory.
228  local init = [[
229    set directory^=]] .. swapdir:gsub([[\]], [[\\]]) .. [[//
230    set swapfile fileformat=unix nomodified undolevels=-1 nohidden
231  ]]
232  before_each(function()
233    nvim0 = n.new_session(false)
234    set_session(nvim0)
235    rmdir(swapdir)
236    mkdir(swapdir)
237  end)
238  after_each(function()
239    set_session(nvim0)
240    command('%bwipeout!')
241    rmdir(swapdir)
242  end)
243
244  it('redrawing during prompt does not break treesitter', function()
245    local testfile = 'Xtest_swapredraw.lua'
246    finally(function()
247      os.remove(testfile)
248    end)
249    write_file(
250      testfile,
251      [[
252        vim.o.foldmethod = 'expr'
253        vim.o.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
254        vim.defer_fn(function()
255          vim.api.nvim__redraw({ valid = false })
256        end, 500)
257        pcall(vim.cmd.edit, 'Xtest_swapredraw.lua')]]
258    )
259    exec(init)
260    command('edit! ' .. testfile)
261    command('preserve')
262    local args2 = { '--clean', '--embed', '--cmd', n.runtime_set }
263    local nvim2 = n.new_session(true, { args = args2, merge = false })
264    set_session(nvim2)
265    local screen2 = Screen.new(100, 40)
266    screen2:add_extra_attr_ids({
267      [100] = { foreground = Screen.colors.NvimLightGrey2 },
268      [101] = { foreground = Screen.colors.NvimLightGreen },
269      [102] = {
270        foreground = Screen.colors.NvimLightGrey4,
271        background = Screen.colors.NvimDarkGrey1,
272      },
273      [104] = { foreground = Screen.colors.NvimLightCyan },
274      [105] = { foreground = Screen.colors.NvimDarkGrey4 },
275      [106] = {
276        foreground = Screen.colors.NvimLightGrey2,
277        background = Screen.colors.NvimDarkGrey4,
278      },
279      [107] = { foreground = Screen.colors.NvimLightGrey2, bold = true },
280      [108] = { foreground = Screen.colors.NvimLightBlue },
281    })
282    exec(init)
283    command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
284    feed(':edit ' .. testfile .. '<CR>')
285    eq('r?', api.nvim_get_mode().mode)
286    feed('E:source<CR>')
287    eq('r?', api.nvim_get_mode().mode)
288    screen2:sleep(1000)
289    feed('E')
290    screen2:expect([[
291      {100:^vim.o.foldmethod} {100:=} {101:'expr'}                                                                           |
292      {100:vim.o.foldexpr} {100:=} {101:'v:lua.vim.treesitter.foldexpr()'}                                                  |
293      {102:+--  3 lines: vim.defer_fn(function()·······························································}|
294      {104:pcall}{100:(vim.cmd.edit,} {101:'Xtest_swapredraw.lua'}{100:)}                                                         |
295      {105:~                                                                                                   }|*34
296      {106:Xtest_swapredraw.lua                                                              1,1            All}|
297                                                                                                          |
298    ]])
299    nvim2:close()
300  end)
301
302  it('always show swapfile dialog #8840 #9027', function()
303    local testfile = 'Xtest_swapdialog_file1'
304
305    local expected_no_dialog = '^' .. (' '):rep(256) .. '|\n'
306    for _ = 1, 37 do
307      expected_no_dialog = expected_no_dialog .. '~' .. (' '):rep(255) .. '|\n'
308    end
309    expected_no_dialog = expected_no_dialog .. testfile .. (' '):rep(216) .. '0,0-1          All|\n'
310    expected_no_dialog = expected_no_dialog .. (' '):rep(256) .. '|\n'
311
312    exec(init)
313    command('edit! ' .. testfile)
314    feed('isometext<esc>')
315    command('preserve')
316
317    -- Start another Nvim instance.
318    local nvim2 =
319      n.new_session(true, { args = { '-u', 'NONE', '-i', 'NONE', '--embed' }, merge = false })
320    set_session(nvim2)
321    local screen2 = Screen.new(256, 40)
322    screen2._default_attr_ids = nil
323    exec(init)
324    command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
325
326    -- With shortmess+=F
327    command('set shortmess+=F')
328    feed(':edit ' .. testfile .. '<CR>')
329    screen2:expect {
330      any = [[E325: ATTENTION.*]]
331        .. '\n'
332        .. [[Found a swap file by the name ".*]]
333        .. [[Xtest_swapdialog_dir[/\].*]]
334        .. testfile
335        .. [[%.swp"]],
336    }
337    feed('e') -- Chose "Edit" at the swap dialog.
338    screen2:expect(expected_no_dialog)
339
340    -- With :silent and shortmess+=F
341    feed(':silent edit %<CR>')
342    screen2:expect {
343      any = [[Found a swap file by the name ".*]]
344        .. [[Xtest_swapdialog_dir[/\].*]]
345        .. testfile
346        .. [[%.swp"]],
347    }
348    feed('e') -- Chose "Edit" at the swap dialog.
349    screen2:expect(expected_no_dialog)
350
351    -- With :silent! and shortmess+=F
352    feed(':silent! edit %<CR>')
353    screen2:expect {
354      any = [[Found a swap file by the name ".*]]
355        .. [[Xtest_swapdialog_dir[/\].*]]
356        .. testfile
357        .. [[%.swp"]],
358    }
359    feed('e') -- Chose "Edit" at the swap dialog.
360    screen2:expect(expected_no_dialog)
361
362    -- With API (via eval/Vimscript) call and shortmess+=F
363    feed(':call nvim_command("edit %")<CR>')
364    screen2:expect {
365      any = [[Found a swap file by the name ".*]]
366        .. [[Xtest_swapdialog_dir[/\].*]]
367        .. testfile
368        .. [[%.swp"]],
369    }
370    feed('e') -- Chose "Edit" at the swap dialog.
371    screen2:expect({ any = pesc('E5555: API call: Vim(edit):E325: ATTENTION') })
372    feed('<c-c>')
373    screen2:expect(expected_no_dialog)
374
375    -- With API call and shortmess+=F
376    async_meths.nvim_command('edit %')
377    screen2:expect {
378      any = [[Found a swap file by the name ".*]]
379        .. [[Xtest_swapdialog_dir[/\].*]]
380        .. testfile
381        .. [[%.swp"]],
382    }
383    feed('e') -- Chose "Edit" at the swap dialog.
384    expect_msg_seq({
385      ignore = { 'redraw' },
386      seqs = {
387        { { 'notification', 'nvim_error_event', { 0, 'Vim(edit):E325: ATTENTION' } } },
388      },
389    })
390    feed('<cr>')
391
392    nvim2:close()
393  end)
394
395  it('default SwapExists handler selects "(E)dit" and skips prompt', function()
396    exec(init)
397    command('edit Xfile1')
398    command("put ='some text...'")
399    command('preserve') -- Make sure the swap file exists.
400    local nvimpid = fn.getpid()
401
402    local nvim1 = n.new_session(true)
403    set_session(nvim1)
404    local screen = Screen.new(75, 18)
405    exec(init)
406
407    feed(':edit Xfile1\n')
408    local msg_expected = ('W325: Ignoring swapfile from Nvim process %d'):format(nvimpid)
409    screen:expect({ any = vim.pesc(msg_expected) })
410    eq(msg_expected, n.exec_capture('messages'))
411    command('bwipe!')
412
413    -- With smaller screen, the message should be truncated, but only in display.
414    screen:try_resize(40, 18)
415    feed(':edit Xfile1\n')
416    screen:expect([[
417      ^                                        |
418      {1:~                                       }|*16
419      {19:W325: Ignoring swapfile from Nvim proces}|
420    ]])
421    eq(('\n' .. msg_expected):rep(2):sub(2), n.exec_capture('messages'))
422    command('bwipe!')
423
424    -- Also test with 'ruler'.
425    screen:try_resize(60, 18)
426    command('set ruler')
427    feed(':edit Xfile1\n')
428    screen:expect([[
429      ^                                                            |
430      {1:~                                                           }|*16
431      {19:W325: Ignoring swapfile from Nvim process }0,0-1          All|
432    ]])
433    eq(('\n' .. msg_expected):rep(3):sub(2), n.exec_capture('messages'))
434    command('bwipe!')
435
436    nvim1:close()
437  end)
438
439  -- ui2 opens windows to show a message, which chdirs in and out of the target window's context.
440  -- readfile() aliases the buffer name across that.
441  it('ui2 message from the SwapExists handler does not abort the read #41454', function()
442    exec(init)
443    write_file('Xfile1', 'some text...\n')
444    command('edit Xfile1')
445    command('preserve') -- Make sure the swap file exists.
446
447    local initfile = 'Xtest_swapdialog_init.lua'
448    write_file(
449      initfile,
450      ('vim.opt.directory:prepend(%q)\nrequire("vim._core.ui2").enable()\n'):format(swapdir .. '//')
451    )
452    finally(function()
453      os.remove(initfile)
454      os.remove('Xfile1')
455    end)
456
457    local nvim1 = n.new_session(true)
458    set_session(nvim1)
459    local screen = Screen.new(75, 10)
460    -- ui2 needs a UI attached while the file argument is read, i.e. a real TTY.
461    fn.jobstart({ nvim_prog, '-i', 'NONE', '--noplugin', '-u', initfile, 'Xfile1' }, {
462      term = true,
463      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
464    })
465    screen:expect({
466      grid = [[
467        ^some text...                                                               |
468        ~                                                                          |*6
469        Xfile1                                                   1,1            All|
470        {MATCH:W325: Ignoring swapfile from Nvim process %d+ *}|
471                                                                                   |
472      ]],
473      attr_ids = {},
474    })
475
476    nvim1:close()
477  end)
478
479  it('attention message kind', function()
480    exec(init)
481    command('edit Xfile1')
482    command('preserve') -- Make sure the swap file exists.
483
484    local screen = Screen.new(nil, nil, { ext_messages = true })
485    local nvim = n.new_session(true)
486    set_session(nvim)
487    screen:attach()
488    exec(init)
489    command('edit Xfile1')
490    command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
491    command('edit Xfile2 | bunload 1') -- Unload to get non-prompt attention message.
492    command('silent! call bufload("Xfile1")')
493    screen:expect({
494      condition = function()
495        for _, msg in pairs(screen.messages) do
496          local ok = msg.content[1][2]:match('W325')
497          eq(true, ok and msg.kind == 'echomsg' or msg.kind == 'wmsg')
498          eq(true, (ok or msg.content[1][2]:match('Found a swap.*If you did')) ~= nil)
499        end
500        screen.messages = {}
501      end,
502      cmdline = {
503        { content = { { '' } }, hl = 'MoreMsg', pos = 0, prompt = 'Press any key to continue' },
504      },
505    })
506    nvim:close()
507  end)
508
509  -- oldtest: Test_swap_prompt_splitwin()
510  it('selecting "q" in the attention prompt', function()
511    exec(init)
512    command('edit Xfile1')
513    command('preserve') -- Make sure the swap file exists.
514
515    local screen = Screen.new(75, 18)
516    local nvim1 = n.new_session(true)
517    set_session(nvim1)
518    screen:attach()
519    exec(init)
520    command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
521    feed(':split Xfile1\n')
522    -- The default SwapExists handler does _not_ skip this prompt.
523    screen:expect({
524      any = pesc('{6:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^'),
525    })
526    feed('q')
527    screen:expect([[
528      ^                                                                           |
529      {1:~                                                                          }|*16
530                                                                                 |
531    ]])
532    feed(':<CR>')
533    screen:expect([[
534      ^                                                                           |
535      {1:~                                                                          }|*16
536      :                                                                          |
537    ]])
538    nvim1:close()
539
540    local nvim2 = n.new_session(true)
541    set_session(nvim2)
542    screen:attach()
543    exec(init)
544    command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
545    command('set more')
546    command('au bufadd * let foo_w = wincol()')
547    feed(':e Xfile1<CR>')
548    screen:expect({ any = pesc('{6:-- More --}^') })
549    feed('<Space>')
550    screen:expect({
551      any = pesc('{6:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^'),
552    })
553    feed('q')
554    command([[echo 'hello']])
555    screen:expect([[
556      ^                                                                           |
557      {1:~                                                                          }|*16
558      hello                                                                      |
559    ]])
560    nvim2:close()
561  end)
562
563  --- @param swapexists boolean Enable the default SwapExists handler.
564  --- @param on_swapfile_running fun(screen: any) Called after swapfile ("STILL RUNNING") prompt.
565  local function test_swapfile_after_reboot(swapexists, on_swapfile_running)
566    local screen = Screen.new(75, 30)
567
568    exec(init)
569    if not swapexists then
570      command('autocmd! nvim.swapfile') -- Delete the default handler (which skips the dialog).
571    end
572    command('set nohidden')
573
574    exec([=[
575      " Make a copy of the current swap file to "Xswap".
576      " Return the name of the swap file.
577      func CopySwapfile()
578        preserve
579        " get the name of the swap file
580        let swname = split(execute("swapname"))[0]
581        let swname = substitute(swname, '[[:blank:][:cntrl:]]*\(.\{-}\)[[:blank:][:cntrl:]]*$', '\1', '')
582        " make a copy of the swap file in Xswap
583        set binary
584        exe 'sp ' . fnameescape(swname)
585        w! Xswap
586        set nobinary
587        return swname
588      endfunc
589    ]=])
590
591    -- Edit a file and grab its swapfile.
592    exec([[
593      edit Xswaptest
594      call setline(1, ['a', 'b', 'c'])
595    ]])
596    local swname = fn.CopySwapfile()
597
598    -- Forget we edited this file
599    exec([[
600      new
601      only!
602      bwipe! Xswaptest
603    ]])
604
605    os.rename('Xswap', swname)
606
607    feed(':edit Xswaptest<CR>')
608    on_swapfile_running(screen)
609
610    feed('e')
611
612    -- Forget we edited this file
613    exec([[
614      new
615      only!
616      bwipe! Xswaptest
617    ]])
618
619    -- pretend that the swapfile was created before boot
620    local atime = os.time() - uv.uptime() - 10
621    uv.fs_utime(swname, atime, atime)
622
623    feed(':edit Xswaptest<CR>')
624    screen:expect({
625      any = table.concat({
626        '{9:E325: ATTENTION}',
627        pesc('{6:[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: }^'),
628      }, '.*'),
629    })
630
631    feed('e')
632  end
633
634  -- oldtest: Test_nocatch_process_still_running()
635  it('swapfile created before boot vim-patch:8.2.2586', function()
636    test_swapfile_after_reboot(false, function(screen)
637      screen:expect({
638        any = table.concat({
639          '{9:E325: ATTENTION}',
640          '{6:        process ID: %d* %(STILL RUNNING%)}',
641          '{6:While opening file "Xswaptest"}',
642          pesc('{6:[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: }^'),
643        }, '.*'),
644      })
645    end)
646  end)
647
648  it('swapfile created before boot + default SwapExists handler', function()
649    test_swapfile_after_reboot(true, function(screen)
650      screen:expect({ any = 'W325: Ignoring swapfile from Nvim process' })
651    end)
652  end)
653end)
654
655describe('quitting swapfile dialog on startup stops TUI properly', function()
656  local swapdir = uv.cwd() .. '/Xtest_swapquit_dir'
657  local testfile = 'Xtest_swapquit_file1'
658  local otherfile = 'Xtest_swapquit_file2'
659  -- Put swapdir at the start of the 'directory' list. #1836
660  -- Note: `set swapfile` *must* go after `set directory`: otherwise it may
661  -- attempt to create a swapfile in different directory.
662  local init_dir = [[set directory^=]] .. swapdir:gsub([[\]], [[\\]]) .. [[//]]
663  local init_set = [[set swapfile fileformat=unix nomodified undolevels=-1 nohidden]]
664
665  before_each(function()
666    clear({ args = { '--cmd', init_dir, '--cmd', init_set } })
667    rmdir(swapdir)
668    mkdir(swapdir)
669    write_file(
670      testfile,
671      [[
672      first
673      second
674      third
675
676    ]]
677    )
678    command('edit! ' .. testfile)
679    feed('Gisometext<esc>')
680    poke_eventloop()
681    clear() -- Leaves a swap file behind
682    api.nvim_ui_attach(80, 30, {})
683  end)
684  after_each(function()
685    rmdir(swapdir)
686    os.remove(testfile)
687    os.remove(otherfile)
688  end)
689
690  it('(Q)uit at first file argument', function()
691    local chan = fn.jobstart(
692      { nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', init_dir, '--cmd', init_set, testfile },
693      {
694        term = true,
695        env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
696      }
697    )
698    retry(nil, nil, function()
699      eq(
700        '[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:',
701        eval("getline('$')->trim(' ', 2)")
702      )
703    end)
704    api.nvim_chan_send(chan, 'q')
705    expect_exitcode(1)
706  end)
707
708  it('(A)bort at second file argument with -p', function()
709    local chan = fn.jobstart({
710      nvim_prog,
711      '-u',
712      'NONE',
713      '-i',
714      'NONE',
715      '--cmd',
716      init_dir,
717      '--cmd',
718      init_set,
719      '-p',
720      otherfile,
721      testfile,
722    }, {
723      term = true,
724      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
725    })
726    retry(nil, nil, function()
727      eq(
728        '[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:',
729        eval("getline('$')->trim(' ', 2)")
730      )
731    end)
732    api.nvim_chan_send(chan, 'a')
733    expect_exitcode(1)
734  end)
735
736  it('(Q)uit at file opened by -t', function()
737    write_file(
738      otherfile,
739      ([[
740      !_TAG_FILE_ENCODING	utf-8	//
741      first	%s	/^  \zsfirst$/
742      second	%s	/^  \zssecond$/
743      third	%s	/^  \zsthird$/]]):format(testfile, testfile, testfile)
744    )
745    local chan = fn.jobstart({
746      nvim_prog,
747      '-u',
748      'NONE',
749      '-i',
750      'NONE',
751      '--cmd',
752      init_dir,
753      '--cmd',
754      init_set,
755      '--cmd',
756      'set tags=' .. otherfile,
757      '-tsecond',
758    }, {
759      term = true,
760      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
761    })
762    retry(nil, nil, function()
763      eq(
764        '[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:',
765        eval("getline('$')->trim(' ', 2)")
766      )
767    end)
768    api.nvim_chan_send(chan, 'q')
769    expect_exitcode(1)
770  end)
771end)
772
773describe('swapfile', function()
774  it('when using device path #31606', function()
775    t.skip(not is_os('win'), 'N/A: Windows feature')
776    local cwd = vim.fs.normalize(vim.uv.cwd())
777    local drive, path = cwd:sub(1, 1), cwd:sub(3)
778    local swapdir = ('%s/Xtest_swap_dir'):format(cwd)
779    local dos_path = ('%s/file.txt'):format(cwd)
780    local device_quest_path = ('//?/%s'):format(dos_path)
781    clear({
782      args = {
783        '--embed',
784        '--headless',
785        '--cmd',
786        ('set directory=%s//'):format(swapdir),
787        '--',
788        device_quest_path,
789      },
790      merge = false,
791    })
792    local escaped_name = ('%s/%s.swp'):format(swapdir, dos_path:gsub('[:/]', '%%'))
793    eq(escaped_name, fn.swapname('%'))
794
795    command('bw!')
796    api.nvim_buf_set_name(0, dos_path)
797    eq(escaped_name, fn.swapname('%'))
798
799    command('bw!')
800    local device_dot_path = ('//./%s'):format(dos_path)
801    api.nvim_buf_set_name(0, device_dot_path)
802    eq(escaped_name, fn.swapname('%'))
803
804    command('bw!')
805    local device_unc_path = ('//?/UNC/localhost/%s$%s/file.txt'):format(drive, path)
806    api.nvim_buf_set_name(0, device_unc_path)
807    eq(('%s/%%%s.swp'):format(swapdir, device_unc_path:sub(8):gsub('/', '%%')), fn.swapname('%'))
808
809    command('bw!')
810    -- Volume GUID form, like \\?\Volume{d4857377-2ac4-45d8-a4cb-9b2e447fd02e}\
811    local guid = vim.fs.normalize(vim.trim(vim.fn.system(('mountvol %s: /L'):format(drive))))
812    local device_guid_path = ('%s%s/file.txt'):format(guid, path:sub(2))
813    api.nvim_buf_set_name(0, device_guid_path)
814    eq(escaped_name, fn.swapname('%'))
815  end)
816end)