robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
57.5 KiB1917 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4
5local describe, it, before_each, after_each, setup, teardown, finally =
6  t.describe, t.it, t.before_each, t.after_each, t.setup, t.teardown, t.finally
7local assert_alive = n.assert_alive
8local assert_log = t.assert_log
9local clear = n.clear
10local command = n.command
11local ok = t.ok
12local eq = t.eq
13local matches = t.matches
14local eval = n.eval
15local exec = n.exec
16local exec_capture = n.exec_capture
17local exec_lua = n.exec_lua
18local feed = n.feed
19local fn = n.fn
20local pesc = vim.pesc
21local mkdir = t.mkdir
22local mkdir_p = n.mkdir_p
23local nvim_prog = n.nvim_prog
24local nvim_set = n.nvim_set
25local read_file = t.read_file
26local retry = t.retry
27local rmdir = n.rmdir
28local sleep = vim.uv.sleep
29local startswith = vim.startswith
30local write_file = t.write_file
31local api = n.api
32local is_os = t.is_os
33local dedent = t.dedent
34local tbl_map = vim.tbl_map
35local tbl_filter = vim.tbl_filter
36local endswith = vim.endswith
37local check_close = n.check_close
38
39local testlog = 'Xtest-startupspec-log'
40
41describe('startup', function()
42  it('--clean', function()
43    clear()
44    matches(vim.pesc(fn.stdpath('config')), api.nvim_get_option_value('runtimepath', {}))
45
46    clear('--clean')
47    ok(not api.nvim_get_option_value('runtimepath', {}):match(vim.pesc(fn.stdpath('config'))))
48  end)
49
50  it('prevents remote UI infinite loop', function()
51    clear()
52    local screen = Screen.new(84, 3)
53    fn.jobstart(
54      { nvim_prog, '-u', 'NONE', '--server', eval('v:servername'), '--remote-ui' },
55      { term = true }
56    )
57    screen:expect([[
58      ^Cannot attach UI of :terminal child to its parent. (Unset $NVIM to skip this check) |
59      [Process exited 1]                                                                  |
60                                                                                          |
61    ]])
62  end)
63
64  it('--startuptime', function()
65    local testfile = 'Xtest_startuptime'
66    finally(function()
67      os.remove(testfile)
68    end)
69    clear({ args = { '--startuptime', testfile } })
70    assert_log('Embedded', testfile, 100)
71    assert_log('sourcing', testfile, 100)
72    assert_log("require%('vim%._core.editor'%)", testfile, 100)
73  end)
74
75  it('--startuptime does not crash on error #31125', function()
76    local p = n.spawn_wait('--startuptime', '.', '-c', '42cquit')
77    eq("E484: Can't open file .", p.stderr)
78    eq(42, p.status)
79  end)
80
81  it('-D does not hang #12647', function()
82    clear()
83    local screen = Screen.new(60, 7)
84    -- not the same colors on windows for some reason
85    screen._default_attr_ids = nil
86    local id = fn.jobstart({
87      nvim_prog,
88      '-u',
89      'NONE',
90      '-i',
91      'NONE',
92      '--cmd',
93      'set noruler',
94      '-D',
95    }, {
96      term = true,
97      env = {
98        VIMRUNTIME = os.getenv('VIMRUNTIME'),
99      },
100    })
101    screen:expect({ any = pesc('Entering Debug mode.  Type "cont" to continue.') })
102    fn.chansend(id, 'cont\n')
103    screen:expect([[
104      ^                                                            |
105      ~                                                           |*3
106      [No Name]                                                   |
107                                                                  |*2
108    ]])
109  end)
110
111  it(':filetype detect enables filetype detection with -u NONE', function()
112    clear()
113    eq('filetype detection:OFF  plugin:OFF  indent:OFF', exec_capture('filetype'))
114    command('filetype detect')
115    eq('filetype detection:ON  plugin:OFF  indent:OFF', exec_capture('filetype'))
116  end)
117end)
118
119describe('startup', function()
120  before_each(clear)
121
122  after_each(function()
123    check_close()
124    os.remove(testlog)
125  end)
126
127  describe('-l Lua', function()
128    local function assert_l_out(expected, nvim_args, lua_args, script, input)
129      local args = { nvim_prog }
130      vim.list_extend(args, nvim_args or {})
131      vim.list_extend(args, { '-l', (script or 'test/functional/fixtures/startup.lua') })
132      vim.list_extend(args, lua_args or {})
133      local out = fn.system(args, input):gsub('\r\n', '\n')
134      if type(expected) == 'function' then
135        return expected(out)
136      else
137        return eq(dedent(expected), out)
138      end
139    end
140
141    it('outputs the EOF as LF (not CRLF) #36853', function()
142      local args = { nvim_prog, '-l', '-' }
143      local input = 'print("foo")'
144      local out = fn.system(args, input)
145      eq('foo\n', out)
146    end)
147
148    it('failure modes', function()
149      -- nvim -l <empty>
150      local proc = n.spawn_wait('-l')
151      matches('nvim%.?e?x?e?: Argument missing after: "%-l"', proc.stderr)
152      eq(1, proc.status)
153    end)
154
155    it('os.exit() sets Nvim exitcode', function()
156      -- nvim -l foo.lua -arg1 -- a b c
157      assert_l_out(
158        [[
159          bufs:
160          nvim args: 7
161          lua args: { "-arg1", "--exitcode", "73", "--arg2",
162            [0] = "test/functional/fixtures/startup.lua"
163          }
164          ]],
165        {},
166        { '-arg1', '--exitcode', '73', '--arg2' }
167      )
168      eq(73, eval('v:shell_error'))
169    end)
170
171    it('os.exit() runs Nvim teardown', function()
172      local exit_file = t.tmpname(false)
173      finally(function()
174        os.remove(exit_file)
175      end)
176
177      fn.system(
178        {
179          nvim_prog,
180          '-u',
181          'NONE',
182          '-i',
183          'NONE',
184          '--cmd',
185          'set shada=',
186          '-l',
187          '-',
188        },
189        ([[
190        vim.api.nvim_create_autocmd('VimLeave', {
191          callback = function()
192            vim.fn.writefile({ tostring(vim.v.exiting) }, %s)
193          end,
194        })
195        os.exit(73)
196      ]]):format(vim.inspect(exit_file))
197      )
198
199      eq(73, eval('v:shell_error'))
200      eq('73\n', read_file(exit_file))
201    end)
202
203    it('os.exit() fails from libuv process callback #39783', function()
204      local out = fn.system(
205        { nvim_prog, '--clean', '-l', '-' },
206        ([[
207          local callback_called = false
208          local handle
209          handle = assert(vim.uv.spawn(%q, { args = { 'EXIT', '0' } }, function()
210            handle:close()
211            callback_called = true
212            os.exit(73)
213            error('os.exit() returned')
214          end))
215          assert(vim.wait(1000, function()
216            return callback_called
217          end))
218        ]]):format(n.testprg('shell-test'))
219      )
220
221      eq(0, eval('v:shell_error'))
222      matches('E5560: os%.exit must not be called in a fast event context', out)
223    end)
224
225    it('Lua-error sets Nvim exitcode', function()
226      local proc = n.spawn_wait('-l', 'test/functional/fixtures/startup-fail.lua')
227      matches('E5113: .* my pearls!!', (proc:output()))
228      eq(0, proc.signal)
229      eq(1, proc.status)
230
231      eq(0, eval('v:shell_error'))
232      matches(
233        'E5113: .* %[string "error%("whoa"%)"%]:1: whoa',
234        fn.system({ nvim_prog, '-l', '-' }, 'error("whoa")')
235      )
236      eq(1, eval('v:shell_error'))
237    end)
238
239    it('executes stdin "-"', function()
240      assert_l_out(
241        'arg0=- args=2 whoa\n',
242        nil,
243        { 'arg1', 'arg 2' },
244        '-',
245        "print(('arg0=%s args=%d %s'):format(_G.arg[0], #_G.arg, 'whoa'))"
246      )
247      assert_l_out(
248        'biiig input: 1000042\n',
249        nil,
250        nil,
251        '-',
252        ('print("biiig input: "..("%s"):len())'):format(string.rep('x', (1000 * 1000) + 42))
253      )
254      eq(0, eval('v:shell_error'))
255    end)
256
257    it('does not truncate long print() message', function()
258      assert_l_out(('k'):rep(1234) .. '\n', nil, nil, '-', "print(('k'):rep(1234))")
259    end)
260
261    it('does add the expected number of newlines', function()
262      assert_l_out('', nil, nil, '-', '')
263
264      assert_l_out('\n', nil, nil, '-', [[print()]])
265      assert_l_out('\n\n', nil, nil, '-', [[print('\n')]])
266
267      assert_l_out('foobar\n', nil, nil, '-', [[print('foobar')]])
268      assert_l_out('foobar\n\n', nil, nil, '-', [[print('foobar\n')]])
269
270      assert_l_out('foo\nbar\n', nil, nil, '-', [[print('foo')print('bar')]])
271      assert_l_out('foo\n\nbar\n', nil, nil, '-', [[print('foo')print()print('bar')]])
272    end)
273
274    it('preserves escape sequences', function()
275      assert_l_out(
276        'this is \027[31mRED FOR AN AMAZING REASON\027[0m\n',
277        nil,
278        nil,
279        '-',
280        [[print('this is \027[31mRED FOR AN AMAZING REASON\027[0m')]]
281      )
282    end)
283
284    it('sets _G.arg', function()
285      -- nvim -l foo.lua
286      assert_l_out(
287        [[
288          bufs:
289          nvim args: 3
290          lua args: {
291            [0] = "test/functional/fixtures/startup.lua"
292          }
293          ]],
294        {},
295        {}
296      )
297      eq(0, eval('v:shell_error'))
298
299      -- nvim -l foo.lua [args]
300      assert_l_out(
301        [[
302          bufs:
303          nvim args: 7
304          lua args: { "-arg1", "--arg2", "--", "arg3",
305            [0] = "test/functional/fixtures/startup.lua"
306          }
307          ]],
308        {},
309        { '-arg1', '--arg2', '--', 'arg3' }
310      )
311      eq(0, eval('v:shell_error'))
312
313      -- nvim file1 file2 -l foo.lua -arg1 -- file3 file4
314      assert_l_out(
315        [[
316          bufs: file1 file2
317          nvim args: 10
318          lua args: { "-arg1", "arg 2", "--", "file3", "file4",
319            [0] = "test/functional/fixtures/startup.lua"
320          }
321          ]],
322        { 'file1', 'file2' },
323        { '-arg1', 'arg 2', '--', 'file3', 'file4' }
324      )
325      eq(0, eval('v:shell_error'))
326
327      -- nvim -l foo.lua <vim args>
328      assert_l_out(
329        [[
330          bufs:
331          nvim args: 5
332          lua args: { "-c", "set wrap?",
333            [0] = "test/functional/fixtures/startup.lua"
334          }
335          ]],
336        {},
337        { '-c', 'set wrap?' }
338      )
339      eq(0, eval('v:shell_error'))
340
341      -- nvim <vim args> -l foo.lua <vim args>
342      assert_l_out(
343        [[
344            wrap
345          bufs:
346          nvim args: 7
347          lua args: { "-c", "set wrap?",
348            [0] = "test/functional/fixtures/startup.lua"
349          }
350          ]],
351        { '-c', 'set wrap?' },
352        { '-c', 'set wrap?' }
353      )
354      eq(0, eval('v:shell_error'))
355    end)
356
357    it('disables swapfile/shada/config/plugins unless overridden', function()
358      local script = [[print(('updatecount=%d shadafile=%s loadplugins=%s scripts=%d'):format(
359                       vim.o.updatecount, vim.o.shadafile, tostring(vim.o.loadplugins), math.max(1, #vim.fn.getscriptinfo())))]]
360      finally(function()
361        os.remove('Xtest_shada')
362      end)
363
364      assert_l_out(function(out)
365        -- Accept scripts=2 for PUC Lua where `vim._core.util` is sourced from disk instead of a preload blob.
366        return matches('updatecount=0 shadafile=NONE loadplugins=false scripts=[12]\n', out)
367      end, nil, nil, '-', script)
368
369      -- User can override.
370      assert_l_out(
371        function(out)
372          return matches('updatecount=99 shadafile=Xtest_shada loadplugins=true scripts=2%d\n', out)
373        end,
374        { '+set updatecount=99', '-i', 'Xtest_shada', '+set loadplugins', '-u', 'NORC' },
375        nil,
376        '-',
377        script
378      )
379    end)
380  end)
381
382  it('--cmd/-c/+ do not truncate long Lua print() message with --headless', function()
383    local out = fn.system({
384      nvim_prog,
385      '-u',
386      'NONE',
387      '-i',
388      'NONE',
389      '--headless',
390      '--cmd',
391      'lua print(("A"):rep(1234))',
392      '-c',
393      'lua print(("B"):rep(1234))',
394      '+lua print(("C"):rep(1234))',
395      '+q',
396    })
397
398    eq(('A'):rep(1234) .. '\n' .. ('B'):rep(1234) .. '\n' .. ('C'):rep(1234) .. '\n', out)
399  end)
400
401  it('pipe at both ends: has("ttyin")==0 has("ttyout")==0', function()
402    -- system() puts a pipe at both ends.
403    local out = fn.system({
404      nvim_prog,
405      '-u',
406      'NONE',
407      '-i',
408      'NONE',
409      '--headless',
410      '--cmd',
411      nvim_set,
412      '-c',
413      [[echo has('ttyin') has('ttyout')]],
414      '+q',
415    })
416    eq('0 0', out)
417  end)
418
419  it('with --embed: has("ttyin")==0 has("ttyout")==0', function()
420    local screen = Screen.new(25, 3)
421    -- Remote UI connected by --embed.
422    -- TODO: a lot of tests in this file already use the new default color scheme.
423    -- once we do the batch update of tests to use it, remove this workaround
424    screen._default_attr_ids = nil
425    command([[echo has('ttyin') has('ttyout')]])
426    screen:expect([[
427      ^                         |
428      ~                        |
429      0 0                      |
430    ]])
431  end)
432
433  it('in a TTY: has("ttyin")==1 has("ttyout")==1', function()
434    local screen = Screen.new(25, 4)
435    screen._default_attr_ids = nil
436    if is_os('win') then
437      command([[set shellcmdflag=/s\ /c shellxquote=\"]])
438    end
439    -- Running in :terminal
440    fn.jobstart({
441      nvim_prog,
442      '-u',
443      'NONE',
444      '-i',
445      'NONE',
446      '--cmd',
447      nvim_set,
448      '-c',
449      'echo has("ttyin") has("ttyout")',
450    }, {
451      term = true,
452      env = {
453        VIMRUNTIME = os.getenv('VIMRUNTIME'),
454      },
455    })
456    screen:expect([[
457      ^                         |
458      ~                        |
459      1 1                      |
460                               |
461    ]])
462  end)
463
464  it('output to pipe: has("ttyin")==1 has("ttyout")==0', function()
465    clear({ env = { NVIM_LOG_FILE = testlog } })
466    if is_os('win') then
467      command([[set shellcmdflag=/s\ /c shellxquote=\"]])
468    end
469    os.remove('Xtest_startup_ttyout')
470    finally(function()
471      os.remove('Xtest_startup_ttyout')
472    end)
473    -- Running in :terminal
474    fn.jobstart(
475      (
476        [["%s" -u NONE -i NONE --cmd "%s"]]
477        .. [[ -c "call writefile([has('ttyin'), has('ttyout')], 'Xtest_startup_ttyout')"]]
478        .. [[ -c q | cat -v]]
479      ):format(nvim_prog, nvim_set),
480      {
481        term = true,
482        env = {
483          VIMRUNTIME = os.getenv('VIMRUNTIME'),
484        },
485      }
486    )
487    retry(nil, 3000, function()
488      sleep(1)
489      eq(
490        '1\n0\n', -- stdin is a TTY, stdout is a pipe
491        read_file('Xtest_startup_ttyout')
492      )
493    end)
494  end)
495
496  it('input from pipe: has("ttyin")==0 has("ttyout")==1', function()
497    clear({ env = { NVIM_LOG_FILE = testlog } })
498    if is_os('win') then
499      command([[set shellcmdflag=/s\ /c shellxquote=\"]])
500    end
501    os.remove('Xtest_startup_ttyout')
502    finally(function()
503      os.remove('Xtest_startup_ttyout')
504    end)
505    -- Running in :terminal
506    fn.jobstart(
507      (
508        [[echo foo | ]] -- Input from a pipe.
509        .. [["%s" -u NONE -i NONE --cmd "%s"]]
510        .. [[ -c "call writefile([has('ttyin'), has('ttyout')], 'Xtest_startup_ttyout')"]]
511        .. [[ -c q -- -]]
512      ):format(nvim_prog, nvim_set),
513      {
514        term = true,
515        env = {
516          VIMRUNTIME = os.getenv('VIMRUNTIME'),
517        },
518      }
519    )
520    retry(nil, 3000, function()
521      sleep(1)
522      eq(
523        '0\n1\n', -- stdin is a pipe, stdout is a TTY
524        read_file('Xtest_startup_ttyout')
525      )
526    end)
527  end)
528
529  it('input from pipe (implicit) #7679', function()
530    clear({ env = { NVIM_LOG_FILE = testlog } })
531    local screen = Screen.new(25, 4)
532    screen._default_attr_ids = nil
533    if is_os('win') then
534      command([[set shellcmdflag=/s\ /c shellxquote=\"]])
535    end
536    -- Running in :terminal
537    fn.jobstart(
538      (
539        [[echo foo | ]]
540        .. [["%s" -u NONE -i NONE --cmd "%s"]]
541        .. [[ -c "echo has('ttyin') has('ttyout')"]]
542      ):format(nvim_prog, nvim_set),
543      {
544        term = true,
545        env = {
546          VIMRUNTIME = os.getenv('VIMRUNTIME'),
547        },
548      }
549    )
550    screen:expect([[
551      ^foo                      |
552      ~                        |
553      0 1                      |
554                               |
555    ]])
556    if not is_os('win') then
557      assert_log('Failed to get flags on descriptor 3: Bad file descriptor', testlog, 100)
558    end
559  end)
560
561  it('input from pipe + file args #7679', function()
562    eq(
563      'ohyeah\n0 0 bufs=3',
564      fn.system({
565        nvim_prog,
566        '-n',
567        '-u',
568        'NONE',
569        '-i',
570        'NONE',
571        '--headless',
572        '+.print',
573        "+echo has('ttyin') has('ttyout') 'bufs='.bufnr('$')",
574        '+qall!',
575        '-',
576        'test/functional/fixtures/tty-test.c',
577        'test/functional/fixtures/shell-test.c',
578      }, { 'ohyeah', '' })
579    )
580  end)
581
582  it('if stdin is empty: selects buffer 2, deletes buffer 1 #8561', function()
583    eq(
584      '\n  2 %a   "file1"                        line 0\n  3      "file2"                        line 0',
585      fn.system({
586        nvim_prog,
587        '-n',
588        '-u',
589        'NONE',
590        '-i',
591        'NONE',
592        '--headless',
593        '+ls!',
594        '+qall!',
595        '-',
596        'file1',
597        'file2',
598      }, { '' })
599    )
600  end)
601
602  it('if stdin is empty and - is last: selects buffer 1, deletes buffer 3 #35269', function()
603    eq(
604      '\n  1 %a   "file1"                        line 0\n  2      "file2"                        line 0',
605      fn.system({
606        nvim_prog,
607        '-n',
608        '-u',
609        'NONE',
610        '-i',
611        'NONE',
612        '--headless',
613        '+ls!',
614        '+qall!',
615        'file1',
616        'file2',
617        '-',
618      }, { '' })
619    )
620  end)
621
622  it("empty stdin with terminal split doesn't crash #35681", function()
623    eq(
624      'nocrash',
625      fn.system({
626        nvim_prog,
627        '-n',
628        '-u',
629        'NONE',
630        '-i',
631        'NONE',
632        '--headless',
633        '--cmd',
634        'term',
635        '+split',
636        '+quit!',
637        '+bw!',
638        '+bw!',
639        '+echo "nocrash"',
640        "+call timer_start(1, { -> execute('qa') })", -- need to let event handling happen
641        '-',
642      }, { '' })
643    )
644  end)
645
646  it('stdin with -es/-Es #7679', function()
647    local input = { 'append', 'line1', 'line2', '.', '%print', '' }
648    local inputstr = table.concat(input, '\n')
649
650    --
651    -- -Es: read stdin as text
652    --
653    eq(
654      'partylikeits1999\n',
655      fn.system({
656        nvim_prog,
657        '-n',
658        '-u',
659        'NONE',
660        '-i',
661        'NONE',
662        '-Es',
663        '+.print',
664        'test/functional/fixtures/tty-test.c',
665      }, { 'partylikeits1999', '' })
666    )
667    eq(inputstr, fn.system({ nvim_prog, '-i', 'NONE', '-Es', '+%print', '-' }, input))
668    -- with `-u NORC`
669    eq(
670      'thepartycontinues\n',
671      fn.system({ nvim_prog, '-n', '-u', 'NORC', '-Es', '+.print' }, { 'thepartycontinues', '' })
672    )
673    -- without `-u`
674    eq(
675      'thepartycontinues\n',
676      fn.system({ nvim_prog, '-n', '-Es', '+.print' }, { 'thepartycontinues', '' })
677    )
678
679    --
680    -- -es: read stdin as ex-commands
681    --
682    eq(
683      '  encoding=utf-8\n',
684      fn.system({
685        nvim_prog,
686        '-n',
687        '-u',
688        'NONE',
689        '-i',
690        'NONE',
691        '-es',
692        'test/functional/fixtures/tty-test.c',
693      }, { 'set encoding', '' })
694    )
695    eq('line1\nline2\n', fn.system({ nvim_prog, '-i', 'NONE', '-es', '-' }, input))
696    -- with `-u NORC`
697    eq(
698      '  encoding=utf-8\n',
699      fn.system({ nvim_prog, '-n', '-u', 'NORC', '-es' }, { 'set encoding', '' })
700    )
701    -- without `-u`
702    eq('  encoding=utf-8\n', fn.system({ nvim_prog, '-n', '-es' }, { 'set encoding', '' }))
703    -- CRLF input (e.g. Windows pipes) works like LF.
704    eq('  encoding=utf-8\n', fn.system({ nvim_prog, '-n', '-es' }, 'set encoding\r\n'))
705    -- Stdin is not consumed as typeahead: `:lua` can read the next stdin line as data.
706    eq(
707      'thedata\n',
708      fn.system(
709        { nvim_prog, '-n', '-u', 'NONE', '-i', 'NONE', '-es' },
710        { 'lua vim.g.d = io.read()', 'thedata', 'put =g:d', 'print', '' }
711      )
712    )
713
714    -- Cursor starts at the last line (POSIX ex): ed-style "a" appends at end-of-file.
715    write_file('Xesfile', 'L1\nL2\n')
716    finally(function()
717      os.remove('Xesfile')
718    end)
719    eq(
720      'L1\nL2\nX\n',
721      fn.system(
722        { nvim_prog, '-n', '-u', 'NONE', '-i', 'NONE', '-es', 'Xesfile' },
723        { 'a', 'X', '.', '%print', '' }
724      )
725    )
726
727    -- In a terminal, "-es" executes +cmds and exits; it doesn't wait for input.
728    local screen = Screen.new(60, 6)
729    fn.jobstart({ nvim_prog, '-u', 'NONE', '-i', 'NONE', '-es', '-V1', '+echo "hello"' }, {
730      term = true,
731      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
732    })
733    -- "nvim -es" output ends with a final newline.
734    screen:expect([[
735      ^hello                                                       |
736                                                                  |
737      [Process exited 0]                                          |
738                                                                  |*3
739    ]])
740  end)
741
742  it('-es/-Es disables swapfile/shada/config #8540', function()
743    for _, arg in ipairs({ '-es', '-Es' }) do
744      local out = fn.system({
745        nvim_prog,
746        arg,
747        '+set updatecount? shadafile? loadplugins?',
748        '+put =map(getscriptinfo(), {-> v:val.name})',
749        '+%print',
750      })
751      local line1 = string.match(out, '^.-\n')
752      -- updatecount=0 means swapfile was disabled.
753      eq('  updatecount=0  shadafile=NONE  loadplugins\n', line1)
754      -- Standard plugins were loaded, but not user config. #31878
755      local nrlines = #vim.split(out, '\n')
756      ok(nrlines > 20, '>20', nrlines)
757      ok(string.find(out, 'man.lua') ~= nil)
758      ok(string.find(out, 'init.vim') == nil)
759    end
760  end)
761
762  it('fails on --embed with -es/-Es/-l', function()
763    matches(
764      'nvim[.exe]*: %-%-embed conflicts with %-es/%-Es/%-l',
765      n.spawn_wait('--embed', '-es').stderr
766    )
767    matches(
768      'nvim[.exe]*: %-%-embed conflicts with %-es/%-Es/%-l',
769      n.spawn_wait('--embed', '-Es').stderr
770    )
771    matches(
772      'nvim[.exe]*: %-%-embed conflicts with %-es/%-Es/%-l',
773      n.spawn_wait('--embed', '-l', 'foo.lua').stderr
774    )
775  end)
776
777  it('-es does not exit early with closed stdin', function()
778    write_file('Xinput.txt', 'line1\nline2\nline3\nline4\n')
779    write_file('Xoutput.txt', 'OUT\n')
780    finally(function()
781      os.remove('Xinput.txt')
782      os.remove('Xoutput.txt')
783    end)
784    -- Use system() without input so that stdin is closed.
785    fn.system({
786      nvim_prog,
787      '--clean',
788      '-es',
789      '-c',
790      [[g/^/.w >>Xoutput.txt]],
791      'Xinput.txt',
792    })
793    eq('OUT\nline1\nline2\nline3\nline4\n', read_file('Xoutput.txt'))
794  end)
795
796  it('ENTER dismisses early message #7967', function()
797    local screen
798    screen = Screen.new(60, 6)
799    screen._default_attr_ids = nil
800    local id = fn.jobstart({
801      nvim_prog,
802      '-u',
803      'NONE',
804      '-i',
805      'NONE',
806      '--cmd',
807      'set noruler',
808      '--cmd',
809      'let g:foo = g:bar',
810    }, {
811      term = true,
812      env = {
813        VIMRUNTIME = os.getenv('VIMRUNTIME'),
814      },
815    })
816    screen:expect([[
817      ^                                                            |
818                                                                  |
819      Error in pre-vimrc command line:                            |
820      E121: Undefined variable: g:bar                             |
821      Press ENTER or type command to continue                     |
822                                                                  |
823    ]])
824    fn.chansend(id, '\n')
825    screen:expect([[
826      ^                                                            |
827      ~                                                           |*2
828      [No Name]                                                   |
829                                                                  |*2
830    ]])
831  end)
832
833  it('-r works without --headless in PTY #23294', function()
834    exec([[
835      func Normalize(data) abort
836        " Windows: remove ^M and term escape sequences
837        return mapnew(a:data, 'substitute(substitute(v:val, "\r", "", "g"), "\x1b\\%(\\]\\d\\+;.\\{-}\x07\\|\\[.\\{-}[\x40-\x7E]\\)", "", "g")')
838      endfunc
839      func OnOutput(id, data, event) dict
840        let g:stdout = Normalize(a:data)
841      endfunc
842      call jobstart([v:progpath, '-u', 'NONE', '-i', 'NONE', '-r'], {
843      \ 'pty': v:true,
844      \ 'stdout_buffered': v:true,
845      \ 'on_stdout': function('OnOutput'),
846      \ })
847    ]])
848    retry(nil, nil, function()
849      eq('Swap files found:', eval('g:stdout[0]'))
850    end)
851  end)
852
853  it('fixed hang issue with --headless (#11386)', function()
854    local expected = ''
855    local period = 100
856    for i = 1, period - 1 do
857      expected = expected .. i .. '\n'
858    end
859    expected = expected .. period
860    eq(
861      expected,
862      -- FIXME(codehex): We should really set a timeout for the system function.
863      -- If this test fails, there will be a waiting input state.
864      fn.system({
865        nvim_prog,
866        '-u',
867        'NONE',
868        '-c',
869        'for i in range(1, 100) | echo i | endfor | quit',
870        '--headless',
871      })
872    )
873  end)
874
875  it('get command line arguments from v:argv', function()
876    local p = n.spawn_wait('--cmd', nvim_set, '-c', [[echo v:argv[-1:] len(v:argv) > 1]], '+q')
877    eq("['+q'] 1", p.stderr)
878  end)
879end)
880
881describe('startup', function()
882  it('-e/-E interactive #7679', function()
883    clear('-e')
884    local screen = Screen.new(40, 12)
885    feed("put ='from -e'<CR>")
886    screen:expect([[
887                                              |
888      from -e                                 |
889      {1:~                                       }|*6
890      {2:[No Name] [+]                           }|
891      {1::}^                                       |
892      {3:[Ex mode]                               }|
893      {5:-- INSERT --}                            |
894    ]])
895
896    clear('-E')
897    screen = Screen.new(40, 12)
898    feed("put ='from -E'<CR>")
899    screen:expect([[
900                                              |
901      from -E                                 |
902      {1:~                                       }|*6
903      {2:[No Name] [+]                           }|
904      {1::}^                                       |
905      {3:[Ex mode]                               }|
906      {5:-- INSERT --}                            |
907    ]])
908  end)
909
910  it('-e enters Ex mode at startup', function()
911    clear('-e')
912    local screen = Screen.new(40, 12)
913    -- The keep-open cmdwin REPL is focused, in Insert mode. #40962
914    screen:expect({ any = vim.pesc('[Ex mode]') })
915    eq(':', fn.getcmdwintype())
916    feed('visual<CR>')
917    eq('n', fn.mode(1))
918    eq('', fn.getcmdwintype())
919
920    -- Scripts can detect batch mode ("-es"): mode() is "cv".
921    eq('cv\n', fn.system({ nvim_prog, '-n', '-es' }, { 'put =mode(1)', 'print', '' }))
922  end)
923
924  it('-d does not diff non-arglist windows #13720 #21289', function()
925    write_file(
926      'Xdiff.vim',
927      [[
928      let bufnr = nvim_create_buf(0, 1)
929      let config = {
930            \   'relative': 'editor',
931            \   'focusable': v:false,
932            \   'width': 1,
933            \   'height': 1,
934            \   'row': 3,
935            \   'col': 3
936            \ }
937      autocmd WinEnter * let g:float_win = nvim_open_win(bufnr, v:false, config)
938    ]]
939    )
940    finally(function()
941      os.remove('Xdiff.vim')
942    end)
943    clear { args = { '-u', 'Xdiff.vim', '-d', 'Xdiff.vim', 'Xdiff.vim' } }
944    eq(true, api.nvim_get_option_value('diff', { win = fn.win_getid(1) }))
945    eq(true, api.nvim_get_option_value('diff', { win = fn.win_getid(2) }))
946    local float_win = eval('g:float_win')
947    eq('editor', api.nvim_win_get_config(float_win).relative)
948    eq(false, api.nvim_get_option_value('diff', { win = float_win }))
949  end)
950
951  it('still opens arglist windows if init only opens floating windows', function()
952    write_file(
953      'Xfloat.vim',
954      [[
955      let config = {
956            \   'relative': 'editor',
957            \   'focusable': v:false,
958            \   'width': 1,
959            \   'height': 1,
960            \   'row': 1,
961            \   'col': 1
962            \ }
963      call nvim_open_win(0, v:false, config)
964    ]]
965    )
966    finally(function()
967      os.remove('Xfloat.vim')
968    end)
969    clear { args = { '-u', 'Xfloat.vim', '-d', 'Xfloat.vim', 'foo' } }
970    local screen = Screen.new(40, 5)
971    screen:add_extra_attr_ids({
972      [101] = {
973        bold = true,
974        background = Screen.colors.LightBlue,
975        foreground = Screen.colors.Brown,
976      },
977      [102] = { foreground = Screen.colors.SlateBlue, background = Screen.colors.LightBlue },
978      [103] = { foreground = Screen.colors.Magenta, background = Screen.colors.LightBlue },
979      [104] = { foreground = Screen.colors.DarkCyan, background = Screen.colors.LightBlue },
980    })
981    screen:expect([[
982      {7:  }{101:^let}{22: config }{101:=}{22: }{102:{}{22:                      }│{23:-}|
983      {7: }{101:l}{22:      }{102:\}{22:   }{103:'relative'}{22:: }{103:'editor'}{22:,     }│{23:-}|
984      {7:  }{22:      }{102:\}{22:   }{103:'focusable'}{22:: }{104:v:}{22:false,     }│ |
985      {3:Xfloat.vim                             }{2:<}|
986                                              |
987    ]])
988  end)
989
990  it("default 'diffopt' is applied with -d", function()
991    clear({
992      args = {
993        '-d',
994        'test/functional/fixtures/diff/startup_old.txt',
995        'test/functional/fixtures/diff/startup_new.txt',
996        '--cmd',
997        'set laststatus=0',
998      },
999    })
1000    local screen = Screen.new(80, 24)
1001    screen:expect([[
1002      {7:+ }{13:^+-- 15 lines: package main············}│{7:+ }{13:+-- 15 lines: package main···········}|
1003      {7:  }                                      │{7:  }                                     |
1004      {7:  }func printCharacters(str string) strin│{7:  }func printCharacters(str string) stri|
1005      {7:  }        return str                    │{7:  }        return str                   |
1006      {7:  }}                                     │{7:  }}                                    |
1007      {7:  }                                      │{7:  }                                     |
1008      {7:  }func main() {                         │{7:  }func main() {                        |
1009      {7:  }{23:--------------------------------------}│{7:  }{22:        hello := "Hello, World!"     }|
1010      {7:  }{23:--------------------------------------}│{7:  }{22:                                     }|
1011      {7:  }{4:        fmt.Print}{27:Ln}{4:(compressString("aa}│{7:  }{4:        fmt.Print(compressString("aaa}|
1012      {7:  }{4:        fmt.Print}{27:Ln}{4:(compressString("go}│{7:  }{4:        fmt.Print(compressString("gol}|
1013      {7:  }{4:        fmt.Print}{27:Ln}{4:(removeDuplicate("a}│{7:  }{4:        fmt.Print(removeDuplicate("aa}|
1014      {7:  }{4:        fmt.Print}{27:Ln}{4:(reverseAndDouble("}│{7:  }{4:        fmt.Print(reverseAndDouble("a}|
1015      {7:  }{4:        fmt.Print}{27:Ln}{4:(printCharacters("g}│{7:  }{4:        fmt.Print(printCharacters("go}|
1016      {7:  }{23:--------------------------------------}│{7:  }{22:                                     }|
1017      {7:  }{23:--------------------------------------}│{7:  }{22:        fmt.Println(hello)           }|
1018      {7:  }}                                     │{7:  }}                                    |
1019      {1:~                                       }│{1:~                                      }|*6
1020                                                                                      |
1021    ]])
1022    command('let &diffopt = &diffopt')
1023    screen:expect_unchanged()
1024  end)
1025
1026  it('does not crash if --embed is given twice', function()
1027    clear { args = { '--embed' } }
1028    assert_alive()
1029  end)
1030
1031  it('does not crash when expanding cdpath during early_init', function()
1032    clear { env = { CDPATH = '~doesnotexist' } }
1033    assert_alive()
1034    eq(',~doesnotexist', eval('&cdpath'))
1035  end)
1036
1037  it("sets 'shortmess' when loading other tabs", function()
1038    clear({ args = { '-p', 'a', 'b', 'c' } })
1039    local screen = Screen.new(25, 4)
1040    screen:expect([[
1041      {5: a }{24: b  c }{2:               }{24:X}|
1042      ^                         |
1043      {1:~                        }|
1044                               |
1045    ]])
1046  end)
1047
1048  describe('opening a terminal before buffers are loaded #30765', function()
1049    local lines = {} --- @type string[]
1050    for i = 1, 50 do
1051      lines[#lines + 1] = ('line%d'):format(i)
1052    end
1053
1054    setup(function()
1055      write_file('Xsomefile', table.concat(lines, '\n') .. '\n')
1056    end)
1057
1058    teardown(function()
1059      os.remove('Xsomefile')
1060    end)
1061
1062    it('sends buffer content to terminal with nvim_open_term()', function()
1063      clear({
1064        args_rm = { '--headless' },
1065        args = {
1066          'Xsomefile',
1067          '--cmd',
1068          'let g:chan = nvim_open_term(0, {}) | startinsert',
1069          '--cmd',
1070          'call chansend(g:chan, "new_line1\nnew_line2\nnew_line3")',
1071        },
1072      })
1073      local screen = Screen.new(50, 7)
1074      screen:expect([[
1075        line48                                            |
1076        line49                                            |
1077        line50                                            |
1078        new_line1                                         |
1079        new_line2                                         |
1080        new_line3^                                         |
1081        {5:-- TERMINAL --}                                    |
1082      ]])
1083      eq(lines, api.nvim_buf_get_lines(0, 0, #lines, true))
1084    end)
1085
1086    it('does not error with jobstart(…,{term=true})', function()
1087      clear({
1088        args_rm = { '--headless' },
1089        args = {
1090          'Xsomefile',
1091          '--cmd',
1092          ('lua vim.fn.jobstart({%q}, {term = true})'):format(n.testprg('tty-test')),
1093        },
1094      })
1095      local screen = Screen.new(50, 7)
1096      screen:expect([[
1097        ^tty ready                                         |
1098                                                          |*6
1099      ]])
1100    end)
1101  end)
1102end)
1103
1104describe('startup', function()
1105  local function pack_clear(cmd)
1106    -- add packages after config dir in rtp but before config/after
1107    clear {
1108      args = {
1109        '--cmd',
1110        'set packpath=test/functional/fixtures',
1111        '--cmd',
1112        'let paths=split(&rtp, ",")',
1113        '--cmd',
1114        'let &rtp = paths[0]..",test/functional/fixtures,test/functional/fixtures/middle,"..join(paths[1:],",")',
1115        '--cmd',
1116        cmd,
1117      },
1118      env = { XDG_CONFIG_HOME = 'test/functional/fixtures/' },
1119      args_rm = { 'runtimepath' },
1120    }
1121  end
1122
1123  it('handles &packpath during startup', function()
1124    pack_clear [[
1125      let g:x = bar#test()
1126      let g:y = leftpad#pad("heyya")
1127    ]]
1128    eq(-3, eval 'g:x')
1129    eq('  heyya', eval 'g:y')
1130
1131    pack_clear [[ lua _G.y = require'bar'.doit() _G.z = require'leftpad''howdy' ]]
1132    eq({ 9003, '\thowdy' }, exec_lua [[ return { _G.y, _G.z } ]])
1133  end)
1134
1135  it('handles require from &packpath in an async handler', function()
1136    -- NO! you cannot just speed things up by calling async functions during startup!
1137    -- It doesn't make anything actually faster! NOOOO!
1138    pack_clear [[ lua require'async_leftpad'('brrrr', 'async_res') ]]
1139
1140    -- haha, async leftpad go brrrrr
1141    eq('\tbrrrr', exec_lua [[ return _G.async_res ]])
1142  end)
1143
1144  it('handles :packadd during startup', function()
1145    -- control group: opt/bonus is not available by default
1146    pack_clear [[
1147      try
1148        let g:x = bonus#secret()
1149      catch
1150        let g:err = v:exception
1151      endtry
1152    ]]
1153    eq('Vim(let):E117: Unknown function: bonus#secret', eval 'g:err')
1154
1155    pack_clear [[ lua _G.test = {pcall(function() require'bonus'.launch() end)} ]]
1156    eq(
1157      { false, [[[string ":lua"]:1: module 'bonus' not found:]] },
1158      exec_lua [[ _G.test[2] = string.gsub(_G.test[2], '[\r\n].*', '') return _G.test ]]
1159    )
1160
1161    -- ok, time to launch the nukes:
1162    pack_clear [[ packadd! bonus | let g:x = bonus#secret() ]]
1163    eq('halloj', eval 'g:x')
1164
1165    pack_clear [[ packadd! bonus | lua _G.y = require'bonus'.launch() ]]
1166    eq('CPE 1704 TKS', exec_lua [[ return _G.y ]])
1167  end)
1168
1169  it('handles the correct order with start packages and after/', function()
1170    pack_clear [[ lua _G.test_loadorder = {} vim.cmd "runtime! filen.lua" ]]
1171    eq(
1172      { 'ordinary', 'FANCY', 'mittel', 'FANCY after', 'ordinary after' },
1173      exec_lua [[ return _G.test_loadorder ]]
1174    )
1175  end)
1176
1177  it('handles the correct order with start packages and after/ after startup', function()
1178    pack_clear [[ lua _G.test_loadorder = {} ]]
1179    command [[ runtime! filen.lua ]]
1180    eq(
1181      { 'ordinary', 'FANCY', 'mittel', 'FANCY after', 'ordinary after' },
1182      exec_lua [[ return _G.test_loadorder ]]
1183    )
1184  end)
1185
1186  it('handles the correct order with globpath(&rtp, ...)', function()
1187    pack_clear [[ set loadplugins | lua _G.test_loadorder = {} ]]
1188    command [[
1189      for x in globpath(&rtp, "filen.lua",1,1)
1190        call v:lua.dofile(x)
1191      endfor
1192    ]]
1193    eq(
1194      { 'ordinary', 'FANCY', 'mittel', 'FANCY after', 'ordinary after' },
1195      exec_lua [[ return _G.test_loadorder ]]
1196    )
1197
1198    local rtp = api.nvim_get_option_value('rtp', {})
1199    ok(
1200      startswith(
1201        rtp,
1202        'test/functional/fixtures/nvim,test/functional/fixtures/pack/*/start/*,test/functional/fixtures/start/*,test/functional/fixtures,test/functional/fixtures/middle,'
1203      ),
1204      'startswith(…)',
1205      'rtp=' .. rtp
1206    )
1207  end)
1208
1209  it('handles the correct order with opt packages and after/', function()
1210    pack_clear [[ lua _G.test_loadorder = {} vim.cmd "packadd! superspecial\nruntime! filen.lua" ]]
1211    eq({
1212      'ordinary',
1213      'SuperSpecial',
1214      'FANCY',
1215      'mittel',
1216      'FANCY after',
1217      'SuperSpecial after',
1218      'ordinary after',
1219    }, exec_lua [[ return _G.test_loadorder ]])
1220  end)
1221
1222  it('handles the correct order with opt packages and after/ after startup', function()
1223    pack_clear [[ lua _G.test_loadorder = {} ]]
1224    command [[
1225      packadd! superspecial
1226      runtime! filen.lua
1227    ]]
1228    eq({
1229      'ordinary',
1230      'SuperSpecial',
1231      'FANCY',
1232      'mittel',
1233      'FANCY after',
1234      'SuperSpecial after',
1235      'ordinary after',
1236    }, exec_lua [[ return _G.test_loadorder ]])
1237  end)
1238
1239  it('does an incremental update for packadd', function()
1240    pack_clear [[ lua _G.test_loadorder = {} ]]
1241    command [[
1242      " need to use the runtime to make the initial cache:
1243      runtime! non_exist_ent
1244      " this should now incrementally update it:
1245      packadd! superspecial
1246    ]]
1247
1248    local check = api.nvim__runtime_inspect()
1249    local check_copy = vim.deepcopy(check)
1250    local any_incremental = false
1251    for _, item in ipairs(check_copy) do
1252      any_incremental = any_incremental or item.pack_inserted
1253      item.pack_inserted = nil
1254    end
1255    eq(true, any_incremental, 'no pack_inserted in ' .. vim.inspect(check))
1256
1257    command [[
1258      let &rtp = &rtp
1259      runtime! phantom_ghost
1260    ]]
1261
1262    local new_check = api.nvim__runtime_inspect()
1263    eq(check_copy, new_check)
1264
1265    command [[ runtime! filen.lua ]]
1266    eq({
1267      'ordinary',
1268      'SuperSpecial',
1269      'FANCY',
1270      'mittel',
1271      'FANCY after',
1272      'SuperSpecial after',
1273      'ordinary after',
1274    }, exec_lua [[ return _G.test_loadorder ]])
1275  end)
1276
1277  it('handles the correct order with opt packages and globpath(&rtp, ...)', function()
1278    pack_clear [[ set loadplugins | lua _G.test_loadorder = {} ]]
1279    command [[
1280      packadd! superspecial
1281      for x in globpath(&rtp, "filen.lua",1,1)
1282        call v:lua.dofile(x)
1283      endfor
1284    ]]
1285    eq({
1286      'ordinary',
1287      'SuperSpecial',
1288      'FANCY',
1289      'mittel',
1290      'SuperSpecial after',
1291      'FANCY after',
1292      'ordinary after',
1293    }, exec_lua [[ return _G.test_loadorder ]])
1294  end)
1295
1296  it('handles the correct order with a package that changes packpath', function()
1297    pack_clear [[ lua _G.test_loadorder = {} vim.cmd "packadd! funky\nruntime! filen.lua" ]]
1298    eq(
1299      { 'ordinary', 'funky!', 'FANCY', 'mittel', 'FANCY after', 'ordinary after' },
1300      exec_lua [[ return _G.test_loadorder ]]
1301    )
1302    eq({ 'ordinary', 'funky!', 'mittel', 'ordinary after' }, exec_lua [[ return _G.nested_order ]])
1303  end)
1304
1305  it('handles the correct order when prepending packpath', function()
1306    clear {
1307      args = {
1308        '--cmd',
1309        'set packpath^=test/functional/fixtures',
1310        '--cmd',
1311        [[ lua _G.test_loadorder = {} vim.cmd "runtime! filen.lua" ]],
1312      },
1313      env = { XDG_CONFIG_HOME = 'test/functional/fixtures/' },
1314    }
1315    eq(
1316      { 'ordinary', 'FANCY', 'FANCY after', 'ordinary after' },
1317      exec_lua [[ return _G.test_loadorder ]]
1318    )
1319  end)
1320
1321  it('window widths are correct when modelines set &columns with tabpages', function()
1322    write_file('Xtab1.noft', 'vim: columns=81')
1323    write_file('Xtab2.noft', 'vim: columns=81')
1324    finally(function()
1325      os.remove('Xtab1.noft')
1326      os.remove('Xtab2.noft')
1327    end)
1328    clear({ args = { '-p', 'Xtab1.noft', 'Xtab2.noft' } })
1329    eq(81, api.nvim_win_get_width(0))
1330    command('tabnext')
1331    eq(81, api.nvim_win_get_width(0))
1332  end)
1333end)
1334
1335describe('sysinit', function()
1336  local xdgdir = 'Xxdg'
1337  local vimdir = 'Xvim'
1338  local xhome = 'Xhome'
1339
1340  before_each(function()
1341    rmdir(xdgdir)
1342    rmdir(vimdir)
1343    rmdir(xhome)
1344
1345    mkdir(xdgdir)
1346    mkdir(('%s/nvim'):format(xdgdir))
1347    write_file(
1348      ('%s/nvim/sysinit.vim'):format(xdgdir),
1349      [[
1350      let g:loaded = get(g:, "loaded", 0) + 1
1351      let g:xdg = 1
1352    ]]
1353    )
1354
1355    mkdir(vimdir)
1356    write_file(
1357      ('%s/sysinit.vim'):format(vimdir),
1358      [[
1359      let g:loaded = get(g:, "loaded", 0) + 1
1360      let g:vim = 1
1361    ]]
1362    )
1363
1364    mkdir(xhome)
1365  end)
1366  after_each(function()
1367    rmdir(xdgdir)
1368    rmdir(vimdir)
1369    rmdir(xhome)
1370  end)
1371
1372  it('prefers XDG_CONFIG_DIRS over VIM', function()
1373    clear {
1374      args = { '--cmd', 'set nomore undodir=. directory=. belloff=' },
1375      args_rm = { '-u', '--cmd' },
1376      env = { HOME = xhome, XDG_CONFIG_DIRS = xdgdir, VIM = vimdir },
1377    }
1378    eq(
1379      'loaded 1 xdg 1 vim 0',
1380      eval('printf("loaded %d xdg %d vim %d", g:loaded, get(g:, "xdg", 0), get(g:, "vim", 0))')
1381    )
1382  end)
1383
1384  it('uses VIM if XDG_CONFIG_DIRS unset', function()
1385    clear {
1386      args = { '--cmd', 'set nomore undodir=. directory=. belloff=' },
1387      args_rm = { '-u', '--cmd' },
1388      env = { HOME = xhome, XDG_CONFIG_DIRS = '', VIM = vimdir },
1389    }
1390    eq(
1391      'loaded 1 xdg 0 vim 1',
1392      eval('printf("loaded %d xdg %d vim %d", g:loaded, get(g:, "xdg", 0), get(g:, "vim", 0))')
1393    )
1394  end)
1395
1396  it('respects NVIM_APPNAME in XDG_CONFIG_DIRS', function()
1397    local appname = 'mysysinitapp'
1398    mkdir(('%s/%s'):format(xdgdir, appname))
1399    write_file(('%s/%s/sysinit.vim'):format(xdgdir, appname), [[let g:appname_sysinit = 1]])
1400    clear {
1401      args_rm = { '-u' },
1402      env = { HOME = xhome, XDG_CONFIG_DIRS = xdgdir, NVIM_APPNAME = appname },
1403    }
1404    eq(1, eval('g:appname_sysinit'))
1405    -- Should not load from nvim/ subdir (which has the default sysinit.vim from before_each)
1406    eq(0, eval('get(g:, "xdg", 0)'))
1407  end)
1408end)
1409
1410describe('user config init', function()
1411  local xhome = 'Xhome'
1412  local xconfig = ('%s/Xconfig'):format(xhome)
1413  local xdata = ('%s/Xdata'):format(xhome)
1414  local init_lua_path = ('%s/nvim/init.lua'):format(xconfig)
1415  local xenv = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata }
1416
1417  before_each(function()
1418    rmdir(xhome)
1419
1420    mkdir_p(('%s/nvim'):format(xconfig))
1421    mkdir_p(xdata)
1422
1423    write_file(init_lua_path, [[vim.g.lua_rc = 1]])
1424  end)
1425
1426  after_each(function()
1427    rmdir(xhome)
1428  end)
1429
1430  it('loads init.lua from XDG config home by default', function()
1431    clear { args_rm = { '-u' }, env = xenv }
1432
1433    eq(1, eval('g:lua_rc'))
1434    eq(fn.fnamemodify(init_lua_path, ':p'), eval('$MYVIMRC'))
1435  end)
1436
1437  describe('loads existing', function()
1438    local exrc_path = '.exrc'
1439    local xstate = 'Xstate'
1440    local xstateenv = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata, XDG_STATE_HOME = xstate }
1441
1442    local function setup_exrc_file(filename)
1443      exrc_path = filename
1444
1445      if string.find(exrc_path, '%.lua$') then
1446        write_file(
1447          exrc_path,
1448          string.format(
1449            [[
1450              vim.g.exrc_file = "%s"
1451              vim.g.exrc_path = debug.getinfo(1, 'S').source:gsub('^@', '')
1452              vim.g.exrc_count = (vim.g.exrc_count or 0) + 1
1453            ]],
1454            exrc_path
1455          )
1456        )
1457      else
1458        write_file(
1459          exrc_path,
1460          string.format(
1461            [[
1462              let g:exrc_file = "%s"
1463              " let g:exrc_path = ??
1464              let g:exrc_count = get(g:, 'exrc_count', 0) + 1
1465            ]],
1466            exrc_path
1467          )
1468        )
1469      end
1470    end
1471
1472    before_each(function()
1473      for _, file in ipairs({ '.exrc', '.nvimrc', '.nvim.lua' }) do
1474        os.remove('../' .. file)
1475        os.remove(file)
1476      end
1477      write_file(
1478        init_lua_path,
1479        [[
1480          vim.o.exrc = true
1481          vim.g.exrc_file = '---'
1482        ]]
1483      )
1484      mkdir_p(('%s/%s'):format(xstate, is_os('win') and 'nvim-data' or 'nvim'))
1485    end)
1486
1487    after_each(function()
1488      for _, file in ipairs({ '.exrc', '.nvimrc', '.nvim.lua' }) do
1489        os.remove('../' .. file)
1490        os.remove(file)
1491      end
1492      rmdir(xstate)
1493    end)
1494
1495    for _, filename in ipairs({ '.exrc', '.nvimrc', '.nvim.lua', '../.nvim.lua', '../.nvimrc' }) do
1496      it(filename .. ' from cwd', function()
1497        setup_exrc_file(filename)
1498
1499        clear { args_rm = { '-u' }, env = xstateenv }
1500        -- The 'exrc' file is not trusted, and the prompt is skipped because there is no UI.
1501        eq('---', eval('g:exrc_file'))
1502
1503        local screen = Screen.new(50, 8)
1504        screen._default_attr_ids = nil
1505        fn.jobstart({ nvim_prog }, {
1506          term = true,
1507          env = {
1508            VIMRUNTIME = os.getenv('VIMRUNTIME'),
1509          },
1510        })
1511        screen:expect({ any = pesc('[i]gnore, (v)iew, (d)eny:') })
1512        -- `i` to enter Terminal mode, `v` to view then `:trust`
1513        feed('iv')
1514        feed(':trust<CR>')
1515        feed(':q<CR>')
1516        screen:expect([[
1517          ^                                                  |
1518          ~                                                 |*4
1519          [No Name]                       0,0-1          All|
1520                                                            |
1521          -- TERMINAL --                                    |
1522        ]])
1523        feed(':echo g:exrc_file<CR>')
1524        screen:expect(string.format(
1525          [[
1526          ^                                                  |
1527          ~                                                 |*4
1528          [No Name]                       0,0-1          All|
1529          %s%s|
1530          -- TERMINAL --                                    |
1531        ]],
1532          '---',
1533          string.rep(' ', 50 - #'---')
1534        ))
1535
1536        clear { args_rm = { '-u' }, env = xstateenv }
1537        if string.find(exrc_path, '%.lua$') then
1538          eq(
1539            vim.fs.normalize(vim.fs.abspath(filename)),
1540            vim.fs.normalize(vim.fs.abspath(eval('g:exrc_path')))
1541          )
1542        end
1543        -- The 'exrc' file is now trusted.
1544        eq(filename, eval('g:exrc_file'))
1545      end)
1546    end
1547
1548    it('exrc from parent directories', function()
1549      setup_exrc_file('.nvim.lua')
1550      setup_exrc_file('../.exrc')
1551      clear { args_rm = { '-u' }, env = xstateenv }
1552      -- use a screen wide width to avoid wrapping the word `.exrc`, `.nvim.lua` below.
1553      local screen = Screen.new(500, 8)
1554      screen._default_attr_ids = nil
1555      fn.jobstart({ nvim_prog }, {
1556        term = true,
1557        env = {
1558          VIMRUNTIME = os.getenv('VIMRUNTIME'),
1559        },
1560      })
1561      -- current directory exrc is found first
1562      screen:expect({ any = '.nvim.lua' })
1563      screen:expect({ any = pesc('[i]gnore, (v)iew, (d)eny:'), unchanged = true })
1564      feed('iv')
1565
1566      -- after that the exrc in the parent directory
1567      screen:expect({ any = '.exrc', unchanged = true })
1568      screen:expect({ any = pesc('[i]gnore, (v)iew, (d)eny:'), unchanged = true })
1569      feed('v')
1570
1571      -- trust .exrc
1572      feed(':trust<CR>')
1573      screen:expect({ any = 'Allowed in trust database: ".*/%.exrc"' })
1574      feed(':q<CR>')
1575      -- trust .nvim.lua
1576      feed(':trust<CR>')
1577      screen:expect({ any = 'Allowed in trust database: ".*/%.nvim%.lua"' })
1578      feed(':q<CR>')
1579      -- no exrc file is executed
1580      feed(':echo g:exrc_count<CR>')
1581      screen:expect({ any = 'E121: Undefined variable: g:exrc_count' })
1582
1583      -- restart nvim
1584      feed(':restart<CR>')
1585      screen:expect([[
1586        ^{MATCH: +}|
1587        ~{MATCH: +}|*4
1588        [No Name]{MATCH: +}0,0-1{MATCH: +}All|
1589        {MATCH: +}|
1590        -- TERMINAL --{MATCH: +}|
1591      ]])
1592
1593      -- a total of 2 exrc files are executed
1594      feed(':echo g:exrc_count<CR>')
1595      screen:expect([[
1596        ^{MATCH: +}|
1597        ~{MATCH: +}|*4
1598        [No Name]{MATCH: +}0,0-1{MATCH: +}All|
1599        2{MATCH: +}|
1600        -- TERMINAL --{MATCH: +}|
1601      ]])
1602
1603      -- The server is now detached and needs to be quit explicitly.
1604      feed(':qall!<CR>')
1605      screen:expect({ any = vim.pesc('[Process exited 0]') })
1606    end)
1607  end)
1608
1609  describe('with explicitly provided config', function()
1610    local custom_lua_path = ('%s/custom.lua'):format(xhome)
1611    before_each(function()
1612      write_file(
1613        custom_lua_path,
1614        [[
1615          vim.g.custom_lua_rc = 1
1616        ]]
1617      )
1618    end)
1619
1620    it('loads custom lua config and does not set $MYVIMRC', function()
1621      clear { args = { '-u', custom_lua_path }, env = xenv }
1622      eq(1, eval('g:custom_lua_rc'))
1623      eq('', eval('$MYVIMRC'))
1624    end)
1625  end)
1626
1627  describe('VIMRC also exists', function()
1628    before_each(function()
1629      write_file(
1630        ('%s/nvim/init.vim'):format(xconfig),
1631        [[
1632          let g:vim_rc = 1
1633        ]]
1634      )
1635    end)
1636
1637    it('loads default lua config, but shows an error', function()
1638      clear { args_rm = { '-u' }, env = xenv }
1639      eq(1, eval('g:lua_rc'))
1640      t.matches(
1641        'E5422: Conflicting configs: "Xhome.Xconfig.nvim.init.lua" "Xhome.Xconfig.nvim.init.vim"',
1642        eval('v:errmsg')
1643      )
1644    end)
1645  end)
1646
1647  describe('from XDG_CONFIG_DIRS', function()
1648    local xdgdir = 'Xxdgconfigdirs'
1649
1650    before_each(function()
1651      -- Remove init.lua from XDG_CONFIG_HOME so nvim falls back to XDG_CONFIG_DIRS
1652      os.remove(init_lua_path)
1653      rmdir(xdgdir)
1654      mkdir_p(('%s/nvim'):format(xdgdir))
1655    end)
1656
1657    after_each(function()
1658      rmdir(xdgdir)
1659    end)
1660
1661    it('loads init.lua from XDG_CONFIG_DIRS when no config in XDG_CONFIG_HOME', function()
1662      write_file(('%s/nvim/init.lua'):format(xdgdir), [[vim.g.xdg_config_dirs_lua = 1]])
1663      clear {
1664        args_rm = { '-u' },
1665        env = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata, XDG_CONFIG_DIRS = xdgdir },
1666      }
1667      eq(1, eval('g:xdg_config_dirs_lua'))
1668      eq(fn.fnamemodify(('%s/nvim/init.lua'):format(xdgdir), ':p'), eval('$MYVIMRC'))
1669    end)
1670
1671    it('prefers init.lua over init.vim, shows E5422', function()
1672      write_file(('%s/nvim/init.lua'):format(xdgdir), [[vim.g.xdg_lua = 1]])
1673      write_file(('%s/nvim/init.vim'):format(xdgdir), [[let g:xdg_vim = 1]])
1674      clear {
1675        args_rm = { '-u' },
1676        env = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata, XDG_CONFIG_DIRS = xdgdir },
1677      }
1678      eq(1, eval('g:xdg_lua'))
1679      eq(0, eval('get(g:, "xdg_vim", 0)'))
1680      t.matches('E5422: Conflicting configs:', eval('v:errmsg'))
1681    end)
1682
1683    it('falls back to init.vim when no init.lua', function()
1684      write_file(('%s/nvim/init.vim'):format(xdgdir), [[let g:xdg_vim = 1]])
1685      clear {
1686        args_rm = { '-u' },
1687        env = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata, XDG_CONFIG_DIRS = xdgdir },
1688      }
1689      eq(1, eval('g:xdg_vim'))
1690    end)
1691
1692    it('respects NVIM_APPNAME', function()
1693      local appname = 'mytestapp'
1694      mkdir_p(('%s/%s'):format(xdgdir, appname))
1695      -- Also create nvim/ with a config that should NOT be loaded
1696      write_file(('%s/nvim/init.lua'):format(xdgdir), [[vim.g.wrong = 1]])
1697      write_file(('%s/%s/init.lua'):format(xdgdir, appname), [[vim.g.appname_lua = 1]])
1698      clear {
1699        args_rm = { '-u' },
1700        env = {
1701          XDG_CONFIG_HOME = xconfig,
1702          XDG_DATA_HOME = xdata,
1703          XDG_CONFIG_DIRS = xdgdir,
1704          NVIM_APPNAME = appname,
1705        },
1706      }
1707      eq(1, eval('g:appname_lua'))
1708      eq(0, eval('get(g:, "wrong", 0)'))
1709      eq(fn.fnamemodify(('%s/%s/init.lua'):format(xdgdir, appname), ':p'), eval('$MYVIMRC'))
1710    end)
1711  end)
1712end)
1713
1714describe('runtime:', function()
1715  local xhome = 'Xhome'
1716  local xconfig = ('%s/Xconfig'):format(xhome)
1717  local xdata = ('%s/Xdata'):format(xhome)
1718  local xenv = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata }
1719
1720  setup(function()
1721    rmdir(xhome)
1722    mkdir_p(('%s/nvim'):format(xconfig))
1723    mkdir_p(xdata)
1724  end)
1725
1726  teardown(function()
1727    rmdir(xhome)
1728  end)
1729
1730  it('loads plugin/*.lua from XDG config home', function()
1731    local plugin_folder_path = ('%s/nvim/plugin'):format(xconfig)
1732    local plugin_file_path = ('%s/plugin.lua'):format(plugin_folder_path)
1733    mkdir_p(plugin_folder_path)
1734    finally(function()
1735      rmdir(plugin_folder_path)
1736    end)
1737    write_file(plugin_file_path, [[ vim.g.lua_plugin = 1 ]])
1738
1739    clear { args_rm = { '-u' }, env = xenv }
1740
1741    eq(1, eval('g:lua_plugin'))
1742  end)
1743
1744  it('loads plugin/*.lua from start packages', function()
1745    local plugin_path = ('%s/nvim/pack/category/start/test_plugin'):format(xconfig)
1746    local plugin_folder_path = ('%s/plugin'):format(plugin_path)
1747    local plugin_file_path = ('%s/plugin.lua'):format(plugin_folder_path)
1748    local profiler_file = 'test_startuptime.log'
1749    mkdir_p(plugin_folder_path)
1750    finally(function()
1751      os.remove(profiler_file)
1752      rmdir(plugin_path)
1753    end)
1754
1755    write_file(plugin_file_path, [[vim.g.lua_plugin = 2]])
1756
1757    clear { args_rm = { '-u' }, args = { '--startuptime', profiler_file }, env = xenv }
1758
1759    eq(2, eval('g:lua_plugin'))
1760    -- Check if plugin_file_path is listed in getscriptinfo()
1761    local scripts = tbl_map(function(s)
1762      return s.name
1763    end, fn.getscriptinfo())
1764    ok(#tbl_filter(function(s)
1765      return endswith(s, plugin_file_path)
1766    end, scripts) > 0)
1767
1768    -- Check if plugin_file_path is listed in startup profile
1769    local profile_reader = io.open(profiler_file, 'r')
1770    local profile_log = profile_reader:read('*a')
1771    profile_reader:close()
1772    ok(profile_log:find(plugin_file_path) ~= nil)
1773  end)
1774
1775  it('loads plugin/*.lua from site packages', function()
1776    local nvimdata = is_os('win') and 'nvim-data' or 'nvim'
1777    local plugin_path = ('%s/%s/site/pack/xa/start/yb'):format(xdata, nvimdata)
1778    local plugin_folder_path = ('%s/plugin'):format(plugin_path)
1779    local plugin_after_path = ('%s/after/plugin'):format(plugin_path)
1780    local plugin_file_path = ('%s/plugin.lua'):format(plugin_folder_path)
1781    local plugin_after_file_path = ('%s/helloo.lua'):format(plugin_after_path)
1782    mkdir_p(plugin_folder_path)
1783    mkdir_p(plugin_after_path)
1784    finally(function()
1785      rmdir(plugin_path)
1786    end)
1787
1788    write_file(plugin_file_path, [[table.insert(_G.lista, "unos")]])
1789    write_file(plugin_after_file_path, [[table.insert(_G.lista, "dos")]])
1790
1791    clear { args_rm = { '-u' }, args = { '--cmd', 'lua _G.lista = {}' }, env = xenv }
1792
1793    eq({ 'unos', 'dos' }, exec_lua 'return _G.lista')
1794  end)
1795
1796  it('no crash setting &rtp in plugins with :packloadall called before #18315', function()
1797    local plugin_folder_path = ('%s/nvim/plugin'):format(xconfig)
1798    mkdir_p(plugin_folder_path)
1799    finally(function()
1800      rmdir(plugin_folder_path)
1801    end)
1802
1803    write_file(
1804      ('%s/plugin.vim'):format(plugin_folder_path),
1805      [[
1806        let &runtimepath = &runtimepath
1807        let g:vim_plugin = 1
1808      ]]
1809    )
1810    write_file(
1811      ('%s/plugin.lua'):format(plugin_folder_path),
1812      [[
1813        vim.o.runtimepath = vim.o.runtimepath
1814        vim.g.lua_plugin = 1
1815      ]]
1816    )
1817
1818    clear { args_rm = { '-u' }, args = { '--cmd', 'packloadall' }, env = xenv }
1819
1820    eq(1, eval('g:vim_plugin'))
1821    eq(1, eval('g:lua_plugin'))
1822  end)
1823
1824  it("loads ftdetect/*.{vim,lua} respecting 'rtp' order", function()
1825    local rtp_folder = ('%s/nvim'):format(xconfig)
1826    local after_rtp_folder = ('%s/after'):format(rtp_folder)
1827    local ftdetect_folder = ('%s/ftdetect'):format(rtp_folder)
1828    local after_ftdetect_folder = ('%s/ftdetect'):format(after_rtp_folder)
1829    mkdir_p(ftdetect_folder)
1830    mkdir_p(after_ftdetect_folder)
1831    finally(function()
1832      rmdir(ftdetect_folder)
1833      rmdir(after_ftdetect_folder)
1834    end)
1835    write_file(('%s/scripts.vim'):format(rtp_folder), [[let g:aseq ..= 'S']])
1836    write_file(('%s/scripts.vim'):format(after_rtp_folder), [[let g:aseq ..= 's']])
1837    -- A .lua file is loaded after a .vim file if they only differ in extension.
1838    -- All files in after/ftdetect/ are loaded after all files in ftdetect/.
1839    write_file(
1840      ('%s/new-ft.vim'):format(ftdetect_folder),
1841      [[
1842        let g:seq ..= 'A'
1843        autocmd BufRead,BufNewFile FTDETECT let g:aseq ..= 'A'
1844      ]]
1845    )
1846    write_file(
1847      ('%s/new-ft.lua'):format(ftdetect_folder),
1848      [[
1849        vim.g.seq = vim.g.seq .. 'B'
1850        vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, {
1851          pattern = 'FTDETECT',
1852          command = "let g:aseq ..= 'B'",
1853        })
1854      ]]
1855    )
1856    write_file(
1857      ('%s/new-ft.vim'):format(after_ftdetect_folder),
1858      [[
1859        let g:seq ..= 'a'
1860        autocmd BufRead,BufNewFile FTDETECT let g:aseq ..= 'a'
1861      ]]
1862    )
1863    write_file(
1864      ('%s/new-ft.lua'):format(after_ftdetect_folder),
1865      [[
1866        vim.g.seq = vim.g.seq .. 'b'
1867        vim.api.nvim_create_autocmd({ 'BufRead', 'BufNewFile' }, {
1868          pattern = 'FTDETECT',
1869          command = "let g:aseq ..= 'b'",
1870        })
1871      ]]
1872    )
1873    clear { args_rm = { '-u' }, args = { '--cmd', 'let g:seq = ""' }, env = xenv }
1874    eq('ABab', eval('g:seq'))
1875    command('let g:aseq = ""')
1876    command('edit FTDETECT')
1877    eq('SsABab', eval('g:aseq'))
1878  end)
1879
1880  it('no crash for recursive search_path build #39815', function()
1881    clear()
1882    local screen = Screen.new()
1883    fn.jobstart({
1884      nvim_prog,
1885      '--clean',
1886      '+lua require("vim._core.ui2").enable()',
1887      '+set rtp+=$FOO | set syntax',
1888    }, { term = true, env = { VIMRUNTIME = os.getenv('VIMRUNTIME') } })
1889    screen:expect({ any = 'syntax', none = 'Process exited 1' })
1890  end)
1891end)
1892
1893describe('user session', function()
1894  local xhome = 'Xhome'
1895  local session_file = ('%s/session.lua'):format(xhome)
1896
1897  before_each(function()
1898    rmdir(xhome)
1899
1900    mkdir(xhome)
1901    write_file(
1902      session_file,
1903      [[
1904        vim.g.lua_session = 1
1905      ]]
1906    )
1907  end)
1908
1909  after_each(function()
1910    rmdir(xhome)
1911  end)
1912
1913  it('loads session from the provided lua file', function()
1914    clear { args = { '-S', session_file }, env = { HOME = xhome } }
1915    eq(1, eval('g:lua_session'))
1916  end)
1917end)