robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
246.1 KiB6940 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local describe, it, before_each, after_each, setup, teardown, finally =
5  t.describe, t.it, t.before_each, t.after_each, t.setup, t.teardown, t.finally
6local uv = vim.uv
7
8local dedent = t.dedent
9local assert_alive = n.assert_alive
10local NIL = vim.NIL
11local clear, eq, neq = n.clear, t.eq, t.neq
12local command = n.command
13local command_output = n.api.nvim_command_output
14local exec = n.exec
15local exec_capture = n.exec_capture
16local eval = n.eval
17local expect = n.expect
18local fn = n.fn
19local api = n.api
20local matches = t.matches
21local pesc = vim.pesc
22local mkdir_p = n.mkdir_p
23local ok, nvim_async, feed = t.ok, n.nvim_async, n.feed
24local async_meths = n.async_meths
25local is_os = t.is_os
26local parse_context = n.parse_context
27local request = n.request
28local rmdir = n.rmdir
29local source = n.source
30local next_msg = n.next_msg
31local tmpname = t.tmpname
32local write_file = t.write_file
33local exec_lua = n.exec_lua
34local insert = n.insert
35local skip = t.skip
36
37local pcall_err = t.pcall_err
38local format_string = require('test.format_string').format_string
39local intchar2lua = t.intchar2lua
40local mergedicts_copy = t.mergedicts_copy
41local endswith = vim.endswith
42
43describe('API', function()
44  before_each(clear)
45
46  it('validates requests', function()
47    -- RPC
48    matches('Invalid method: bogus$', pcall_err(request, 'bogus'))
49    matches('Invalid method: … の り 。…$', pcall_err(request, '… の り 。…'))
50    matches('Invalid method: <empty>$', pcall_err(request, ''))
51
52    -- Non-RPC: rpcrequest(v:servername) uses internal channel.
53    matches(
54      'Invalid method: … の り 。…$',
55      pcall_err(
56        request,
57        'nvim_eval',
58        [=[rpcrequest(sockconnect('pipe', v:servername, {'rpc':1}), '… の り 。…')]=]
59      )
60    )
61    matches(
62      'Invalid method: bogus$',
63      pcall_err(
64        request,
65        'nvim_eval',
66        [=[rpcrequest(sockconnect('pipe', v:servername, {'rpc':1}), 'bogus')]=]
67      )
68    )
69
70    -- XXX: This must be the last one, else next one will fail:
71    --      "Packer instance already working. Use another Packer ..."
72    matches("can't serialize object of type .$", pcall_err(request, nil))
73  end)
74
75  it('handles errors in async requests', function()
76    local error_types = api.nvim_get_api_info()[2].error_types
77    nvim_async('bogus')
78    eq({
79      'notification',
80      'nvim_error_event',
81      { error_types.Exception.id, 'Invalid method: bogus' },
82    }, next_msg())
83    -- error didn't close channel.
84    assert_alive()
85  end)
86
87  it('failed async request emits nvim_error_event', function()
88    local error_types = api.nvim_get_api_info()[2].error_types
89    async_meths.nvim_command('bogus')
90    eq({
91      'notification',
92      'nvim_error_event',
93      { error_types.Exception.id, 'Vim:E492: Not an editor command: bogus' },
94    }, next_msg())
95    -- error didn't close channel.
96    assert_alive()
97  end)
98
99  it('input is processed first if followed immediately by non-fast events', function()
100    api.nvim_set_current_line('ab')
101    async_meths.nvim_input('x')
102    async_meths.nvim_exec_lua('_G.res1 = vim.api.nvim_get_current_line()', {})
103    async_meths.nvim_exec_lua('_G.res2 = vim.api.nvim_get_current_line()', {})
104    eq({ 'b', 'b' }, exec_lua('return { _G.res1, _G.res2 }'))
105    -- Also test with getchar()
106    async_meths.nvim_command('let g:getchar = 1 | call getchar() | let g:getchar = 0')
107    eq(1, api.nvim_get_var('getchar'))
108    async_meths.nvim_input('x')
109    async_meths.nvim_exec_lua('_G.res1 = vim.g.getchar', {})
110    async_meths.nvim_exec_lua('_G.res2 = vim.g.getchar', {})
111    eq({ 0, 0 }, exec_lua('return { _G.res1, _G.res2 }'))
112  end)
113
114  it('does not set CA_COMMAND_BUSY #7254', function()
115    command('split')
116    command('autocmd WinEnter * startinsert')
117    command('wincmd w')
118    eq({ mode = 'i', blocking = false }, api.nvim_get_mode())
119  end)
120
121  describe('nvim_exec2', function()
122    it('always returns table', function()
123      -- In built version this results into `vim.empty_dict()`
124      eq({}, api.nvim_exec2('echo "Hello"', {}))
125      eq({}, api.nvim_exec2('echo "Hello"', { output = false }))
126      eq({ output = 'Hello' }, api.nvim_exec2('echo "Hello"', { output = true }))
127    end)
128
129    it('default options', function()
130      -- Should be equivalent to { output = false }
131      api.nvim_exec2("let x0 = 'a'", {})
132      eq('a', api.nvim_get_var('x0'))
133    end)
134
135    it('one-line input', function()
136      api.nvim_exec2("let x1 = 'a'", { output = false })
137      eq('a', api.nvim_get_var('x1'))
138    end)
139
140    it(':verbose set {option}?', function()
141      api.nvim_exec2('set nowrap', { output = false })
142      eq(
143        { output = 'nowrap\n\tLast set from anonymous :source line 1' },
144        api.nvim_exec2('verbose set wrap?', { output = true })
145      )
146
147      -- Using script var to force creation of a script item
148      api.nvim_exec2(
149        [[
150        let s:a = 1
151        set nowrap
152      ]],
153        { output = false }
154      )
155      eq(
156        { output = 'nowrap\n\tLast set from anonymous :source (script id 1) line 2' },
157        api.nvim_exec2('verbose set wrap?', { output = true })
158      )
159    end)
160
161    it('multiline input', function()
162      -- Heredoc + empty lines.
163      api.nvim_exec2("let x2 = 'a'\n", { output = false })
164      eq('a', api.nvim_get_var('x2'))
165      api.nvim_exec2('lua <<EOF\n\n\n\ny=3\n\n\nEOF', { output = false })
166      eq(3, api.nvim_eval("luaeval('y')"))
167
168      eq({}, api.nvim_exec2('lua <<EOF\ny=3\nEOF', { output = false }))
169      eq(3, api.nvim_eval("luaeval('y')"))
170
171      -- Multiple statements
172      api.nvim_exec2('let x1=1\nlet x2=2\nlet x3=3\n', { output = false })
173      eq(1, api.nvim_eval('x1'))
174      eq(2, api.nvim_eval('x2'))
175      eq(3, api.nvim_eval('x3'))
176
177      -- Functions
178      api.nvim_exec2('function Foo()\ncall setline(1,["xxx"])\nendfunction', { output = false })
179      eq('', api.nvim_get_current_line())
180      api.nvim_exec2('call Foo()', { output = false })
181      eq('xxx', api.nvim_get_current_line())
182
183      -- Autocmds
184      api.nvim_exec2('autocmd BufAdd * :let x1 = "Hello"', { output = false })
185      command('new foo')
186      eq('Hello', request('nvim_eval', 'g:x1'))
187
188      -- Line continuations
189      api.nvim_exec2(
190        [[
191        let abc = #{
192          \ a: 1,
193         "\ b: 2,
194          \ c: 3
195          \ }]],
196        { output = false }
197      )
198      eq({ a = 1, c = 3 }, request('nvim_eval', 'g:abc'))
199
200      -- try no spaces before continuations to catch off-by-one error
201      api.nvim_exec2('let ab = #{\n\\a: 98,\n"\\ b: 2\n\\}', { output = false })
202      eq({ a = 98 }, request('nvim_eval', 'g:ab'))
203
204      -- Script scope (s:)
205      eq(
206        { output = 'ahoy! script-scoped varrrrr' },
207        api.nvim_exec2(
208          [[
209          let s:pirate = 'script-scoped varrrrr'
210          function! s:avast_ye_hades(s) abort
211            return a:s .. ' ' .. s:pirate
212          endfunction
213          echo <sid>avast_ye_hades('ahoy!')
214        ]],
215          { output = true }
216        )
217      )
218
219      eq(
220        { output = "{'output': 'ahoy! script-scoped varrrrr'}" },
221        api.nvim_exec2(
222          [[
223          let s:pirate = 'script-scoped varrrrr'
224          function! Avast_ye_hades(s) abort
225            return a:s .. ' ' .. s:pirate
226          endfunction
227          echo nvim_exec2('echo Avast_ye_hades(''ahoy!'')', {'output': v:true})
228        ]],
229          { output = true }
230        )
231      )
232
233      matches(
234        'Vim%(echo%):E121: Undefined variable: s:pirate$',
235        pcall_err(
236          request,
237          'nvim_exec2',
238          [[
239          let s:pirate = 'script-scoped varrrrr'
240          call nvim_exec2('echo s:pirate', {'output': v:true})
241        ]],
242          { output = false }
243        )
244      )
245
246      -- Script items are created only on script var access
247      eq(
248        { output = '1\n0' },
249        api.nvim_exec2(
250          [[
251          echo expand("<SID>")->empty()
252          let s:a = 123
253          echo expand("<SID>")->empty()
254        ]],
255          { output = true }
256        )
257      )
258
259      eq(
260        { output = '1\n0' },
261        api.nvim_exec2(
262          [[
263          echo expand("<SID>")->empty()
264          function s:a() abort
265          endfunction
266          echo expand("<SID>")->empty()
267        ]],
268          { output = true }
269        )
270      )
271    end)
272
273    it('non-ASCII input', function()
274      api.nvim_exec2(
275        [=[
276        new
277        exe "normal! i ax \n Ax "
278        :%s/ax/--a1234--/g | :%s/Ax/--A1234--/g
279      ]=],
280        { output = false }
281      )
282      command('1')
283      eq(' --a1234-- ', api.nvim_get_current_line())
284      command('2')
285      eq(' --A1234-- ', api.nvim_get_current_line())
286
287      api.nvim_exec2(
288        [[
289        new
290        call setline(1,['xxx'])
291        call feedkeys('r')
292        call feedkeys('ñ', 'xt')
293      ]],
294        { output = false }
295      )
296      eq('ñxx', api.nvim_get_current_line())
297    end)
298
299    it('can use :finish', function()
300      api.nvim_exec2('let g:var = 123\nfinish\nlet g:var = 456', {})
301      eq(123, api.nvim_get_var('var'))
302    end)
303
304    it('execution error', function()
305      eq(
306        'nvim_exec2(), line 1: Vim:E492: Not an editor command: bogus_command',
307        pcall_err(request, 'nvim_exec2', 'bogus_command', {})
308      )
309      eq('', api.nvim_eval('v:errmsg')) -- v:errmsg was not updated.
310      eq('', eval('v:exception'))
311
312      eq(
313        'nvim_exec2(), line 1: Vim(buffer):E86: Buffer 23487 does not exist',
314        pcall_err(request, 'nvim_exec2', 'buffer 23487', {})
315      )
316      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
317      eq('', eval('v:exception'))
318    end)
319
320    it('recursion', function()
321      local fname = tmpname()
322      write_file(fname, 'let x1 = "set from :source file"\n')
323      -- nvim_exec2
324      --   :source
325      --     nvim_exec2
326      request('nvim_exec2', [[
327        let x2 = substitute('foo','o','X','g')
328        let x4 = 'should be overwritten'
329        call nvim_exec2("source ]] .. fname .. [[\nlet x3 = substitute('foo','foo','set by recursive nvim_exec2','g')\nlet x5='overwritten'\nlet x4=x5\n", {'output': v:false})
330      ]], { output = false })
331      eq('set from :source file', request('nvim_get_var', 'x1'))
332      eq('fXX', request('nvim_get_var', 'x2'))
333      eq('set by recursive nvim_exec2', request('nvim_get_var', 'x3'))
334      eq('overwritten', request('nvim_get_var', 'x4'))
335      eq('overwritten', request('nvim_get_var', 'x5'))
336      os.remove(fname)
337    end)
338
339    it('traceback', function()
340      local fname = tmpname()
341      write_file(fname, 'echo "hello"\n')
342      local sourcing_fname = tmpname()
343      write_file(sourcing_fname, 'call nvim_exec2("source ' .. fname .. '", {"output": v:false})\n')
344      api.nvim_exec2('set verbose=2', { output = false })
345      local traceback_output = dedent([[
346        sourcing "nvim_exec2()"
347        line 1: sourcing "nvim_exec2() called at nvim_exec2():1"
348        line 1: sourcing "%s"
349        line 1: sourcing "nvim_exec2() called at %s:1"
350        line 1: sourcing "%s"
351        hello
352        finished sourcing %s
353        continuing in nvim_exec2() called at %s:1
354        finished sourcing nvim_exec2() called at %s:1
355        continuing in %s
356        finished sourcing %s
357        continuing in nvim_exec2() called at nvim_exec2():1
358        finished sourcing nvim_exec2() called at nvim_exec2():1
359        continuing in nvim_exec2()
360        finished sourcing nvim_exec2()]]):format(
361        sourcing_fname,
362        sourcing_fname,
363        fname,
364        fname,
365        sourcing_fname,
366        sourcing_fname,
367        sourcing_fname,
368        sourcing_fname
369      )
370      eq(
371        { output = traceback_output },
372        api.nvim_exec2(
373          'call nvim_exec2("source ' .. sourcing_fname .. '", {"output": v:false})',
374          { output = true }
375        )
376      )
377      os.remove(fname)
378      os.remove(sourcing_fname)
379    end)
380
381    it('returns output', function()
382      eq(
383        { output = 'this is spinal tap' },
384        api.nvim_exec2('lua <<EOF\n\n\nprint("this is spinal tap")\n\n\nEOF', { output = true })
385      )
386      eq({ output = '' }, api.nvim_exec2('echo', { output = true }))
387      eq({ output = 'foo 42' }, api.nvim_exec2('echo "foo" 42', { output = true }))
388      -- Returns output in cmdline mode #35321
389      feed(':')
390      eq({ output = 'foo 42' }, api.nvim_exec2('echo "foo" 42', { output = true }))
391    end)
392
393    it('displays messages when opts.output=false', function()
394      local screen = Screen.new(40, 8)
395      api.nvim_exec2("echo 'hello'", { output = false })
396      screen:expect {
397        grid = [[
398        ^                                        |
399        {1:~                                       }|*6
400        hello                                   |
401      ]],
402      }
403    end)
404
405    it("doesn't display messages when output=true", function()
406      local screen = Screen.new(40, 6)
407      api.nvim_exec2("echo 'hello'", { output = true })
408      screen:expect {
409        grid = [[
410        ^                                        |
411        {1:~                                       }|*4
412                                                |
413      ]],
414      }
415      exec([[
416        func Print()
417          call nvim_exec2('echo "hello"', { 'output': v:true })
418        endfunc
419      ]])
420      feed([[:echon 1 | call Print() | echon 5<CR>]])
421      screen:expect {
422        grid = [[
423        ^                                        |
424        {1:~                                       }|*4
425        15                                      |
426      ]],
427      }
428    end)
429
430    it('errors properly when command too recursive', function()
431      exec_lua([[
432        _G.success = false
433        vim.api.nvim_create_user_command('Test', function()
434          vim.api.nvim_exec2('Test', {})
435          _G.success = true
436        end, {})
437      ]])
438      pcall_err(command, 'Test')
439      assert_alive()
440      eq(false, exec_lua('return _G.success'))
441    end)
442
443    it('redir_write() message column is reset with ext_messages', function()
444      exec_lua('vim.ui_attach(1, { ext_messages = true }, function() end)')
445      api.nvim_exec2('hi VisualNC', { output = true })
446      eq('VisualNC       xxx cleared', api.nvim_exec2('hi VisualNC', { output = true }).output)
447      api.nvim_exec2('echon 1234567', { output = true })
448      eq('VisualNC       xxx cleared', api.nvim_exec2('hi VisualNC', { output = true }).output)
449    end)
450
451    it('captures multi-chunk err nvim_echo() #36883', function()
452      eq(
453        'nvim_exec2(), line 1: Vim(call):abc',
454        pcall_err(request, 'nvim_exec2', 'call nvim_echo([["a"],["b"],["c"] ], 0, #{err:1})', {})
455      )
456    end)
457  end)
458
459  describe('nvim_command', function()
460    it('works', function()
461      local fname = tmpname()
462      command('new')
463      command('edit ' .. fname)
464      command('normal itesting\napi')
465      command('w')
466      local f = assert(io.open(fname))
467      if is_os('win') then
468        eq('testing\r\napi\r\n', f:read('*a'))
469      else
470        eq('testing\napi\n', f:read('*a'))
471      end
472      f:close()
473      os.remove(fname)
474    end)
475
476    it('Vimscript validation error: fails with specific error', function()
477      local status, rv = pcall(command, 'bogus_command')
478      eq(false, status) -- nvim_command() failed.
479      eq('E492:', string.match(rv, 'E%d*:')) -- Vimscript error was returned.
480      eq('', api.nvim_eval('v:errmsg')) -- v:errmsg was not updated.
481      eq('', eval('v:exception'))
482    end)
483
484    it('Vimscript execution error: fails with specific error', function()
485      local status, rv = pcall(command, 'buffer 23487')
486      eq(false, status) -- nvim_command() failed.
487      eq('E86: Buffer 23487 does not exist', string.match(rv, 'E%d*:.*'))
488      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
489      eq('', eval('v:exception'))
490    end)
491
492    it('gives E493 instead of prompting on backwards range', function()
493      command('split')
494      eq(
495        'Vim(windo):E493: Backwards range given: 2,1windo echo',
496        pcall_err(command, '2,1windo echo')
497      )
498    end)
499  end)
500
501  describe('nvim_command_output', function()
502    it('does not induce hit-enter prompt', function()
503      api.nvim_ui_attach(80, 20, {})
504      -- Induce a hit-enter prompt use nvim_input (non-blocking).
505      command('set cmdheight=1')
506      api.nvim_input([[:echo "hi\nhi2"<CR>]])
507
508      -- Verify hit-enter prompt.
509      eq({ mode = 'r', blocking = true }, api.nvim_get_mode())
510      api.nvim_input([[<C-c>]])
511
512      -- Verify NO hit-enter prompt.
513      command_output([[echo "hi\nhi2"]])
514      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
515    end)
516
517    it('captures command output', function()
518      eq('this is\nspinal tap', command_output([[echo "this is\nspinal tap"]]))
519      eq('no line ending!', command_output([[echon "no line ending!"]]))
520    end)
521
522    it('captures empty command output', function()
523      eq('', command_output('echo'))
524    end)
525
526    it('captures single-char command output', function()
527      eq('x', command_output('echo "x"'))
528    end)
529
530    it('captures multiple commands', function()
531      eq('foo\n  1 %a   "[No Name]"                    line 1', command_output('echo "foo" | ls'))
532    end)
533
534    it('captures nested execute()', function()
535      eq(
536        '\nnested1\nnested2\n  1 %a   "[No Name]"                    line 1',
537        command_output([[echo execute('echo "nested1\nnested2"') | ls]])
538      )
539    end)
540
541    it('captures nested nvim_command_output()', function()
542      eq(
543        'nested1\nnested2\n  1 %a   "[No Name]"                    line 1',
544        command_output([[echo nvim_command_output('echo "nested1\nnested2"') | ls]])
545      )
546    end)
547
548    it('returns shell |:!| output', function()
549      local win_lf = is_os('win') and '\r' or ''
550      eq(':!echo foo\r\n\nfoo' .. win_lf .. '\n', command_output([[!echo foo]]))
551    end)
552
553    it('Vimscript validation error: fails with specific error', function()
554      local status, rv = pcall(command_output, 'bogus commannnd')
555      eq(false, status) -- nvim_command_output() failed.
556      eq('E492: Not an editor command: bogus commannnd', string.match(rv, 'E%d*:.*'))
557      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
558      -- Verify NO hit-enter prompt.
559      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
560    end)
561
562    it('Vimscript execution error: fails with specific error', function()
563      local status, rv = pcall(command_output, 'buffer 42')
564      eq(false, status) -- nvim_command_output() failed.
565      eq('E86: Buffer 42 does not exist', string.match(rv, 'E%d*:.*'))
566      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
567      -- Verify NO hit-enter prompt.
568      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
569    end)
570
571    it('does not cause heap buffer overflow with large output', function()
572      eq(eval('string(range(1000000))'), command_output('echo range(1000000)'))
573    end)
574  end)
575
576  describe('nvim_eval', function()
577    it('works', function()
578      command('let g:v1 = "a"')
579      command('let g:v2 = [1, 2, {"v3": 3}]')
580      eq({ v1 = 'a', v2 = { 1, 2, { v3 = 3 } } }, api.nvim_eval('g:'))
581    end)
582
583    it('handles NULL-initialized strings correctly', function()
584      eq(1, api.nvim_eval("matcharg(1) == ['', '']"))
585      eq({ '', '' }, api.nvim_eval('matcharg(1)'))
586    end)
587
588    it('works under deprecated name', function()
589      eq(2, request('vim_eval', '1+1'))
590    end)
591
592    it('Vimscript error: returns error details, does NOT update v:errmsg', function()
593      eq('Vim:E121: Undefined variable: bogus', pcall_err(request, 'nvim_eval', 'bogus expression'))
594      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
595    end)
596
597    it('can return Lua function to Lua code', function()
598      eq(
599        [["a string with \"double quotes\" and 'single quotes'"]],
600        exec_lua([=[
601          local fun = vim.api.nvim_eval([[luaeval('string.format')]])
602          return fun('%q', [[a string with "double quotes" and 'single quotes']])
603        ]=])
604      )
605    end)
606  end)
607
608  describe('nvim_call_function', function()
609    it('works', function()
610      api.nvim_call_function('setqflist', { { { filename = 'something', lnum = 17 } }, 'r' })
611      eq(17, api.nvim_call_function('getqflist', {})[1].lnum)
612      eq(17, api.nvim_call_function('eval', { 17 }))
613      eq('foo', api.nvim_call_function('simplify', { 'this/./is//redundant/../../../foo' }))
614    end)
615
616    it('Vimscript validation error: returns specific error, does NOT update v:errmsg', function()
617      eq(
618        'Vim:E117: Unknown function: bogus function',
619        pcall_err(request, 'nvim_call_function', 'bogus function', { 'arg1' })
620      )
621      eq(
622        'Vim:E119: Not enough arguments for function: atan',
623        pcall_err(request, 'nvim_call_function', 'atan', {})
624      )
625      eq('', eval('v:exception'))
626      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
627    end)
628
629    it('Vimscript error: returns error details, does NOT update v:errmsg', function()
630      eq(
631        'Vim:E808: Number or Float required',
632        pcall_err(request, 'nvim_call_function', 'atan', { 'foo' })
633      )
634      eq(
635        'Vim:Invalid channel stream "xxx"',
636        pcall_err(request, 'nvim_call_function', 'chanclose', { 999, 'xxx' })
637      )
638      eq(
639        'Vim:E900: Invalid channel id',
640        pcall_err(request, 'nvim_call_function', 'chansend', { 999, 'foo' })
641      )
642      eq('', eval('v:exception'))
643      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
644    end)
645
646    it('Vimscript exception: returns exception details, does NOT update v:errmsg', function()
647      source([[
648        function! Foo() abort
649          throw 'wtf'
650        endfunction
651      ]])
652      eq('function Foo, line 1: wtf', pcall_err(request, 'nvim_call_function', 'Foo', {}))
653      eq('', eval('v:exception'))
654      eq('', eval('v:errmsg')) -- v:errmsg was not updated.
655    end)
656
657    it('validation', function()
658      -- stylua: ignore
659      local too_many_args = { 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x' }
660      source([[
661        function! Foo(...) abort
662          echo a:000
663        endfunction
664      ]])
665      -- E740
666      eq(
667        'Function called with too many arguments',
668        pcall_err(request, 'nvim_call_function', 'Foo', too_many_args)
669      )
670    end)
671
672    it('can return Lua function to Lua code', function()
673      eq(
674        [["a string with \"double quotes\" and 'single quotes'"]],
675        exec_lua([=[
676          local fun = vim.api.nvim_call_function('luaeval', { 'string.format' })
677          return fun('%q', [[a string with "double quotes" and 'single quotes']])
678        ]=])
679      )
680    end)
681  end)
682
683  describe('nvim_call_dict_function', function()
684    it('invokes Vimscript dict function', function()
685      source([[
686        function! F(name) dict
687          return self.greeting.', '.a:name.'!'
688        endfunction
689        let g:test_dict_fn = { 'greeting':'Hello', 'F':function('F') }
690
691        let g:test_dict_fn2 = { 'greeting':'Hi' }
692        function g:test_dict_fn2.F2(name)
693          return self.greeting.', '.a:name.' ...'
694        endfunction
695      ]])
696
697      -- :help Dictionary-function
698      eq('Hello, World!', api.nvim_call_dict_function('g:test_dict_fn', 'F', { 'World' }))
699      -- Funcref is sent as NIL over RPC.
700      eq({ greeting = 'Hello', F = NIL }, api.nvim_get_var('test_dict_fn'))
701
702      -- :help numbered-function
703      eq('Hi, Moon ...', api.nvim_call_dict_function('g:test_dict_fn2', 'F2', { 'Moon' }))
704      -- Funcref is sent as NIL over RPC.
705      eq({ greeting = 'Hi', F2 = NIL }, api.nvim_get_var('test_dict_fn2'))
706
707      -- Function specified via RPC dict.
708      source('function! G() dict\n  return "@".(self.result)."@"\nendfunction')
709      eq('@it works@', api.nvim_call_dict_function({ result = 'it works', G = 'G' }, 'G', {}))
710    end)
711
712    it('validation', function()
713      command('let g:d={"baz":"zub","meep":[]}')
714      eq(
715        'Not found: bogus',
716        pcall_err(request, 'nvim_call_dict_function', 'g:d', 'bogus', { 1, 2 })
717      )
718      eq(
719        'Not a function: baz',
720        pcall_err(request, 'nvim_call_dict_function', 'g:d', 'baz', { 1, 2 })
721      )
722      eq(
723        'Not a function: meep',
724        pcall_err(request, 'nvim_call_dict_function', 'g:d', 'meep', { 1, 2 })
725      )
726      eq(
727        'Vim:E117: Unknown function: f',
728        pcall_err(request, 'nvim_call_dict_function', { f = '' }, 'f', { 1, 2 })
729      )
730      eq(
731        'Not a function: f',
732        pcall_err(request, 'nvim_call_dict_function', "{ 'f': '' }", 'f', { 1, 2 })
733      )
734      eq(
735        'Invalid dict argument: expected String or Dict',
736        pcall_err(request, 'nvim_call_dict_function', 42, 'f', { 1, 2 })
737      )
738      eq(
739        'Vim:E121: Undefined variable: foo',
740        pcall_err(request, 'nvim_call_dict_function', 'foo', 'f', { 1, 2 })
741      )
742      eq('dict not found', pcall_err(request, 'nvim_call_dict_function', '42', 'f', { 1, 2 }))
743      eq(
744        'Invalid function name: (empty)',
745        pcall_err(request, 'nvim_call_dict_function', "{ 'f': '' }", '', { 1, 2 })
746      )
747    end)
748  end)
749
750  describe('nvim_set_current_dir', function()
751    local start_dir
752    local test_dir = 'Xtest_set_current_dir'
753
754    before_each(function()
755      fn.mkdir(test_dir)
756      start_dir = fn.getcwd()
757    end)
758
759    after_each(function()
760      n.rmdir(test_dir)
761    end)
762
763    it('works', function()
764      api.nvim_set_current_dir(test_dir)
765      eq(start_dir .. n.get_pathsep() .. test_dir, fn.getcwd())
766    end)
767
768    it('sets previous directory', function()
769      api.nvim_set_current_dir(test_dir)
770      command('cd -')
771      eq(start_dir, fn.getcwd())
772    end)
773  end)
774
775  describe('nvim_exec_lua', function()
776    it('works', function()
777      api.nvim_exec_lua('vim.api.nvim_set_var("test", 3)', {})
778      eq(3, api.nvim_get_var('test'))
779
780      eq(17, api.nvim_exec_lua('a, b = ...\nreturn a + b', { 10, 7 }))
781
782      eq(NIL, api.nvim_exec_lua('function xx(a,b)\nreturn a..b\nend', {}))
783      eq('xy', api.nvim_exec_lua('return xx(...)', { 'x', 'y' }))
784
785      -- Deprecated name: nvim_execute_lua.
786      eq('xy', api.nvim_execute_lua('return xx(...)', { 'x', 'y' }))
787    end)
788
789    it('reports errors', function()
790      eq([['=' expected near '+']], pcall_err(api.nvim_exec_lua, 'a+*b', {}))
791      eq([[unexpected symbol near '1']], pcall_err(api.nvim_exec_lua, '1+2', {}))
792      eq([[unexpected symbol]], pcall_err(api.nvim_exec_lua, 'aa=bb\0', {}))
793      eq(
794        [[attempt to call global 'bork' (a nil value)]],
795        pcall_err(api.nvim_exec_lua, 'bork()', {})
796      )
797      eq('did\nthe\nfail', pcall_err(api.nvim_exec_lua, 'error("did\\nthe\\nfail")', {}))
798    end)
799
800    it('uses native float values', function()
801      eq(2.5, api.nvim_exec_lua('return select(1, ...)', { 2.5 }))
802      eq('2.5', api.nvim_exec_lua('return vim.inspect(...)', { 2.5 }))
803
804      -- "special" float values are still accepted as return values.
805      eq(2.5, api.nvim_exec_lua("return vim.api.nvim_eval('2.5')", {}))
806      eq(
807        '{\n  [false] = 2.5,\n  [true] = 3\n}',
808        api.nvim_exec_lua("return vim.inspect(vim.api.nvim_eval('2.5'))", {})
809      )
810    end)
811  end)
812
813  describe('nvim_input', function()
814    it('Vimscript error: does NOT fail, updates v:errmsg', function()
815      local status, _ = pcall(api.nvim_input, ':call bogus_fn()<CR>')
816      local v_errnum = string.match(api.nvim_eval('v:errmsg'), 'E%d*:')
817      eq(true, status) -- nvim_input() did not fail.
818      eq('E117:', v_errnum) -- v:errmsg was updated.
819    end)
820
821    it('does not crash even if trans_special result is largest #11788, #12287', function()
822      command("call nvim_input('<M-'.nr2char(0x40000000).'>')")
823      eq(1, eval('1'))
824    end)
825
826    it('keeps accepting input after the input buffer fills and drains', function()
827      -- Regression test: the fixed input buffer (INPUT_BUFFER_SIZE == 16386) is
828      -- compacted left, not a ring. Filling it to within <19 bytes of the top
829      -- and then draining it used to leave the read/write cursors pinned, so
830      -- input_enqueue() could never reclaim space and silently dropped all
831      -- further input, freezing the editor. One oversized burst of a Normal-mode
832      -- no-op (CTRL-L) saturates the buffer in a single nvim_input() call; once it
833      -- has drained, input must still register. poke_eventloop() waits for the
834      -- burst to be fully consumed before the probe: the fix only reclaims space
835      -- once the buffer is empty, so the probe must arrive after the drain.
836      api.nvim_input(('\12'):rep(20000))
837      n.poke_eventloop()
838      api.nvim_input('ix<Esc>')
839      n.poke_eventloop()
840      eq('x', api.nvim_get_current_line())
841    end)
842  end)
843
844  describe('nvim_paste', function()
845    it('validation', function()
846      eq("Invalid 'phase': -2", pcall_err(request, 'nvim_paste', 'foo', true, -2))
847      eq("Invalid 'phase': 4", pcall_err(request, 'nvim_paste', 'foo', true, 4))
848    end)
849    local function run_streamed_paste_tests()
850      it('stream: multiple chunks form one undo-block', function()
851        api.nvim_paste('1/chunk 1 (start)\n', true, 1)
852        api.nvim_paste('1/chunk 2 (end)\n', true, 3)
853        local expected1 = [[
854          1/chunk 1 (start)
855          1/chunk 2 (end)
856          ]]
857        expect(expected1)
858        api.nvim_paste('2/chunk 1 (start)\n', true, 1)
859        api.nvim_paste('2/chunk 2\n', true, 2)
860        expect([[
861          1/chunk 1 (start)
862          1/chunk 2 (end)
863          2/chunk 1 (start)
864          2/chunk 2
865          ]])
866        api.nvim_paste('2/chunk 3\n', true, 2)
867        api.nvim_paste('2/chunk 4 (end)\n', true, 3)
868        expect([[
869          1/chunk 1 (start)
870          1/chunk 2 (end)
871          2/chunk 1 (start)
872          2/chunk 2
873          2/chunk 3
874          2/chunk 4 (end)
875          ]])
876        feed('u') -- Undo.
877        expect(expected1)
878      end)
879      it("stream: multiple chunks sets correct '[ mark", function()
880        -- Pastes single chunk
881        api.nvim_paste('aaaaaa\n', true, -1)
882        eq({ 0, 1, 1, 0 }, fn.getpos("'["))
883        -- Pastes an empty chunk
884        api.nvim_paste('', true, -1)
885        eq({ 0, 2, 1, 0 }, fn.getpos("'["))
886        -- Pastes some chunks on empty line
887        api.nvim_paste('1/chunk 1 (start)\n', true, 1)
888        eq({ 0, 2, 1, 0 }, fn.getpos("'["))
889        api.nvim_paste('1/chunk 2\n', true, 2)
890        eq({ 0, 2, 1, 0 }, fn.getpos("'["))
891        api.nvim_paste('1/chunk 3 (end)\n', true, 3)
892        eq({ 0, 2, 1, 0 }, fn.getpos("'["))
893        -- Pastes some chunks on non-empty line
894        api.nvim_paste('aaaaaa', true, -1)
895        eq({ 0, 5, 1, 0 }, fn.getpos("'["))
896        api.nvim_paste('bbbbbb', true, 1)
897        eq({ 0, 5, 7, 0 }, fn.getpos("'["))
898        api.nvim_paste('cccccc', true, 2)
899        eq({ 0, 5, 7, 0 }, fn.getpos("'["))
900        api.nvim_paste('dddddd\n', true, 3)
901        eq({ 0, 5, 7, 0 }, fn.getpos("'["))
902        -- Pastes some empty chunks between non-empty chunks
903        api.nvim_paste('', true, 1)
904        eq({ 0, 5, 7, 0 }, fn.getpos("'["))
905        api.nvim_paste('a', true, 2)
906        eq({ 0, 6, 1, 0 }, fn.getpos("'["))
907        api.nvim_paste('', true, 2)
908        eq({ 0, 6, 1, 0 }, fn.getpos("'["))
909        api.nvim_paste('a', true, 3)
910        eq({ 0, 6, 1, 0 }, fn.getpos("'["))
911      end)
912      it('stream: Insert mode', function()
913        -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
914        feed('afoo<Esc>u')
915        feed('i')
916        api.nvim_paste('aaaaaa', false, 1)
917        api.nvim_paste('bbbbbb', false, 2)
918        api.nvim_paste('cccccc', false, 2)
919        api.nvim_paste('dddddd', false, 3)
920        expect('aaaaaabbbbbbccccccdddddd')
921        feed('<Esc>u')
922        expect('')
923      end)
924      describe('stream: Normal mode', function()
925        describe('on empty line', function()
926          before_each(function()
927            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
928            feed('afoo<Esc>u')
929          end)
930          after_each(function()
931            feed('u')
932            expect('')
933          end)
934          it('pasting one line', function()
935            api.nvim_paste('aaaaaa', false, 1)
936            api.nvim_paste('bbbbbb', false, 2)
937            api.nvim_paste('cccccc', false, 2)
938            api.nvim_paste('dddddd', false, 3)
939            expect('aaaaaabbbbbbccccccdddddd')
940          end)
941          it('pasting multiple lines', function()
942            api.nvim_paste('aaaaaa\n', false, 1)
943            api.nvim_paste('bbbbbb\n', false, 2)
944            api.nvim_paste('cccccc\n', false, 2)
945            api.nvim_paste('dddddd', false, 3)
946            expect([[
947            aaaaaa
948            bbbbbb
949            cccccc
950            dddddd]])
951          end)
952        end)
953        describe('not at the end of a line', function()
954          before_each(function()
955            feed('i||<Esc>')
956            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
957            feed('afoo<Esc>u')
958            feed('0')
959          end)
960          after_each(function()
961            feed('u')
962            expect('||')
963          end)
964          it('pasting one line', function()
965            api.nvim_paste('aaaaaa', false, 1)
966            api.nvim_paste('bbbbbb', false, 2)
967            api.nvim_paste('cccccc', false, 2)
968            api.nvim_paste('dddddd', false, 3)
969            expect('|aaaaaabbbbbbccccccdddddd|')
970          end)
971          it('pasting multiple lines', function()
972            api.nvim_paste('aaaaaa\n', false, 1)
973            api.nvim_paste('bbbbbb\n', false, 2)
974            api.nvim_paste('cccccc\n', false, 2)
975            api.nvim_paste('dddddd', false, 3)
976            expect([[
977            |aaaaaa
978            bbbbbb
979            cccccc
980            dddddd|]])
981          end)
982        end)
983        describe('at the end of a line', function()
984          before_each(function()
985            feed('i||<Esc>')
986            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
987            feed('afoo<Esc>u')
988            feed('2|')
989          end)
990          after_each(function()
991            feed('u')
992            expect('||')
993          end)
994          it('pasting one line', function()
995            api.nvim_paste('aaaaaa', false, 1)
996            api.nvim_paste('bbbbbb', false, 2)
997            api.nvim_paste('cccccc', false, 2)
998            api.nvim_paste('dddddd', false, 3)
999            expect('||aaaaaabbbbbbccccccdddddd')
1000          end)
1001          it('pasting multiple lines', function()
1002            api.nvim_paste('aaaaaa\n', false, 1)
1003            api.nvim_paste('bbbbbb\n', false, 2)
1004            api.nvim_paste('cccccc\n', false, 2)
1005            api.nvim_paste('dddddd', false, 3)
1006            expect([[
1007              ||aaaaaa
1008              bbbbbb
1009              cccccc
1010              dddddd]])
1011          end)
1012        end)
1013      end)
1014      describe('stream: Visual mode', function()
1015        describe('neither end at the end of a line', function()
1016          before_each(function()
1017            feed('i|xxx<CR>xxx|<Esc>')
1018            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
1019            feed('afoo<Esc>u')
1020            feed('3|vhk')
1021          end)
1022          after_each(function()
1023            feed('u')
1024            expect([[
1025            |xxx
1026            xxx|]])
1027          end)
1028          it('with non-empty chunks', function()
1029            api.nvim_paste('aaaaaa', false, 1)
1030            api.nvim_paste('bbbbbb', false, 2)
1031            api.nvim_paste('cccccc', false, 2)
1032            api.nvim_paste('dddddd', false, 3)
1033            expect('|aaaaaabbbbbbccccccdddddd|')
1034          end)
1035          it('with empty first chunk', function()
1036            api.nvim_paste('', false, 1)
1037            api.nvim_paste('bbbbbb', false, 2)
1038            api.nvim_paste('cccccc', false, 2)
1039            api.nvim_paste('dddddd', false, 3)
1040            expect('|bbbbbbccccccdddddd|')
1041          end)
1042          it('with all chunks empty', function()
1043            api.nvim_paste('', false, 1)
1044            api.nvim_paste('', false, 2)
1045            api.nvim_paste('', false, 2)
1046            api.nvim_paste('', false, 3)
1047            expect('||')
1048          end)
1049        end)
1050        describe('cursor at the end of a line', function()
1051          before_each(function()
1052            feed('i||xxx<CR>xxx<Esc>')
1053            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
1054            feed('afoo<Esc>u')
1055            feed('3|vko')
1056          end)
1057          after_each(function()
1058            feed('u')
1059            expect([[
1060              ||xxx
1061              xxx]])
1062          end)
1063          it('with non-empty chunks', function()
1064            api.nvim_paste('aaaaaa', false, 1)
1065            api.nvim_paste('bbbbbb', false, 2)
1066            api.nvim_paste('cccccc', false, 2)
1067            api.nvim_paste('dddddd', false, 3)
1068            expect('||aaaaaabbbbbbccccccdddddd')
1069          end)
1070          it('with empty first chunk', function()
1071            api.nvim_paste('', false, 1)
1072            api.nvim_paste('bbbbbb', false, 2)
1073            api.nvim_paste('cccccc', false, 2)
1074            api.nvim_paste('dddddd', false, 3)
1075            expect('||bbbbbbccccccdddddd')
1076          end)
1077        end)
1078        describe('other end at the end of a line', function()
1079          before_each(function()
1080            feed('i||xxx<CR>xxx<Esc>')
1081            -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
1082            feed('afoo<Esc>u')
1083            feed('3|vk')
1084          end)
1085          after_each(function()
1086            feed('u')
1087            expect([[
1088              ||xxx
1089              xxx]])
1090          end)
1091          it('with non-empty chunks', function()
1092            api.nvim_paste('aaaaaa', false, 1)
1093            api.nvim_paste('bbbbbb', false, 2)
1094            api.nvim_paste('cccccc', false, 2)
1095            api.nvim_paste('dddddd', false, 3)
1096            expect('||aaaaaabbbbbbccccccdddddd')
1097          end)
1098          it('with empty first chunk', function()
1099            api.nvim_paste('', false, 1)
1100            api.nvim_paste('bbbbbb', false, 2)
1101            api.nvim_paste('cccccc', false, 2)
1102            api.nvim_paste('dddddd', false, 3)
1103            expect('||bbbbbbccccccdddddd')
1104          end)
1105        end)
1106      end)
1107      describe('stream: linewise Visual mode', function()
1108        before_each(function()
1109          feed('i123456789<CR>987654321<CR>123456789<Esc>')
1110          -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
1111          feed('afoo<Esc>u')
1112        end)
1113        after_each(function()
1114          feed('u')
1115          expect([[
1116            123456789
1117            987654321
1118            123456789]])
1119        end)
1120        describe('selecting the start of a file', function()
1121          before_each(function()
1122            feed('ggV')
1123          end)
1124          it('pasting text without final new line', function()
1125            api.nvim_paste('aaaaaa\n', false, 1)
1126            api.nvim_paste('bbbbbb\n', false, 2)
1127            api.nvim_paste('cccccc\n', false, 2)
1128            api.nvim_paste('dddddd', false, 3)
1129            expect([[
1130              aaaaaa
1131              bbbbbb
1132              cccccc
1133              dddddd987654321
1134              123456789]])
1135          end)
1136          it('pasting text with final new line', function()
1137            api.nvim_paste('aaaaaa\n', false, 1)
1138            api.nvim_paste('bbbbbb\n', false, 2)
1139            api.nvim_paste('cccccc\n', false, 2)
1140            api.nvim_paste('dddddd\n', false, 3)
1141            expect([[
1142              aaaaaa
1143              bbbbbb
1144              cccccc
1145              dddddd
1146              987654321
1147              123456789]])
1148          end)
1149        end)
1150        describe('selecting the middle of a file', function()
1151          before_each(function()
1152            feed('2ggV')
1153          end)
1154          it('pasting text without final new line', function()
1155            api.nvim_paste('aaaaaa\n', false, 1)
1156            api.nvim_paste('bbbbbb\n', false, 2)
1157            api.nvim_paste('cccccc\n', false, 2)
1158            api.nvim_paste('dddddd', false, 3)
1159            expect([[
1160              123456789
1161              aaaaaa
1162              bbbbbb
1163              cccccc
1164              dddddd123456789]])
1165          end)
1166          it('pasting text with final new line', function()
1167            api.nvim_paste('aaaaaa\n', false, 1)
1168            api.nvim_paste('bbbbbb\n', false, 2)
1169            api.nvim_paste('cccccc\n', false, 2)
1170            api.nvim_paste('dddddd\n', false, 3)
1171            expect([[
1172              123456789
1173              aaaaaa
1174              bbbbbb
1175              cccccc
1176              dddddd
1177              123456789]])
1178          end)
1179        end)
1180        describe('selecting the end of a file', function()
1181          before_each(function()
1182            feed('3ggV')
1183          end)
1184          it('pasting text without final new line', function()
1185            api.nvim_paste('aaaaaa\n', false, 1)
1186            api.nvim_paste('bbbbbb\n', false, 2)
1187            api.nvim_paste('cccccc\n', false, 2)
1188            api.nvim_paste('dddddd', false, 3)
1189            expect([[
1190              123456789
1191              987654321
1192              aaaaaa
1193              bbbbbb
1194              cccccc
1195              dddddd]])
1196          end)
1197          it('pasting text with final new line', function()
1198            api.nvim_paste('aaaaaa\n', false, 1)
1199            api.nvim_paste('bbbbbb\n', false, 2)
1200            api.nvim_paste('cccccc\n', false, 2)
1201            api.nvim_paste('dddddd\n', false, 3)
1202            expect([[
1203              123456789
1204              987654321
1205              aaaaaa
1206              bbbbbb
1207              cccccc
1208              dddddd
1209              ]])
1210          end)
1211        end)
1212        describe('selecting the whole file', function()
1213          before_each(function()
1214            feed('ggVG')
1215          end)
1216          it('pasting text without final new line', function()
1217            api.nvim_paste('aaaaaa\n', false, 1)
1218            api.nvim_paste('bbbbbb\n', false, 2)
1219            api.nvim_paste('cccccc\n', false, 2)
1220            api.nvim_paste('dddddd', false, 3)
1221            expect([[
1222              aaaaaa
1223              bbbbbb
1224              cccccc
1225              dddddd]])
1226          end)
1227          it('pasting text with final new line', function()
1228            api.nvim_paste('aaaaaa\n', false, 1)
1229            api.nvim_paste('bbbbbb\n', false, 2)
1230            api.nvim_paste('cccccc\n', false, 2)
1231            api.nvim_paste('dddddd\n', false, 3)
1232            expect([[
1233              aaaaaa
1234              bbbbbb
1235              cccccc
1236              dddddd
1237              ]])
1238          end)
1239        end)
1240      end)
1241    end
1242    describe('without virtualedit,', function()
1243      run_streamed_paste_tests()
1244    end)
1245    describe('with virtualedit=onemore,', function()
1246      before_each(function()
1247        command('set virtualedit=onemore')
1248      end)
1249      run_streamed_paste_tests()
1250    end)
1251    describe('stream: terminal buffer', function()
1252      local eol = is_os('win') and '\r\n' or '\n'
1253      before_each(function()
1254        exec_lua(function()
1255          _G.input = {}
1256          _G.chan = vim.api.nvim_open_term(0, {
1257            on_input = function(_, _, _, data)
1258              if #data > 0 then
1259                table.insert(_G.input, data)
1260              end
1261            end,
1262            force_crlf = false,
1263          })
1264        end)
1265      end)
1266      local function run_terminal_streamed_paste_tests(check_dot_repeat)
1267        it('without bracketed paste mode in terminal', function()
1268          api.nvim_paste('AA\nBB\n', false, 1)
1269          eq({ 'AA', eol, 'BB', eol }, exec_lua('return _G.input'))
1270          api.nvim_paste('CC', false, 2)
1271          eq({ 'AA', eol, 'BB', eol, 'CC' }, exec_lua('return _G.input'))
1272          api.nvim_paste('\nDD', false, 3)
1273          eq({ 'AA', eol, 'BB', eol, 'CC', eol, 'DD' }, exec_lua('return _G.input'))
1274          if check_dot_repeat then
1275            exec_lua('_G.input = {}')
1276            feed('.')
1277            eq({ 'AA', eol, 'BB', eol, 'CC', eol, 'DD' }, exec_lua('return _G.input'))
1278          end
1279        end)
1280        it('with bracketed paste mode in terminal', function()
1281          exec_lua([[vim.api.nvim_chan_send(_G.chan, '\027[?2004h')]])
1282          api.nvim_paste('AA\nBB\n', false, 1)
1283          eq({ '\027[200~', 'AA', eol, 'BB', eol }, exec_lua('return _G.input'))
1284          api.nvim_paste('CC', false, 2)
1285          eq({ '\027[200~', 'AA', eol, 'BB', eol, 'CC' }, exec_lua('return _G.input'))
1286          api.nvim_paste('\nDD', false, 3)
1287          eq(
1288            { '\027[200~', 'AA', eol, 'BB', eol, 'CC', eol, 'DD', '\027[201~' },
1289            exec_lua('return _G.input')
1290          )
1291          if check_dot_repeat then
1292            exec_lua('_G.input = {}')
1293            feed('.')
1294            eq(
1295              { '\027[200~', 'AA', eol, 'BB', eol, 'CC', eol, 'DD', '\027[201~' },
1296              exec_lua('return _G.input')
1297            )
1298          end
1299        end)
1300      end
1301      describe('in Normal mode', function()
1302        run_terminal_streamed_paste_tests(true)
1303      end)
1304      describe('in Terminal mode', function()
1305        before_each(function()
1306          feed('i')
1307          eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1308        end)
1309        run_terminal_streamed_paste_tests(false)
1310      end)
1311    end)
1312    it('non-streaming', function()
1313      -- With final "\n".
1314      api.nvim_paste('line 1\nline 2\nline 3\n', true, -1)
1315      expect([[
1316        line 1
1317        line 2
1318        line 3
1319        ]])
1320      eq({ 0, 4, 1, 0 }, fn.getpos('.')) -- Cursor follows the paste.
1321      eq(false, api.nvim_get_option_value('paste', {}))
1322      command('%delete _')
1323      -- Without final "\n".
1324      api.nvim_paste('line 1\nline 2\nline 3', true, -1)
1325      expect([[
1326        line 1
1327        line 2
1328        line 3]])
1329      eq({ 0, 3, 6, 0 }, fn.getpos('.'))
1330      command('%delete _')
1331      -- CRLF #10872
1332      api.nvim_paste('line 1\r\nline 2\r\nline 3\r\n', true, -1)
1333      expect([[
1334        line 1
1335        line 2
1336        line 3
1337        ]])
1338      eq({ 0, 4, 1, 0 }, fn.getpos('.'))
1339      command('%delete _')
1340      -- CRLF without final "\n".
1341      api.nvim_paste('line 1\r\nline 2\r\nline 3\r', true, -1)
1342      expect([[
1343        line 1
1344        line 2
1345        line 3
1346        ]])
1347      eq({ 0, 4, 1, 0 }, fn.getpos('.'))
1348      command('%delete _')
1349      -- CRLF without final "\r\n".
1350      api.nvim_paste('line 1\r\nline 2\r\nline 3', true, -1)
1351      expect([[
1352        line 1
1353        line 2
1354        line 3]])
1355      eq({ 0, 3, 6, 0 }, fn.getpos('.'))
1356      command('%delete _')
1357      -- Various other junk.
1358      api.nvim_paste('line 1\r\n\r\rline 2\nline 3\rline 4\r', true, -1)
1359      expect('line 1\n\n\nline 2\nline 3\nline 4\n')
1360      eq({ 0, 7, 1, 0 }, fn.getpos('.'))
1361      eq(false, api.nvim_get_option_value('paste', {}))
1362    end)
1363    it('Replace-mode', function()
1364      -- Within single line
1365      api.nvim_put({ 'aabbccdd', 'eeffgghh', 'iijjkkll' }, 'c', true, false)
1366      command('normal l')
1367      command('startreplace')
1368      api.nvim_paste('123456', true, -1)
1369      expect([[
1370      a123456d
1371      eeffgghh
1372      iijjkkll]])
1373      command('%delete _')
1374      -- Across lines
1375      api.nvim_put({ 'aabbccdd', 'eeffgghh', 'iijjkkll' }, 'c', true, false)
1376      command('normal l')
1377      command('startreplace')
1378      api.nvim_paste('123\n456', true, -1)
1379      expect([[
1380      a123
1381      456d
1382      eeffgghh
1383      iijjkkll]])
1384    end)
1385    it('when searching in Visual mode', function()
1386      feed('v/')
1387      api.nvim_paste('aabbccdd', true, -1)
1388      eq('aabbccdd', fn.getcmdline())
1389      expect('')
1390    end)
1391    it('mappings are disabled in Cmdline mode', function()
1392      command('cnoremap a b')
1393      feed(':')
1394      api.nvim_paste('a', true, -1)
1395      eq('a', fn.getcmdline())
1396    end)
1397    it('pasted text is saved in cmdline history when <CR> comes from mapping #20957', function()
1398      command('cnoremap <CR> <CR>')
1399      feed(':')
1400      api.nvim_paste('echo', true, -1)
1401      eq('', fn.histget(':'))
1402      feed('<CR>')
1403      eq('echo', fn.histget(':'))
1404    end)
1405    it('pasting with empty last chunk in Cmdline mode', function()
1406      local screen = Screen.new(20, 4)
1407      feed(':')
1408      api.nvim_paste('Foo', true, 1)
1409      api.nvim_paste('', true, 3)
1410      screen:expect([[
1411                            |
1412        {1:~                   }|*2
1413        :Foo^                |
1414      ]])
1415    end)
1416    it('pasting text with control characters in Cmdline mode', function()
1417      local screen = Screen.new(20, 4)
1418      feed(':')
1419      api.nvim_paste('normal! \023\022\006\027', true, -1)
1420      screen:expect([[
1421                            |
1422        {1:~                   }|*2
1423        :normal! {18:^W^V^F^[}^   |
1424      ]])
1425    end)
1426    it('crlf=false does not break lines at CR, CRLF', function()
1427      api.nvim_paste('line 1\r\n\r\rline 2\nline 3\rline 4\r', false, -1)
1428      local expected = 'line 1\r\n\r\rline 2\nline 3\rline 4\r'
1429      expect(expected)
1430      eq({ 0, 3, 14, 0 }, fn.getpos('.'))
1431      feed('u') -- Undo.
1432      expect('')
1433      feed('.') -- Dot-repeat.
1434      expect(expected)
1435    end)
1436    describe('repeating a paste via redo/recording', function()
1437      -- Test with indent and control chars and multibyte chars containing 0x80 bytes
1438      local text = dedent(([[
1439      foo
1440        bar
1441          baz
1442      !!!%s!!!%s!!!%s!!!
1443      最…倒…倀…
1444      ]]):format('\0', '\2\3\6\21\22\23\24\27', '\127'))
1445      before_each(function()
1446        api.nvim_set_option_value('autoindent', true, {})
1447      end)
1448      local function test_paste_repeat_normal_insert(is_insert)
1449        feed('qr' .. (is_insert and 'i' or ''))
1450        eq('r', fn.reg_recording())
1451        api.nvim_paste(text, true, -1)
1452        feed(is_insert and '<Esc>' or '')
1453        expect(text)
1454        feed('.')
1455        expect(text:rep(2))
1456        feed('q')
1457        eq('', fn.reg_recording())
1458        feed('3.')
1459        expect(text:rep(5))
1460        feed('2@r')
1461        expect(text:rep(9))
1462      end
1463      it('works in Normal mode', function()
1464        test_paste_repeat_normal_insert(false)
1465      end)
1466      it('works in Insert mode', function()
1467        test_paste_repeat_normal_insert(true)
1468      end)
1469      local function test_paste_repeat_visual_select(is_select)
1470        insert(('xxx\n'):rep(5))
1471        feed('ggqr' .. (is_select and 'gH' or 'V'))
1472        api.nvim_paste(text, true, -1)
1473        feed('q')
1474        expect(text .. ('xxx\n'):rep(4))
1475        feed('2@r')
1476        expect(text:rep(3) .. ('xxx\n'):rep(2))
1477      end
1478      it('works in Visual mode (recording only)', function()
1479        test_paste_repeat_visual_select(false)
1480      end)
1481      it('works in Select mode (recording only)', function()
1482        test_paste_repeat_visual_select(true)
1483      end)
1484    end)
1485    it('in a mapping recorded in a macro', function()
1486      command([[nnoremap <F2> <Cmd>call nvim_paste('foo', v:false, -1)<CR>]])
1487      feed('qr<F2>$q')
1488      expect('foo')
1489      feed('@r') -- repeating a macro containing the mapping should only paste once
1490      expect('foofoo')
1491    end)
1492    local function test_paste_cancel_error(is_error)
1493      before_each(function()
1494        exec_lua(([[
1495          vim.paste = (function(overridden)
1496            return function(lines, phase)
1497              for i, line in ipairs(lines) do
1498                if line == 'CANCEL' then
1499                  %s
1500                end
1501              end
1502              return overridden(lines, phase)
1503            end
1504          end)(vim.paste)
1505        ]]):format(is_error and 'error("fake fail")' or 'return false'))
1506      end)
1507      local function check_paste_cancel_error(data, crlf, phase)
1508        if is_error then
1509          eq('fake fail', pcall_err(api.nvim_paste, data, crlf, phase))
1510        else
1511          eq(false, api.nvim_paste(data, crlf, phase))
1512        end
1513      end
1514      it('in phase -1', function()
1515        feed('A')
1516        check_paste_cancel_error('CANCEL', true, -1)
1517        feed('<Esc>')
1518        expect('')
1519        feed('.')
1520        expect('')
1521      end)
1522      it('in phase 1', function()
1523        feed('A')
1524        check_paste_cancel_error('CANCEL', true, 1)
1525        feed('<Esc>')
1526        expect('')
1527        feed('.')
1528        expect('')
1529      end)
1530      it('in phase 2', function()
1531        feed('A')
1532        eq(true, api.nvim_paste('aaa', true, 1))
1533        expect('aaa')
1534        check_paste_cancel_error('CANCEL', true, 2)
1535        feed('<Esc>')
1536        expect('aaa')
1537        feed('.')
1538        expect('aaaaaa')
1539      end)
1540      it('in phase 3', function()
1541        feed('A')
1542        eq(true, api.nvim_paste('aaa', true, 1))
1543        expect('aaa')
1544        eq(true, api.nvim_paste('bbb', true, 2))
1545        expect('aaabbb')
1546        check_paste_cancel_error('CANCEL', true, 3)
1547        feed('<Esc>')
1548        expect('aaabbb')
1549        feed('.')
1550        expect('aaabbbaaabbb')
1551      end)
1552    end
1553    describe('vim.paste() cancel', function()
1554      test_paste_cancel_error(false)
1555    end)
1556    describe('vim.paste() error', function()
1557      test_paste_cancel_error(true)
1558    end)
1559  end)
1560
1561  describe('nvim_put', function()
1562    it('validation', function()
1563      eq(
1564        "Invalid 'line': expected String, got Integer",
1565        pcall_err(request, 'nvim_put', { 42 }, 'l', false, false)
1566      )
1567      eq("Invalid 'type': 'x'", pcall_err(request, 'nvim_put', { 'foo' }, 'x', false, false))
1568    end)
1569    it("fails if 'nomodifiable'", function()
1570      command('set nomodifiable')
1571      eq(
1572        [[Vim:E21: Cannot make changes, 'modifiable' is off]],
1573        pcall_err(request, 'nvim_put', { 'a', 'b' }, 'l', true, true)
1574      )
1575    end)
1576    it('inserts text', function()
1577      exec([[
1578        let g:pre_event = []
1579        let g:post_event = []
1580        au TextPutPre * let g:pre_event = copy(v:event)
1581        au TextPutPost * let g:post_event = copy(v:event)
1582      ]])
1583      -- linewise
1584      local lines = { 'line 1', 'line 2', 'line 3' }
1585      local expected_event = {
1586        regcontents = lines,
1587        regname = '_',
1588        operator = 'p',
1589        regtype = 'V',
1590        visual = false,
1591      }
1592      api.nvim_put(lines, 'l', true, true)
1593      expect([[
1594
1595        line 1
1596        line 2
1597        line 3]])
1598      eq({ 0, 4, 1, 0 }, fn.getpos('.'))
1599      eq(expected_event, api.nvim_get_var('pre_event'))
1600      eq(expected_event, api.nvim_get_var('post_event'))
1601      command('%delete _')
1602      -- charwise
1603      expected_event.regtype = 'v'
1604      api.nvim_put({ 'line 1', 'line 2', 'line 3' }, 'c', true, false)
1605      expect([[
1606        line 1
1607        line 2
1608        line 3]])
1609      eq({ 0, 1, 1, 0 }, fn.getpos('.')) -- follow=false
1610      eq(expected_event, api.nvim_get_var('pre_event'))
1611      eq(expected_event, api.nvim_get_var('post_event'))
1612      -- blockwise
1613      lines = { 'AA', 'BB' }
1614      expected_event.regcontents = lines
1615      expected_event.regtype = '\0222'
1616      api.nvim_put(lines, 'b', true, true)
1617      expect([[
1618        lAAine 1
1619        lBBine 2
1620        line 3]])
1621      eq({ 0, 2, 4, 0 }, fn.getpos('.'))
1622      eq(expected_event, api.nvim_get_var('pre_event'))
1623      eq(expected_event, api.nvim_get_var('post_event'))
1624      command('%delete _')
1625      -- Empty lines list.
1626      api.nvim_put({}, 'c', true, true)
1627      eq({ 0, 1, 1, 0 }, fn.getpos('.'))
1628      expect([[]])
1629      -- Single empty line.
1630      api.nvim_put({ '' }, 'c', true, true)
1631      eq({ 0, 1, 1, 0 }, fn.getpos('.'))
1632      expect([[
1633      ]])
1634      api.nvim_put({ 'AB' }, 'c', true, true)
1635      -- after=false, follow=true
1636      lines = { 'line 1', 'line 2' }
1637      expected_event.regcontents = lines
1638      expected_event.regtype = 'v'
1639      expected_event.operator = 'P'
1640      api.nvim_put(lines, 'c', false, true)
1641      expect([[
1642        Aline 1
1643        line 2B]])
1644      eq({ 0, 2, 7, 0 }, fn.getpos('.'))
1645      eq(expected_event, api.nvim_get_var('pre_event'))
1646      eq(expected_event, api.nvim_get_var('post_event'))
1647      command('%delete _')
1648      api.nvim_put({ 'AB' }, 'c', true, true)
1649      -- after=false, follow=false
1650      api.nvim_put(lines, 'c', false, false)
1651      expect([[
1652        Aline 1
1653        line 2B]])
1654      eq({ 0, 1, 2, 0 }, fn.getpos('.'))
1655      eq(expected_event, api.nvim_get_var('pre_event'))
1656      eq(expected_event, api.nvim_get_var('post_event'))
1657      eq('', api.nvim_eval('v:errmsg'))
1658    end)
1659
1660    it('detects charwise/linewise text (empty {type})', function()
1661      -- linewise (final item is empty string)
1662      api.nvim_put({ 'line 1', 'line 2', 'line 3', '' }, '', true, true)
1663      expect([[
1664
1665        line 1
1666        line 2
1667        line 3]])
1668      eq({ 0, 4, 1, 0 }, fn.getpos('.'))
1669      command('%delete _')
1670      -- charwise (final item is non-empty)
1671      api.nvim_put({ 'line 1', 'line 2', 'line 3' }, '', true, true)
1672      expect([[
1673        line 1
1674        line 2
1675        line 3]])
1676      eq({ 0, 3, 6, 0 }, fn.getpos('.'))
1677    end)
1678
1679    it('allows block width', function()
1680      -- behave consistently with setreg(); support "\022{NUM}" return by getregtype()
1681      api.nvim_put({ 'line 1', 'line 2', 'line 3' }, 'l', false, false)
1682      expect([[
1683        line 1
1684        line 2
1685        line 3
1686        ]])
1687
1688      -- larger width create spaces
1689      api.nvim_put({ 'a', 'bc' }, 'b3', false, false)
1690      expect([[
1691        a  line 1
1692        bc line 2
1693        line 3
1694        ]])
1695      -- smaller width is ignored
1696      api.nvim_put({ 'xxx', 'yyy' }, '\0221', false, true)
1697      expect([[
1698        xxxa  line 1
1699        yyybc line 2
1700        line 3
1701        ]])
1702      eq("Invalid 'type': 'bx'", pcall_err(api.nvim_put, { 'xxx', 'yyy' }, 'bx', false, true))
1703      eq("Invalid 'type': 'b3x'", pcall_err(api.nvim_put, { 'xxx', 'yyy' }, 'b3x', false, true))
1704    end)
1705
1706    it('computes block width correctly when not specified #35034', function()
1707      api.nvim_put({ 'line 1', 'line 2', 'line 3' }, 'l', false, false)
1708      -- block width should be 4
1709      api.nvim_put({ 'あい', 'xxx', 'xx' }, 'b', false, false)
1710      expect([[
1711        あいline 1
1712        xxx line 2
1713        xx  line 3
1714        ]])
1715    end)
1716  end)
1717
1718  describe('nvim_strwidth', function()
1719    it('works', function()
1720      eq(3, api.nvim_strwidth('abc'))
1721      -- 6 + (neovim)
1722      -- 19 * 2 (each japanese character occupies two cells)
1723      eq(44, api.nvim_strwidth('neovimのデザインかなりまともなのになってる。'))
1724    end)
1725
1726    it('cannot handle NULs', function()
1727      eq(0, api.nvim_strwidth('\0abc'))
1728    end)
1729
1730    it('can handle emoji with variant selectors and ZWJ', function()
1731      local selector = '❤️'
1732      eq(2, fn.strchars(selector))
1733      eq(1, fn.strcharlen(selector))
1734      eq(2, api.nvim_strwidth(selector))
1735
1736      local no_selector = '❤'
1737      eq(1, fn.strchars(no_selector))
1738      eq(1, fn.strcharlen(no_selector))
1739      eq(1, api.nvim_strwidth(no_selector))
1740
1741      local selector_zwj_selector = '🏳️‍⚧️'
1742      eq(5, fn.strchars(selector_zwj_selector))
1743      eq(1, fn.strcharlen(selector_zwj_selector))
1744      eq(2, api.nvim_strwidth(selector_zwj_selector))
1745
1746      local emoji_zwj_emoji = '🧑‍🌾'
1747      eq(3, fn.strchars(emoji_zwj_emoji))
1748      eq(1, fn.strcharlen(emoji_zwj_emoji))
1749      eq(2, api.nvim_strwidth(emoji_zwj_emoji))
1750    end)
1751  end)
1752
1753  describe('nvim_get_current_line, nvim_set_current_line', function()
1754    it('works', function()
1755      eq('', api.nvim_get_current_line())
1756      api.nvim_set_current_line('abc')
1757      eq('abc', api.nvim_get_current_line())
1758    end)
1759  end)
1760
1761  describe('set/get/del variables', function()
1762    it('validation', function()
1763      eq('Key not found: bogus', pcall_err(api.nvim_get_var, 'bogus'))
1764      eq('Key not found: bogus', pcall_err(api.nvim_del_var, 'bogus'))
1765    end)
1766
1767    it('nvim_get_var, nvim_set_var, nvim_del_var', function()
1768      api.nvim_set_var('lua', { 1, 2, { ['3'] = 1 } })
1769      eq({ 1, 2, { ['3'] = 1 } }, api.nvim_get_var('lua'))
1770      eq({ 1, 2, { ['3'] = 1 } }, api.nvim_eval('g:lua'))
1771      eq(1, fn.exists('g:lua'))
1772      api.nvim_del_var('lua')
1773      eq(0, fn.exists('g:lua'))
1774      eq('Key not found: lua', pcall_err(api.nvim_del_var, 'lua'))
1775      api.nvim_set_var('lua', 1)
1776
1777      -- Empty keys are allowed in Vim dicts (and msgpack).
1778      api.nvim_set_var('dict_empty_key', { [''] = 'empty key' })
1779      eq({ [''] = 'empty key' }, api.nvim_get_var('dict_empty_key'))
1780
1781      -- Set locked g: var.
1782      command('lockvar lua')
1783      eq('Key is locked: lua', pcall_err(api.nvim_del_var, 'lua'))
1784      eq('Key is locked: lua', pcall_err(api.nvim_set_var, 'lua', 1))
1785
1786      exec([[
1787        function Test()
1788        endfunction
1789        function s:Test()
1790        endfunction
1791        let g:Unknown_func = function('Test')
1792        let g:Unknown_script_func = function('s:Test')
1793      ]])
1794      eq(NIL, api.nvim_get_var('Unknown_func'))
1795      eq(NIL, api.nvim_get_var('Unknown_script_func'))
1796
1797      -- Check if autoload works properly
1798      local xhome = 'Xhome_api'
1799      local xconfig = ('%s/Xconfig'):format(xhome)
1800      local xdata = ('%s/Xdata'):format(xhome)
1801      local autoload_folder = ('%s/nvim/autoload'):format(xconfig)
1802      local autoload_file = ('%s/testload.vim'):format(autoload_folder)
1803      mkdir_p(autoload_folder)
1804      write_file(autoload_file, [[let testload#value = 2]])
1805
1806      clear { args_rm = { '-u' }, env = { XDG_CONFIG_HOME = xconfig, XDG_DATA_HOME = xdata } }
1807      eq(2, api.nvim_get_var('testload#value'))
1808      rmdir(xhome)
1809    end)
1810
1811    it('nvim_get_vvar, nvim_set_vvar', function()
1812      eq('Key is read-only: count', pcall_err(request, 'nvim_set_vvar', 'count', 42))
1813      eq('Dict is locked', pcall_err(request, 'nvim_set_vvar', 'nosuchvar', 42))
1814      api.nvim_set_vvar('errmsg', 'set by API')
1815      eq('set by API', api.nvim_get_vvar('errmsg'))
1816      api.nvim_set_vvar('completed_item', { word = 'a', user_data = vim.empty_dict() })
1817      eq({}, api.nvim_get_vvar('completed_item')['user_data'])
1818      api.nvim_set_vvar('errmsg', 42)
1819      eq('42', eval('v:errmsg'))
1820      api.nvim_set_vvar('oldfiles', { 'one', 'two' })
1821      eq({ 'one', 'two' }, eval('v:oldfiles'))
1822      api.nvim_set_vvar('oldfiles', {})
1823      eq({}, eval('v:oldfiles'))
1824      eq(
1825        'Setting v:oldfiles to value with wrong type',
1826        pcall_err(api.nvim_set_vvar, 'oldfiles', 'a')
1827      )
1828      eq({}, eval('v:oldfiles'))
1829
1830      feed('i foo foo foo<Esc>0/foo<CR>')
1831      eq({ 1, 1 }, api.nvim_win_get_cursor(0))
1832      eq(1, eval('v:searchforward'))
1833      feed('n')
1834      eq({ 1, 5 }, api.nvim_win_get_cursor(0))
1835      api.nvim_set_vvar('searchforward', 0)
1836      eq(0, eval('v:searchforward'))
1837      feed('n')
1838      eq({ 1, 1 }, api.nvim_win_get_cursor(0))
1839      api.nvim_set_vvar('searchforward', 1)
1840      eq(1, eval('v:searchforward'))
1841      feed('n')
1842      eq({ 1, 5 }, api.nvim_win_get_cursor(0))
1843
1844      local screen = Screen.new(60, 3)
1845      eq(1, eval('v:hlsearch'))
1846      screen:expect {
1847        grid = [[
1848         {10:foo} {10:^foo} {10:foo}                                                |
1849        {1:~                                                           }|
1850                                                                    |
1851      ]],
1852      }
1853      api.nvim_set_vvar('hlsearch', 0)
1854      eq(0, eval('v:hlsearch'))
1855      screen:expect {
1856        grid = [[
1857         foo ^foo foo                                                |
1858        {1:~                                                           }|
1859                                                                    |
1860      ]],
1861      }
1862      api.nvim_set_vvar('hlsearch', 1)
1863      eq(1, eval('v:hlsearch'))
1864      screen:expect {
1865        grid = [[
1866         {10:foo} {10:^foo} {10:foo}                                                |
1867        {1:~                                                           }|
1868                                                                    |
1869      ]],
1870      }
1871    end)
1872
1873    it('vim_set_var returns the old value', function()
1874      local val1 = { 1, 2, { ['3'] = 1 } }
1875      local val2 = { 4, 7 }
1876      eq(NIL, request('vim_set_var', 'lua', val1))
1877      eq(val1, request('vim_set_var', 'lua', val2))
1878    end)
1879
1880    it('vim_del_var returns the old value', function()
1881      local val1 = { 1, 2, { ['3'] = 1 } }
1882      local val2 = { 4, 7 }
1883      eq(NIL, request('vim_set_var', 'lua', val1))
1884      eq(val1, request('vim_set_var', 'lua', val2))
1885      eq(val2, request('vim_del_var', 'lua'))
1886    end)
1887
1888    it('preserves values with NULs in them', function()
1889      api.nvim_set_var('xxx', 'ab\0cd')
1890      eq('ab\000cd', api.nvim_get_var('xxx'))
1891    end)
1892  end)
1893
1894  describe('nvim_get_option_value, nvim_set_option_value', function()
1895    it('works', function()
1896      ok(api.nvim_get_option_value('equalalways', {}))
1897      api.nvim_set_option_value('equalalways', false, {})
1898      ok(not api.nvim_get_option_value('equalalways', {}))
1899    end)
1900
1901    it('Lua funcref RPC value is a `:map`-style "<Lua …>" string', function()
1902      exec_lua('vim.o.operatorfunc = function() end')
1903      matches('^<Lua %d+.*>$', api.nvim_get_option_value('operatorfunc', {}))
1904    end)
1905
1906    it('works to get global value of local options', function()
1907      eq(false, api.nvim_get_option_value('lisp', {}))
1908      eq(8, api.nvim_get_option_value('shiftwidth', {}))
1909    end)
1910
1911    it('works to set global value of local options', function()
1912      api.nvim_set_option_value('lisp', true, { scope = 'global' })
1913      eq(true, api.nvim_get_option_value('lisp', { scope = 'global' }))
1914      eq(false, api.nvim_get_option_value('lisp', {}))
1915      eq(nil, command_output('setglobal lisp?'):match('nolisp'))
1916      eq('nolisp', command_output('setlocal lisp?'):match('nolisp'))
1917      api.nvim_set_option_value('shiftwidth', 20, { scope = 'global' })
1918      eq('20', command_output('setglobal shiftwidth?'):match('%d+'))
1919      eq('8', command_output('setlocal shiftwidth?'):match('%d+'))
1920    end)
1921
1922    it('updates where the option was last set from', function()
1923      api.nvim_set_option_value('equalalways', false, {})
1924      local status, rv = pcall(command_output, 'verbose set equalalways?')
1925      eq(true, status)
1926      matches('noequalalways\n' .. '\tLast set from API client %(channel id %d+%)', rv)
1927
1928      api.nvim_exec_lua('vim.api.nvim_set_option_value("equalalways", true, {})', {})
1929      status, rv = pcall(command_output, 'verbose set equalalways?')
1930      eq(true, status)
1931      eq('  equalalways\n\tLast set from Lua (run Nvim with -V1 for more details)', rv)
1932    end)
1933
1934    it('updates whether the option has ever been set #25025', function()
1935      eq(false, api.nvim_get_option_info2('autochdir', {}).was_set)
1936      api.nvim_set_option_value('autochdir', true, {})
1937      eq(true, api.nvim_get_option_info2('autochdir', {}).was_set)
1938
1939      eq(false, api.nvim_get_option_info2('cmdwinheight', {}).was_set)
1940      api.nvim_set_option_value('cmdwinheight', 10, {})
1941      eq(true, api.nvim_get_option_info2('cmdwinheight', {}).was_set)
1942
1943      eq(false, api.nvim_get_option_info2('debug', {}).was_set)
1944      api.nvim_set_option_value('debug', 'beep', {})
1945      eq(true, api.nvim_get_option_info2('debug', {}).was_set)
1946    end)
1947
1948    it('validation', function()
1949      eq("Unknown option 'foobar'", pcall_err(api.nvim_set_option_value, 'foobar', 'baz', {}))
1950      eq(
1951        "Unknown option 'foobar'",
1952        pcall_err(api.nvim_set_option_value, 'foobar', 'baz', { win = api.nvim_get_current_win() })
1953      )
1954      eq(
1955        "Invalid 'scope': expected 'local' or 'global'",
1956        pcall_err(api.nvim_get_option_value, 'scrolloff', { scope = 'bogus' })
1957      )
1958      eq(
1959        "Invalid 'scope': expected 'local' or 'global'",
1960        pcall_err(api.nvim_set_option_value, 'scrolloff', 1, { scope = 'bogus' })
1961      )
1962      eq(
1963        "Invalid 'scope': expected String, got Integer",
1964        pcall_err(api.nvim_get_option_value, 'scrolloff', { scope = 42 })
1965      )
1966      matches(
1967        "Invalid 'scrolloff': expected a valid type, got Array",
1968        pcall_err(api.nvim_set_option_value, 'scrolloff', {}, {})
1969      )
1970      matches(
1971        "Invalid 'scrolloff': expected a valid type, got Boolean",
1972        pcall_err(api.nvim_set_option_value, 'scrolloff', true, {})
1973      )
1974      matches(
1975        "Invalid 'scrolloff': expected a valid type, got String",
1976        pcall_err(api.nvim_set_option_value, 'scrolloff', 'wrong', {})
1977      )
1978      local tab1 = api.nvim_get_current_tabpage()
1979      eq(
1980        "Conflict: 'tab' not allowed with 'win', 'buf', 'filetype' or 'scope'",
1981        pcall_err(
1982          api.nvim_get_option_value,
1983          'cmdheight',
1984          { tab = tab1, win = api.nvim_get_current_win() }
1985        )
1986      )
1987      eq(
1988        "Conflict: 'tab' not allowed with 'win', 'buf', 'filetype' or 'scope'",
1989        pcall_err(api.nvim_get_option_value, 'cmdheight', {
1990          tab = tab1,
1991          scope = 'local',
1992        })
1993      )
1994      eq(
1995        "Conflict: 'tab' not allowed with 'shiftwidth'",
1996        pcall_err(api.nvim_get_option_value, 'shiftwidth', { tab = tab1 })
1997      )
1998      eq(
1999        "Conflict: 'tab' not allowed with 'shiftwidth'",
2000        pcall_err(api.nvim_set_option_value, 'shiftwidth', 2, { tab = tab1 })
2001      )
2002      eq(
2003        "Conflict: 'tab' not allowed with this function",
2004        pcall_err(api.nvim_get_option_info2, 'cmdheight', { tab = tab1 })
2005      )
2006      eq(
2007        "Conflict: 'filetype' not allowed with 'scope', 'buf', 'win' or 'tab'",
2008        pcall_err(api.nvim_get_option_value, 'cmdheight', { filetype = 'c', tab = 0 })
2009      )
2010      eq(
2011        "Invalid 'operation': expected 'set', 'append', 'prepend', or 'remove'",
2012        pcall_err(api.nvim_set_option_value, 'wildignore', { 'x' }, { operation = 'bogus' })
2013      )
2014      eq(
2015        "Conflict: 'append' not allowed with boolean options",
2016        pcall_err(api.nvim_set_option_value, 'number', true, { operation = 'append' })
2017      )
2018    end)
2019
2020    it("tabpage-local option ('cmdheight') #31140", function()
2021      api.nvim_set_option_value('cmdheight', 1, {})
2022      local tab1 = api.nvim_get_current_tabpage()
2023      eq(1, api.nvim_get_option_value('cmdheight', { tab = 0 }))
2024      eq(1, api.nvim_get_option_value('cmdheight', { tab = tab1 }))
2025      eq(1, api.nvim_get_option_value('cmdheight', {}))
2026      command('tabnew')
2027      local tab2 = api.nvim_get_current_tabpage()
2028      api.nvim_set_option_value('cmdheight', 4, {})
2029      eq(4, api.nvim_get_option_value('cmdheight', { tab = tab2 }))
2030      eq(1, api.nvim_get_option_value('cmdheight', { tab = tab1 }))
2031      eq(4, api.nvim_get_option_value('cmdheight', {}))
2032
2033      -- Set non-current tab option.
2034      api.nvim_set_option_value('cmdheight', 3, { tab = tab1 })
2035      eq(3, api.nvim_get_option_value('cmdheight', { tab = tab1 }))
2036      eq(4, api.nvim_get_option_value('cmdheight', { tab = tab2 }))
2037      eq(4, api.nvim_get_option_value('cmdheight', {}))
2038      command('tabnext')
2039      eq(3, api.nvim_get_option_value('cmdheight', {}))
2040    end)
2041
2042    it('can get local values when global value is set', function()
2043      eq(0, api.nvim_get_option_value('scrolloff', {}))
2044      eq(-1, api.nvim_get_option_value('scrolloff', { scope = 'local' }))
2045    end)
2046
2047    it('can set global and local values', function()
2048      api.nvim_set_option_value('makeprg', 'hello', {})
2049      eq('hello', api.nvim_get_option_value('makeprg', {}))
2050      eq('', api.nvim_get_option_value('makeprg', { scope = 'local' }))
2051      api.nvim_set_option_value('makeprg', 'world', { scope = 'local' })
2052      eq('world', api.nvim_get_option_value('makeprg', { scope = 'local' }))
2053      api.nvim_set_option_value('makeprg', 'goodbye', { scope = 'global' })
2054      eq('goodbye', api.nvim_get_option_value('makeprg', { scope = 'global' }))
2055      api.nvim_set_option_value('makeprg', 'hello', {})
2056      eq('hello', api.nvim_get_option_value('makeprg', { scope = 'global' }))
2057      eq('hello', api.nvim_get_option_value('makeprg', {}))
2058      eq('', api.nvim_get_option_value('makeprg', { scope = 'local' }))
2059    end)
2060
2061    it('clears the local value of an option with nil', function()
2062      -- Set global value
2063      api.nvim_set_option_value('shiftwidth', 42, {})
2064      eq(42, api.nvim_get_option_value('shiftwidth', {}))
2065
2066      -- Set local value
2067      api.nvim_set_option_value('shiftwidth', 8, { scope = 'local' })
2068      eq(8, api.nvim_get_option_value('shiftwidth', {}))
2069      eq(8, api.nvim_get_option_value('shiftwidth', { scope = 'local' }))
2070      eq(42, api.nvim_get_option_value('shiftwidth', { scope = 'global' }))
2071
2072      -- Clear value without scope
2073      api.nvim_set_option_value('shiftwidth', NIL, {})
2074      eq(42, api.nvim_get_option_value('shiftwidth', {}))
2075      eq(42, api.nvim_get_option_value('shiftwidth', { scope = 'local' }))
2076
2077      -- Clear value with explicit scope
2078      api.nvim_set_option_value('shiftwidth', 8, { scope = 'local' })
2079      api.nvim_set_option_value('shiftwidth', NIL, { scope = 'local' })
2080      eq(42, api.nvim_get_option_value('shiftwidth', {}))
2081      eq(42, api.nvim_get_option_value('shiftwidth', { scope = 'local' }))
2082
2083      -- Now try with options with a special "local is unset" value (e.g. 'undolevels')
2084      api.nvim_set_option_value('undolevels', 1000, {})
2085      api.nvim_set_option_value('undolevels', 1200, { scope = 'local' })
2086      eq(1200, api.nvim_get_option_value('undolevels', { scope = 'local' }))
2087      api.nvim_set_option_value('undolevels', NIL, { scope = 'local' })
2088      eq(-123456, api.nvim_get_option_value('undolevels', { scope = 'local' }))
2089      eq(1000, api.nvim_get_option_value('undolevels', {}))
2090
2091      api.nvim_set_option_value('autoread', true, {})
2092      api.nvim_set_option_value('autoread', false, { scope = 'local' })
2093      eq(false, api.nvim_get_option_value('autoread', { scope = 'local' }))
2094      api.nvim_set_option_value('autoread', NIL, { scope = 'local' })
2095      eq(NIL, api.nvim_get_option_value('autoread', { scope = 'local' }))
2096      eq(true, api.nvim_get_option_value('autoread', {}))
2097    end)
2098
2099    it('set window options', function()
2100      api.nvim_set_option_value('colorcolumn', '4,3', {})
2101      eq('4,3', api.nvim_get_option_value('colorcolumn', { scope = 'local' }))
2102      command('set modified hidden')
2103      command('enew') -- edit new buffer, window option is preserved
2104      eq('4,3', api.nvim_get_option_value('colorcolumn', { scope = 'local' }))
2105    end)
2106
2107    it('set local window options', function()
2108      api.nvim_set_option_value('colorcolumn', '4,3', { win = 0, scope = 'local' })
2109      eq('4,3', api.nvim_get_option_value('colorcolumn', { win = 0, scope = 'local' }))
2110      command('set modified hidden')
2111      command('enew') -- edit new buffer, window option is reset
2112      eq('', api.nvim_get_option_value('colorcolumn', { win = 0, scope = 'local' }))
2113    end)
2114
2115    it('get buffer or window-local options', function()
2116      command('new')
2117      local buf = api.nvim_get_current_buf()
2118      api.nvim_set_option_value('tagfunc', 'foobar', { buf = buf })
2119      eq('foobar', api.nvim_get_option_value('tagfunc', { buf = buf }))
2120
2121      local win = api.nvim_get_current_win()
2122      api.nvim_set_option_value('number', true, { win = win })
2123      eq(true, api.nvim_get_option_value('number', { win = win }))
2124    end)
2125
2126    it('getting current buffer option does not adjust cursor #19381', function()
2127      command('new')
2128      local buf = api.nvim_get_current_buf()
2129      local win = api.nvim_get_current_win()
2130      insert('some text')
2131      feed('0v$')
2132      eq({ 1, 9 }, api.nvim_win_get_cursor(win))
2133      api.nvim_get_option_value('filetype', { buf = buf })
2134      eq({ 1, 9 }, api.nvim_win_get_cursor(win))
2135    end)
2136
2137    it('can get default option values for filetypes', function()
2138      command('filetype plugin on')
2139      for ft, opts in pairs {
2140        lua = { commentstring = '-- %s' },
2141        vim = { commentstring = '"%s' },
2142        man = { tagfunc = "v:lua.require'man'.goto_tag" },
2143        xml = { formatexpr = 'xmlformat#Format()' },
2144      } do
2145        for option, value in pairs(opts) do
2146          eq(value, api.nvim_get_option_value(option, { filetype = ft }))
2147        end
2148      end
2149
2150      command 'au FileType lua ++once setlocal commentstring=NEW\\ %s'
2151      eq('NEW %s', api.nvim_get_option_value('commentstring', { filetype = 'lua' }))
2152
2153      -- Works from within a FileType autocommand fired from setting the &filetype.
2154      exec [[
2155        au FileType * ++once let g:value = nvim_get_option_value('commentstring', #{filetype: 'vim'})
2156        set commentstring= ft=lua
2157      ]]
2158      eq('"%s', eval('g:value'))
2159      -- Check it didn't somehow mess up the &commentstring from setting the &filetype.
2160      eq('-- %s', eval('&commentstring'))
2161
2162      -- Not possible to recurse endlessly, of course.
2163      exec [[
2164        au FileType foobar call nvim_get_option_value('commentstring', #{filetype: 'foobar'})
2165      ]]
2166      matches( -- Watch out - this error is large!
2167        [[E5555: API call: Vim:E218: Autocommand nesting too deep$]],
2168        pcall_err(command, 'set ft=foobar')
2169      )
2170      command('au! FileType foobar')
2171
2172      eq(
2173        [[Vim(call):E5555: API call: Could not execute FileType autocommands]],
2174        pcall_err(command, "noautocmd call nvim_get_option_value('tagfunc', #{filetype: 'man'})")
2175      )
2176
2177      -- No error if executed with no FileType autocommands defined.
2178      -- Returning the copied global value will continue to suffice, I guess.
2179      command([[filetype plugin off | setglobal commentstring=<><\ %s\ ><>]])
2180      eq({}, api.nvim_get_autocmds { event = 'FileType' })
2181      eq('<>< %s ><>', api.nvim_get_option_value('commentstring', { filetype = 'lua' }))
2182    end)
2183
2184    it('errors for bad FileType autocmds', function()
2185      command 'au FileType lua setlocal commentstring=BAD'
2186      eq(
2187        [[FileType Autocommands for "lua": Vim(setlocal):E537: 'commentstring' must be empty or contain %s: commentstring=BAD]],
2188        pcall_err(api.nvim_get_option_value, 'commentstring', { filetype = 'lua' })
2189      )
2190    end)
2191
2192    it("value of 'modified' is always false for scratch buffers", function()
2193      api.nvim_set_current_buf(api.nvim_create_buf(true, true))
2194      insert([[
2195        foo
2196        bar
2197        baz
2198      ]])
2199      eq(false, api.nvim_get_option_value('modified', {}))
2200    end)
2201
2202    it('errors if autocmds wipe the dummy buffer', function()
2203      -- Wipe the dummy buffer. This will throw E813, but the buffer will still be wiped; check that
2204      -- such errors from setting the filetype have priority.
2205      command 'autocmd FileType * ++once bwipeout!'
2206      eq(
2207        'FileType Autocommands for "*": Vim(bwipeout):E813: Cannot close autocmd window',
2208        pcall_err(api.nvim_get_option_value, 'formatexpr', { filetype = 'lua' })
2209      )
2210
2211      -- Silence E813 to check that the error for wiping the dummy buffer is set.
2212      command 'autocmd FileType * ++once silent! bwipeout!'
2213      eq(
2214        'Internal buffer was deleted',
2215        pcall_err(api.nvim_get_option_value, 'formatexpr', { filetype = 'lua' })
2216      )
2217    end)
2218
2219    it('does not crash if autocmds open dummy buffer in other windows', function()
2220      exec [[
2221        autocmd FileType * ++once let g:dummy_buf = bufnr() | split
2222
2223        " Autocommands should be blocked while Nvim attempts to wipe the buffer.
2224        let g:wipe_events = []
2225        autocmd WinClosed * if winbufnr(expand('<amatch>')) == g:dummy_buf
2226                         \| let g:wipe_events += ['WinClosed']
2227                         \| endif
2228        autocmd BufWipeout * if expand('<abuf>') == g:dummy_buf
2229                         \| let g:wipe_events += ['BufWipeout']
2230                         \| endif
2231      ]]
2232      api.nvim_get_option_value('formatexpr', { filetype = 'lua' })
2233      eq(0, eval('bufexists(g:dummy_buf)'))
2234      eq({}, eval('win_findbuf(g:dummy_buf)'))
2235      eq({}, eval('g:wipe_events'))
2236
2237      -- Be an ABSOLUTE nuisance and make it the only window to prevent it from wiping.
2238      -- Do it this way to avoid E813 from :only trying to close the autocmd window.
2239      command('autocmd FileType * ++once let g:dummy_buf = bufnr() | split | wincmd w | quit')
2240      api.nvim_get_option_value('formatexpr', { filetype = 'lua' })
2241      eq(1, eval('bufexists(g:dummy_buf)'))
2242
2243      -- Ensure the buffer does not remain as a dummy by checking that we can switch to it.
2244      local old_win = api.nvim_get_current_win()
2245      command('execute g:dummy_buf "sbuffer"')
2246      eq(eval('g:dummy_buf'), api.nvim_get_current_buf())
2247      neq(old_win, api.nvim_get_current_win())
2248      eq({}, eval('g:wipe_events'))
2249    end)
2250
2251    it('does not crash if dummy buffer wiped after autocommands', function()
2252      -- Autocommands are blocked while Nvim attempts to wipe the buffer, but check something like
2253      -- &bufhidden = "wipe" causing a premature wipe doesn't crash.
2254      command('autocmd FileType * ++once setlocal bufhidden=wipe | split')
2255      api.nvim_get_option_value('formatexpr', { filetype = 'lua' })
2256      assert_alive()
2257    end)
2258
2259    it('sets dummy buffer options without side-effects', function()
2260      exec [[
2261        let g:events = []
2262        autocmd OptionSet * let g:events += [expand("<amatch>")]
2263        autocmd FileType * ++once let g:bufhidden = &l:bufhidden
2264                               \| let g:buftype = &l:buftype
2265                               \| let g:swapfile = &l:swapfile
2266                               \| let g:modeline = &l:modeline
2267                               \| let g:bufloaded = bufloaded(bufnr())
2268      ]]
2269      api.nvim_get_option_value('formatexpr', { filetype = 'lua' })
2270      eq({}, eval('g:events'))
2271      eq('hide', eval('g:bufhidden'))
2272      eq('nofile', eval('g:buftype'))
2273      eq(0, eval('g:swapfile'))
2274      eq(0, eval('g:modeline'))
2275      eq(1, eval('g:bufloaded'))
2276    end)
2277
2278    it('expands env vars', function()
2279      -- I don't know why setting vim.env.INCLUDE doesn't work here.
2280      clear { env = { INCLUDE = '/dev/null' } }
2281      api.nvim_set_option_value('path', '$INCLUDE', {})
2282      eq('/dev/null', api.nvim_get_option_value('path', {}))
2283    end)
2284
2285    it('expands ~', function()
2286      clear { env = { HOME = '/dev/null' } }
2287      api.nvim_set_option_value('rtp', '~', {})
2288      eq('/dev/null', api.nvim_get_option_value('rtp', {}))
2289    end)
2290
2291    it('allows setting, appending, prepending, and removing lists', function()
2292      api.nvim_set_option_value('wildignore', { '*.o', '*.obj' }, {})
2293      eq('*.o,*.obj', api.nvim_get_option_value('wildignore', {}))
2294
2295      api.nvim_set_option_value('wildignore', { '*.a', '*.b', '*.c' }, { operation = 'append' })
2296      eq('*.o,*.obj,*.a,*.b,*.c', api.nvim_get_option_value('wildignore', {}))
2297
2298      api.nvim_set_option_value('wildignore', { '1', '2', '3' }, { operation = 'prepend' })
2299      eq('1,2,3,*.o,*.obj,*.a,*.b,*.c', api.nvim_get_option_value('wildignore', {}))
2300
2301      -- NOTE: you can't remove something like { '1', '*.obj' } because lists
2302      -- only support removing items in order. Behavior matches :set-=
2303      api.nvim_set_option_value('wildignore', { '1', '2', '3' }, { operation = 'remove' })
2304      eq('*.o,*.obj,*.a,*.b,*.c', api.nvim_get_option_value('wildignore', {}))
2305
2306      api.nvim_set_option_value('wildignore', {}, {})
2307      eq('', api.nvim_get_option_value('wildignore', {}))
2308    end)
2309
2310    it('preserves :setlocal trust semantics when merging options', function()
2311      local path = tmpname(false)
2312      finally(function()
2313        os.remove(path)
2314      end)
2315
2316      local expr = "writefile(['foldexpr'], " .. fn.string(path) .. ')'
2317      api.nvim_buf_set_lines(0, 0, -1, false, { 'one', 'two' })
2318
2319      -- Match :setlocal +=, ^=, and -=: retained expression text must stay sandboxed.
2320      for _, case in ipairs({
2321        { 'append', '+0' },
2322        { 'prepend', '0+' },
2323        { 'remove', '+0' },
2324      }) do
2325        local operation, value = unpack(case)
2326
2327        command('setlocal foldmethod=manual')
2328        command('sandbox let &l:foldexpr = ' .. fn.string(expr .. '+0'))
2329        api.nvim_set_option_value('foldexpr', value, { scope = 'local', operation = operation })
2330
2331        command('setlocal foldmethod=expr')
2332        command('normal! zx')
2333        eq(0, fn.filereadable(path))
2334      end
2335
2336      -- As with :setlocal =, a full replacement from trusted code must allow the write.
2337      api.nvim_set_option_value('foldexpr', expr, { scope = 'local' })
2338      command('normal! zx')
2339      eq({ 'foldexpr' }, fn.readfile(path))
2340    end)
2341
2342    it('allows setting, appending, prepending, removing dicts', function()
2343      -- NOTE: order is dependent on lua's hash map implementation. I don't
2344      -- *think* order matters for the map style options
2345      api.nvim_set_option_value('listchars', { eol = '~', space = '-' }, {})
2346      eq('eol:~,space:-', api.nvim_get_option_value('listchars', {}))
2347
2348      api.nvim_set_option_value(
2349        'listchars',
2350        { multispace = '---+', tab = '>-' },
2351        { operation = 'append' }
2352      )
2353      eq('eol:~,space:-,multispace:---+,tab:>-', api.nvim_get_option_value('listchars', {}))
2354
2355      api.nvim_set_option_value('listchars', { lead = '.' }, { operation = 'prepend' })
2356      eq('lead:.,eol:~,space:-,multispace:---+,tab:>-', api.nvim_get_option_value('listchars', {}))
2357
2358      api.nvim_set_option_value(
2359        'listchars',
2360        { lead = '', multispace = '' },
2361        { operation = 'remove' }
2362      )
2363      eq('eol:~,space:-,tab:>-', api.nvim_get_option_value('listchars', {}))
2364
2365      -- A bare key (string or 1-item list) removes the matching "key:value" item by key.
2366      api.nvim_set_option_value('listchars', { 'space' }, { operation = 'remove' })
2367      eq('eol:~,tab:>-', api.nvim_get_option_value('listchars', {}))
2368
2369      api.nvim_set_option_value('listchars', vim.empty_dict(), {})
2370      eq('', api.nvim_get_option_value('listchars', {}))
2371    end)
2372
2373    it('returns the new option value', function()
2374      eq(
2375        { eol = '~', space = '-' },
2376        api.nvim_set_option_value('listchars', { eol = '~', space = '-' }, {})
2377      )
2378      eq('eol:~,space:-', api.nvim_get_option_value('listchars', {}))
2379      eq(
2380        { eol = '~', space = '-', tab = '>-' },
2381        api.nvim_set_option_value('listchars', { tab = '>-' }, { operation = 'append' })
2382      )
2383      eq('eol:~,space:-,tab:>-', api.nvim_get_option_value('listchars', {}))
2384
2385      -- Scalar option types return their plain value.
2386      eq(7, api.nvim_set_option_value('scrolloff', 7, {}))
2387      eq(true, api.nvim_set_option_value('number', true, {}))
2388      eq(false, api.nvim_set_option_value('number', false, {}))
2389      eq('foo', api.nvim_set_option_value('makeprg', 'foo', {}))
2390    end)
2391
2392    it("dry_run doesn't update option value", function()
2393      local listchars = api.nvim_get_option_value('listchars', {})
2394      eq(
2395        { eol = '~', space = '-' },
2396        api.nvim_set_option_value('listchars', { eol = '~', space = '-' }, { dry_run = true })
2397      )
2398      eq(listchars, api.nvim_get_option_value('listchars', {}))
2399
2400      -- dry_run also applies to operations: returns the merged result (5 + 10) without setting it.
2401      api.nvim_set_option_value('scrolloff', 5, {})
2402      eq(15, api.nvim_set_option_value('scrolloff', 10, { operation = 'append', dry_run = true }))
2403      eq(5, api.nvim_get_option_value('scrolloff', {}))
2404    end)
2405
2406    it('dry runs reject invalid values with the same errors as assignments', function()
2407      api.nvim_set_option_value('foldlevel', 2, {})
2408      api.nvim_set_option_value('backupext', '.bak', {})
2409      api.nvim_set_option_value('patchmode', '.orig', {})
2410      for _, case in ipairs({
2411        { 'foldmethod', 'nonsense', 'E474:' },
2412        { 'foldcolumn', 'auto:0', 'E474:' },
2413        { 'foldmarker', 'broken', 'E536:' },
2414        { 'foldmarker', ',}}}', 'E474:' },
2415        { 'foldmarker', '{{{,', 'E474:' },
2416        { 'background', 'nonsense', 'E474:' },
2417        { 'fileformat', 'nonsense', 'E474:' },
2418        { 'fileformats', 'unix,nonsense', 'E474:' },
2419        { 'comments', 'b', 'E524:' },
2420        { 'comments', 'b:', 'E525:' },
2421        { 'commentstring', 'hello', 'E537:' },
2422        { 'eventignore', 'NotAnEvent', 'E474:' },
2423        { 'eventignorewin', 'NotAnEvent', 'E474:' },
2424        { 'eventignorewin', 'VimEnter', 'E474:' },
2425        { 'helplang', 'eng', 'E474:' },
2426        { 'matchpairs', '(:', 'E474:' },
2427        { 'shellpipe', '%x', 'E1577:' },
2428        { 'shellredir', '%s %s', 'E1577:' },
2429        { 'showbreak', '界', 'E595:' },
2430        { 'winborder', 'nonsense', 'E474:' },
2431        { 'pumborder', 'nonsense', 'E474:' },
2432        -- Leading dots are ignored when comparing backup extensions.
2433        { 'backupext', 'orig', 'E589:' },
2434        { 'patchmode', 'bak', 'E589:' },
2435        { 'highlight', '', 'E519:' },
2436        { 'filetype', 'bad/name', 'E474:' },
2437        { 'syntax', 'bad/name', 'E474:' },
2438        { 'keymap', 'bad/name', 'E474:' },
2439        { 'isident', '256', 'E474:' },
2440        { 'iskeyword', '256', 'E474:' },
2441        { 'isfname', '256', 'E474:' },
2442        { 'isprint', '256', 'E519:' },
2443        { 'spelllang', 'en/gb', 'E474:' },
2444        { 'spellfile', 'words.txt', 'E474:' },
2445        { 'complete', 'x', 'E539:' },
2446        { 'complete', '.^x', 'E535:' },
2447        { 'mkspellmem', '1,2,3', 'E474:' },
2448        { 'buftype', 'terminal', 'E474:' },
2449        { 'shada', ':', 'E526:' },
2450        { 'shada', ':1', 'E528:' },
2451        { 'shada', "nfile,'100", 'E528:' }, -- The apostrophe is part of the filename.
2452        { 'wildchar', 3, 'E474:' }, -- CTRL-C.
2453        { 'wildcharm', 13, 'E474:' }, -- Enter.
2454        { 'colorcolumn', 'bad', 'E474:' },
2455        { 'statusline', '%^', 'E539:' },
2456        { 'statusline', '%(', 'E542:' },
2457        { 'statuscolumn', '%(', 'E542:' },
2458        { 'winbar', '%(', 'E542:' },
2459        { 'tabline', '%(', 'E542:' },
2460        { 'rulerformat', '%(', 'E542:' },
2461        { 'listchars', 'eol:xx', 'E1511:' },
2462        { 'fillchars', 'fold:xx', 'E1511:' },
2463        { 'mouse', '?', 'E539:' },
2464        { 'backupcopy', 'yes,no', 'E474:' },
2465        { 'sessionoptions', 'curdir,sesdir', 'E474:' },
2466        { 'compatible', true, 'E519:' },
2467        { 'foldnestmax', 2147483648, 'E474:' },
2468        -- Schemas apply to strings and structured input; validate after merging.
2469        { 'breakindentopt', 'shift:x', "E474: 'shift' requires a number" },
2470        { 'diffopt', { algorithm = 'bogus' }, "E474: 'algorithm' must be one of:" },
2471        { 'messagesopt', 'history:x', "E474: 'history' requires a number" },
2472        { 'mousescroll', '', 'E474:' },
2473        { 'mousescroll', 'ver:x', "E474: 'ver' requires a number" },
2474        { 'mousescroll', { bogus = 1 }, "E474: Unknown item 'bogus'", 'append' },
2475        { 'previewpopup', 'height:0', 'E474:' },
2476        { 'previewpopup', { width = 0 }, 'E474:' },
2477        { 'foldopen', 'nonsense', 'E474:', 'append' },
2478        { 'foldmethod', 'manual', 'E474:', 'remove' },
2479        { 'foldlevel', 3, 'E487:', 'remove' },
2480      }) do
2481        local name, value, error, operation = unpack(case)
2482        local opts = { operation = operation or 'set', dry_run = true }
2483        local before = api.nvim_get_option_value(name, {})
2484        local dry_error = pcall_err(api.nvim_set_option_value, name, value, opts)
2485        matches(error, dry_error)
2486        opts.dry_run = false
2487        eq(dry_error, pcall_err(api.nvim_set_option_value, name, value, opts))
2488        eq(before, api.nvim_get_option_value(name, {}))
2489      end
2490    end)
2491
2492    it('dry runs validate the result of removal, not the removed item', function()
2493      api.nvim_set_option_value('mousescroll', { hor = 3, ver = 2 }, {})
2494      eq(
2495        { hor = '3', ver = '2' },
2496        api.nvim_set_option_value(
2497          'mousescroll',
2498          { bogus = 1 },
2499          { operation = 'remove', dry_run = true }
2500        )
2501      )
2502    end)
2503
2504    it('dry runs and assignments accept valid edge cases', function()
2505      for _, case in ipairs({
2506        { 'backspace', '2' }, -- Legacy numeric spelling.
2507        { 'eventignore', 'VimEnter' }, -- Allowed globally, but not in eventignorewin.
2508        { 'iskeyword', '' }, -- An empty character list is allowed.
2509        { 'winborder', '+,-,+,|,+,-,+,|' }, -- Custom border characters.
2510        { 'complete', '.^2,w' }, -- A source can have a completion limit.
2511        { 'mkspellmem', '1000,50,10' }, -- Memory and word-count limits.
2512        { 'shada', "'0" }, -- Zero disables file marks.
2513        { 'lispoptions', '' }, -- Empty is allowed.
2514        { 'signcolumn', 'auto:1-3' }, -- Range syntax is allowed.
2515        { 'mousescroll', 'ver:0' }, -- Zero disables vertical scrolling.
2516        { 'previewpopup', 'height:1,width:1' }, -- Minimum dimensions.
2517      }) do
2518        local name, value = unpack(case)
2519        local dry_value = api.nvim_set_option_value(name, value, { dry_run = true })
2520        eq(dry_value, api.nvim_set_option_value(name, value, {}))
2521      end
2522    end)
2523
2524    it('dry runs do not change which characters belong to words', function()
2525      api.nvim_set_option_value('iskeyword', '@', { buf = 0 })
2526      eq('one', fn.matchstr('one-two', [[\k\+]]))
2527      api.nvim_set_option_value('iskeyword', '@,-', { buf = 0, dry_run = true })
2528      eq('one', fn.matchstr('one-two', [[\k\+]]))
2529      api.nvim_set_option_value('iskeyword', '@,-', { buf = 0 })
2530      eq('one-two', fn.matchstr('one-two', [[\k\+]]))
2531    end)
2532
2533    it('only successful assignments change the spell suggestion limit', function()
2534      exec_lua([[
2535        vim.ui.select = function(items) _G.suggestion_count = #items end
2536      ]])
2537      api.nvim_buf_set_lines(0, 0, -1, true, { 'helo' })
2538      api.nvim_set_option_value('spellsuggest', 'fast,2', {})
2539      command('normal! z=')
2540      eq(2, exec_lua('return _G.suggestion_count'))
2541
2542      matches('E474:', pcall_err(api.nvim_set_option_value, 'spellsuggest', 'best,fast', {}))
2543      command('normal! z=')
2544      eq(2, exec_lua('return _G.suggestion_count'))
2545
2546      api.nvim_set_option_value('spellsuggest', 'fast,1', {})
2547      command('normal! z=')
2548      eq(1, exec_lua('return _G.suggestion_count'))
2549    end)
2550
2551    it('validates spellfile paths with Windows separators', function()
2552      skip(not is_os('win'))
2553      -- Backslashes become forward slashes before checking filename characters.
2554      api.nvim_set_option_value('isfname', '@,/,.', {})
2555      api.nvim_set_option_value('spellfile', [[dir\words.add]], { dry_run = true })
2556      api.nvim_set_option_value('spellfile', [[dir\words.add]], {})
2557      eq('dir/words.add', api.nvim_get_option_value('spellfile', {}))
2558    end)
2559
2560    it('dry runs leave listchars rendering unchanged', function()
2561      local screen = Screen.new(20, 5)
2562      api.nvim_buf_set_lines(0, 0, -1, true, { 'one' })
2563      command('setlocal list listchars=eol:X | redraw')
2564      eq('X', fn.screenstring(1, 4))
2565      eq({ eol = 'Y' }, api.nvim_set_option_value('listchars', 'eol:Y', { dry_run = true }))
2566      command('redraw')
2567      eq('X', fn.screenstring(1, 4))
2568      api.nvim_set_option_value('listchars', 'eol:Y', {})
2569      command('redraw')
2570      eq('Y', fn.screenstring(1, 4))
2571      screen:detach()
2572    end)
2573
2574    it('dry runs validate against the target buffer and tab', function()
2575      local buf = api.nvim_get_current_buf()
2576      command('setlocal nomodifiable previewwindow | new')
2577      local win = api.nvim_get_current_win()
2578      command('tabnew')
2579      local current = api.nvim_get_current_win()
2580      for _, case in ipairs({
2581        { 'fileformat', 'dos', { buf = buf }, 'E21:' },
2582        { 'previewwindow', true, { win = win }, 'E590:' },
2583      }) do
2584        local name, value, opts, error = unpack(case)
2585        opts.dry_run = true
2586        local dry_error = pcall_err(api.nvim_set_option_value, name, value, opts)
2587        matches(error, dry_error)
2588        eq(current, api.nvim_get_current_win())
2589        opts.dry_run = false
2590        eq(dry_error, pcall_err(api.nvim_set_option_value, name, value, opts))
2591      end
2592      eq(false, api.nvim_get_option_value('previewwindow', { win = win }))
2593      -- A different tab can have its own preview window; the existing one can be reassigned.
2594      eq(true, api.nvim_set_option_value('previewwindow', true, { win = current, dry_run = true }))
2595      api.nvim_set_option_value('previewwindow', true, { win = current })
2596      eq(true, api.nvim_set_option_value('previewwindow', true, { win = current, dry_run = true }))
2597    end)
2598
2599    it('buftype checks terminal buffers only for local assignments', function()
2600      local terminal = api.nvim_create_buf(false, true)
2601      api.nvim_open_term(terminal, {})
2602      for _, dry_run in ipairs({ true, false }) do
2603        local opts = { buf = terminal, dry_run = dry_run }
2604        matches('E474:', pcall_err(api.nvim_set_option_value, 'buftype', 'nofile', opts))
2605        eq('terminal', api.nvim_set_option_value('buftype', 'terminal', opts))
2606        eq(
2607          'terminal',
2608          api.nvim_set_option_value('buftype', 'terminal', {
2609            scope = 'global',
2610            dry_run = dry_run,
2611          })
2612        )
2613      end
2614    end)
2615
2616    it('dry runs return clamped numeric values without storing them', function()
2617      api.nvim_set_option_value('pumblend', 10, {})
2618      eq(100, api.nvim_set_option_value('pumblend', 150, { dry_run = true }))
2619      eq(10, api.nvim_get_option_value('pumblend', {}))
2620      api.nvim_set_option_value('pumblend', 150, {})
2621      eq(100, api.nvim_get_option_value('pumblend', {}))
2622    end)
2623
2624    it('dry runs leave other windows and their folds unchanged', function()
2625      api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two', 'three' })
2626      command('1,3fold')
2627      exec_lua([[
2628        _G.foldexpr_calls = 0
2629        vim.wo.foldexpr = function()
2630          _G.foldexpr_calls = _G.foldexpr_calls + 1
2631          return 0
2632        end
2633      ]])
2634      local target = api.nvim_get_current_win()
2635      command('new')
2636      local current = api.nvim_get_current_win()
2637      exec([[
2638        let g:events = 0
2639        autocmd OptionSet,WinEnter,WinLeave,BufEnter,BufLeave * let g:events += 1
2640      ]])
2641
2642      eq('expr', api.nvim_set_option_value('foldmethod', 'expr', { win = target, dry_run = true }))
2643      eq(current, api.nvim_get_current_win())
2644      eq(0, eval('g:events'))
2645      api.nvim_set_current_win(target)
2646      eq('manual', api.nvim_get_option_value('foldmethod', {}))
2647      eq(1, fn.foldclosed(1))
2648      eq(0, exec_lua('return _G.foldexpr_calls'))
2649    end)
2650
2651    it('foldmarker dry runs preserve folds until assignment', function()
2652      api.nvim_buf_set_lines(0, 0, -1, true, { '{{{', 'one', '}}}', '[[[', 'two', ']]]' })
2653      api.nvim_set_option_value('foldmethod', 'marker', { win = 0 })
2654      eq(1, fn.foldlevel(2))
2655      eq(0, fn.foldlevel(5))
2656      eq(
2657        { '[[[', ']]]' },
2658        api.nvim_set_option_value('foldmarker', '[[[,]]]', { win = 0, dry_run = true })
2659      )
2660      eq(1, fn.foldlevel(2))
2661      eq(0, fn.foldlevel(5))
2662      api.nvim_set_option_value('foldmarker', '[[[,]]]', { win = 0 })
2663      eq(0, fn.foldlevel(2))
2664      eq(1, fn.foldlevel(5))
2665    end)
2666
2667    it('dry runs do not change when motions open folds', function()
2668      api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two', 'three' })
2669      command('1,3fold')
2670      api.nvim_set_option_value('foldopen', '', {})
2671      eq({ 'hor' }, api.nvim_set_option_value('foldopen', 'hor', { dry_run = true }))
2672      feed('l')
2673      eq(1, fn.foldclosed(1))
2674      api.nvim_set_option_value('foldopen', 'hor', {})
2675      feed('l')
2676      eq(-1, fn.foldclosed(1))
2677    end)
2678
2679    it('dry runs use target window bounds and defaults without switching windows', function()
2680      local target = api.nvim_get_current_win()
2681      api.nvim_set_option_value('foldmethod', 'marker', { win = target, scope = 'global' })
2682      command('new')
2683      local current = api.nvim_get_current_win()
2684      api.nvim_set_option_value('foldmethod', 'indent', { win = current, scope = 'global' })
2685      api.nvim_win_set_height(target, 4)
2686      local before = api.nvim_get_option_value('scroll', { win = target })
2687      eq(8, api.nvim_set_option_value('scroll', 8, { win = current, dry_run = true }))
2688      matches(
2689        'E49:',
2690        pcall_err(api.nvim_set_option_value, 'scroll', 8, { win = target, dry_run = true })
2691      )
2692      eq(2, api.nvim_set_option_value('scroll', 0, { win = target, dry_run = true }))
2693      eq(before, api.nvim_get_option_value('scroll', { win = target }))
2694      eq('marker', api.nvim_set_option_value('foldmethod', NIL, { win = target, dry_run = true }))
2695      eq('manual', api.nvim_get_option_value('foldmethod', { win = target }))
2696      eq(current, api.nvim_get_current_win())
2697    end)
2698
2699    it('dry runs do not evaluate callback strings', function()
2700      local value = "function('tr', [execute('let g:called = 1')])"
2701      eq(value, api.nvim_set_option_value('operatorfunc', value, { dry_run = true }))
2702      local complete = api.nvim_get_option_value('complete', {})
2703      value = 'F' .. value:gsub(',', '\\,')
2704      api.nvim_set_option_value('complete', value, { dry_run = true })
2705      eq(complete, api.nvim_get_option_value('complete', {}))
2706      eq(0, fn.exists('g:called'))
2707      eq('', api.nvim_get_option_value('operatorfunc', {}))
2708      api.nvim_set_option_value('complete', value, {})
2709      eq(1, eval('g:called'))
2710    end)
2711
2712    it('2zF includes the existing fold and the next line', function()
2713      api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two', 'three', 'four', 'five' })
2714      command('2,4fold')
2715      command('setlocal nofoldenable')
2716      api.nvim_win_set_cursor(0, { 2, 0 })
2717
2718      -- 2zF turns folding back on. The fold on lines 2-4 counts as the first
2719      -- line, and line 5 counts as the second.
2720      command('normal! 2zF')
2721      eq(5, fn.foldclosedend(2))
2722    end)
2723
2724    it('zM, zx and zX reapply an unchanged foldlevel', function()
2725      api.nvim_buf_set_lines(0, 0, -1, true, { '{{{', 'one', '}}}', 'last' })
2726      api.nvim_set_option_value('foldmethod', 'marker', { win = 0 })
2727      command('normal! zo')
2728      eq(-1, fn.foldclosed(2))
2729      command('normal! zM')
2730      eq(1, fn.foldclosed(2))
2731      command('normal! zn')
2732      eq(false, api.nvim_get_option_value('foldenable', { win = 0 }))
2733      command('normal! zx')
2734      eq(true, api.nvim_get_option_value('foldenable', { win = 0 }))
2735      eq(-1, fn.foldclosed(2))
2736      command('normal! zX')
2737      eq(1, fn.foldclosed(2))
2738    end)
2739
2740    it('folding commands report option changes through OptionSet', function()
2741      api.nvim_buf_set_lines(0, 0, -1, true, { 'one', 'two', 'three' })
2742      command('1,3fold')
2743      exec([[
2744        let g:options = []
2745        autocmd OptionSet foldlevel,foldenable
2746          \ call add(g:options, [expand('<amatch>'), v:option_old, v:option_new])
2747      ]])
2748      command('normal! zr')
2749      command('normal! zm')
2750      command('normal! zi')
2751      eq(
2752        { { 'foldlevel', 0, 1 }, { 'foldlevel', 1, 0 }, { 'foldenable', true, false } },
2753        eval('g:options')
2754      )
2755    end)
2756
2757    it('foldenable setters synchronize diff windows only on assignment', function()
2758      command('setlocal foldmethod=diff scrollbind | split')
2759      local target = api.nvim_get_current_win()
2760      local peer = api.nvim_list_wins()[2]
2761      command('new')
2762      local unrelated = api.nvim_get_current_win()
2763      command('setlocal foldmethod=manual noscrollbind')
2764
2765      api.nvim_set_option_value('foldenable', false, { win = target, dry_run = true })
2766      eq(true, api.nvim_get_option_value('foldenable', { win = target }))
2767      eq(true, api.nvim_get_option_value('foldenable', { win = peer }))
2768
2769      api.nvim_set_option_value('foldenable', false, { win = target })
2770      eq(false, api.nvim_get_option_value('foldenable', { win = peer }))
2771      eq(true, api.nvim_get_option_value('foldenable', { win = unrelated }))
2772
2773      api.nvim_set_current_win(target)
2774      command('normal! zN')
2775      eq(true, api.nvim_get_option_value('foldenable', { win = peer }))
2776    end)
2777
2778    it('cancels a pending fold if OptionSet closes its window', function()
2779      local other = api.nvim_get_current_buf()
2780      local lines = { 'one', 'two', 'three' }
2781      api.nvim_buf_set_lines(other, 0, -1, true, lines)
2782      command('setlocal foldmethod=marker | new | setlocal nofoldenable')
2783      command('autocmd OptionSet foldenable close')
2784      command('normal! zfj')
2785      eq(1, #api.nvim_list_wins())
2786      eq(lines, api.nvim_buf_get_lines(other, 0, -1, true))
2787    end)
2788
2789    it('folding commands stop if OptionSet changes their buffer', function()
2790      local other = api.nvim_get_current_buf()
2791      api.nvim_set_option_value('foldlevel', 4, { win = 0 })
2792      api.nvim_set_current_buf(api.nvim_create_buf(true, false))
2793      command('setlocal nofoldenable')
2794      command('autocmd OptionSet foldenable buffer ' .. other)
2795      command('normal! zM')
2796      eq(other, api.nvim_get_current_buf())
2797      eq(4, api.nvim_get_option_value('foldlevel', { win = 0 }))
2798    end)
2799
2800    it('zx does not open folds in a buffer entered by OptionSet', function()
2801      local other = api.nvim_get_current_buf()
2802      api.nvim_buf_set_lines(other, 0, -1, true, { 'one', 'two', 'three' })
2803      command('1,3fold')
2804      api.nvim_set_current_buf(api.nvim_create_buf(true, false))
2805      command('autocmd OptionSet foldlevel buffer ' .. other)
2806      command('normal! zx')
2807      eq(other, api.nvim_get_current_buf())
2808      eq(1, fn.foldclosed(1))
2809    end)
2810
2811    it('merges options against non-current window', function()
2812      api.nvim_set_option_value('listchars', {}, { operation = 'set' })
2813
2814      local oldwin = fn.win_getid()
2815      command('split')
2816      local curwin = fn.win_getid()
2817      neq(oldwin, curwin)
2818
2819      eq(
2820        { eol = '~' },
2821        api.nvim_set_option_value(
2822          'listchars',
2823          { eol = '~' },
2824          { operation = 'append', win = oldwin }
2825        )
2826      )
2827      eq(
2828        { tab = '>-' },
2829        api.nvim_set_option_value(
2830          'listchars',
2831          { tab = '>-' },
2832          { operation = 'append', win = curwin }
2833        )
2834      )
2835      eq(
2836        { eol = '~', space = '-' },
2837        api.nvim_set_option_value(
2838          'listchars',
2839          { space = '-' },
2840          { operation = 'append', win = oldwin }
2841        )
2842      )
2843      eq(
2844        { lead = '.', tab = '>-' },
2845        api.nvim_set_option_value(
2846          'listchars',
2847          { lead = '.' },
2848          { operation = 'append', win = curwin }
2849        )
2850      )
2851    end)
2852
2853    it('merges options against non-current buffer', function()
2854      eq({}, api.nvim_set_option_value('completeopt', {}, { operation = 'set' }))
2855
2856      local oldbuf = fn.bufnr()
2857      command('new')
2858      local curbuf = fn.bufnr()
2859      neq(oldbuf, curbuf)
2860
2861      eq(
2862        { 'fuzzy' },
2863        api.nvim_set_option_value(
2864          'completeopt',
2865          { 'fuzzy' },
2866          { operation = 'append', buf = oldbuf }
2867        )
2868      )
2869      eq(
2870        { 'longest' },
2871        api.nvim_set_option_value(
2872          'completeopt',
2873          { 'longest' },
2874          { operation = 'append', buf = curbuf }
2875        )
2876      )
2877      eq(
2878        { 'fuzzy', 'menu' },
2879        api.nvim_set_option_value('completeopt', { 'menu' }, { operation = 'append', buf = oldbuf })
2880      )
2881      eq(
2882        { 'longest', 'noinsert' },
2883        api.nvim_set_option_value(
2884          'completeopt',
2885          { 'noinsert' },
2886          { operation = 'append', buf = curbuf }
2887        )
2888      )
2889    end)
2890
2891    it('applies operations to number options', function()
2892      -- For number options the operations are arithmetic. `:set {number}+= ^= -=`
2893      api.nvim_set_option_value('scrolloff', 5, {})
2894      eq(8, api.nvim_set_option_value('scrolloff', 3, { operation = 'append' }))
2895      eq(8, api.nvim_get_option_value('scrolloff', {}))
2896
2897      api.nvim_set_option_value('scrolloff', 5, {})
2898      eq(15, api.nvim_set_option_value('scrolloff', 3, { operation = 'prepend' }))
2899      eq(15, api.nvim_get_option_value('scrolloff', {}))
2900
2901      api.nvim_set_option_value('scrolloff', 5, {})
2902      eq(3, api.nvim_set_option_value('scrolloff', 2, { operation = 'remove' }))
2903      eq(3, api.nvim_get_option_value('scrolloff', {}))
2904    end)
2905
2906    it('applies operations to flag-list and plain string options', function()
2907      -- Flag-list option (no separator); the return value is the Lua map form.
2908      api.nvim_set_option_value('formatoptions', 'tc', {})
2909      eq(
2910        { t = true, c = true, q = true },
2911        api.nvim_set_option_value('formatoptions', 'q', { operation = 'append' })
2912      )
2913      eq('tcq', api.nvim_get_option_value('formatoptions', {}))
2914      eq(
2915        { c = true, q = true },
2916        api.nvim_set_option_value('formatoptions', 't', { operation = 'remove' })
2917      )
2918      eq('cq', api.nvim_get_option_value('formatoptions', {}))
2919
2920      -- Plain (non-list) string option: append concatenates with no separator.
2921      api.nvim_set_option_value('makeprg', 'make', {})
2922      eq('make!', api.nvim_set_option_value('makeprg', '!', { operation = 'append' }))
2923      eq('make!', api.nvim_get_option_value('makeprg', {}))
2924    end)
2925  end)
2926
2927  describe('nvim_{get,set}_current_buf, nvim_list_bufs', function()
2928    it('works', function()
2929      eq(1, #api.nvim_list_bufs())
2930      eq(api.nvim_list_bufs()[1], api.nvim_get_current_buf())
2931      command('new')
2932      eq(2, #api.nvim_list_bufs())
2933      eq(api.nvim_list_bufs()[2], api.nvim_get_current_buf())
2934      api.nvim_set_current_buf(api.nvim_list_bufs()[1])
2935      eq(api.nvim_list_bufs()[1], api.nvim_get_current_buf())
2936    end)
2937  end)
2938
2939  describe('nvim_{get,set}_current_win, nvim_list_wins', function()
2940    it('works', function()
2941      eq(1, #api.nvim_list_wins())
2942      eq(api.nvim_list_wins()[1], api.nvim_get_current_win())
2943      command('vsplit')
2944      command('split')
2945      eq(3, #api.nvim_list_wins())
2946      eq(api.nvim_list_wins()[1], api.nvim_get_current_win())
2947      api.nvim_set_current_win(api.nvim_list_wins()[2])
2948      eq(api.nvim_list_wins()[2], api.nvim_get_current_win())
2949    end)
2950
2951    it('resets Visual mode when switching to different buffer #37072', function()
2952      command('new | wincmd w')
2953      api.nvim_buf_set_lines(0, 0, -1, true, { 'a', 'b' })
2954      api.nvim_win_set_cursor(0, { 2, 0 })
2955      feed('<C-q>')
2956      eq({ mode = '\022', blocking = false }, api.nvim_get_mode())
2957      api.nvim_set_current_win(fn.win_getid(fn.winnr('#')))
2958      eq(true, pcall(command, 'redraw'))
2959    end)
2960
2961    it('failure modes', function()
2962      n.command('split')
2963
2964      eq('Invalid window id: 9999', pcall_err(api.nvim_set_current_win, 9999))
2965
2966      -- XXX: force nvim_set_current_win to fail somehow.
2967      n.command("au WinLeave * throw 'foo'")
2968      eq('WinLeave Autocommands for "*": foo', pcall_err(api.nvim_set_current_win, 1000))
2969    end)
2970  end)
2971
2972  describe('nvim_{get,set}_current_tabpage, nvim_list_tabpages', function()
2973    it('works', function()
2974      eq(1, #api.nvim_list_tabpages())
2975      eq(api.nvim_list_tabpages()[1], api.nvim_get_current_tabpage())
2976      command('tabnew')
2977      eq(2, #api.nvim_list_tabpages())
2978      eq(2, #api.nvim_list_wins())
2979      eq(api.nvim_list_wins()[2], api.nvim_get_current_win())
2980      eq(api.nvim_list_tabpages()[2], api.nvim_get_current_tabpage())
2981      api.nvim_set_current_win(api.nvim_list_wins()[1])
2982      -- Switching window also switches tabpages if necessary
2983      eq(api.nvim_list_tabpages()[1], api.nvim_get_current_tabpage())
2984      eq(api.nvim_list_wins()[1], api.nvim_get_current_win())
2985      api.nvim_set_current_tabpage(api.nvim_list_tabpages()[2])
2986      eq(api.nvim_list_tabpages()[2], api.nvim_get_current_tabpage())
2987      eq(api.nvim_list_wins()[2], api.nvim_get_current_win())
2988    end)
2989
2990    it('failure modes', function()
2991      n.command('tabnew')
2992
2993      eq('Invalid tabpage id: 999', pcall_err(api.nvim_set_current_tabpage, 999))
2994
2995      -- XXX: force nvim_set_current_tabpage to fail somehow.
2996      n.command("au TabLeave * throw 'foo'")
2997      eq('TabLeave Autocommands for "*": foo', pcall_err(api.nvim_set_current_tabpage, 1))
2998    end)
2999  end)
3000
3001  describe('nvim_get_mode', function()
3002    it('during normal-mode `g` returns blocking=true', function()
3003      api.nvim_input('o') -- add a line
3004      eq({ mode = 'i', blocking = false }, api.nvim_get_mode())
3005      api.nvim_input([[<C-\><C-N>]])
3006      eq(2, api.nvim_eval("line('.')"))
3007      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3008
3009      api.nvim_input('g')
3010      eq({ mode = 'n', blocking = true }, api.nvim_get_mode())
3011
3012      api.nvim_input('k') -- complete the operator
3013      eq(1, api.nvim_eval("line('.')")) -- verify the completed operator
3014      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3015    end)
3016
3017    it('returns the correct result multiple consecutive times', function()
3018      for _ = 1, 5 do
3019        eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3020      end
3021      api.nvim_input('g')
3022      for _ = 1, 4 do
3023        eq({ mode = 'n', blocking = true }, api.nvim_get_mode())
3024      end
3025      api.nvim_input('g')
3026      for _ = 1, 7 do
3027        eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3028      end
3029    end)
3030
3031    it('during normal-mode CTRL-W, returns blocking=true', function()
3032      api.nvim_input('<C-W>')
3033      eq({ mode = 'n', blocking = true }, api.nvim_get_mode())
3034
3035      api.nvim_input('s') -- complete the operator
3036      eq(2, api.nvim_eval("winnr('$')")) -- verify the completed operator
3037      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3038    end)
3039
3040    it('during hit-enter prompt without UI returns blocking=false', function()
3041      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3042      command("echom 'msg1'")
3043      command("echom 'msg2'")
3044      command("echom 'msg3'")
3045      command("echom 'msg4'")
3046      command("echom 'msg5'")
3047      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3048      api.nvim_input(':messages<CR>')
3049      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3050    end)
3051
3052    it('during hit-enter prompt returns blocking=true', function()
3053      api.nvim_ui_attach(80, 20, {})
3054      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3055      command("echom 'msg1'")
3056      command("echom 'msg2'")
3057      command("echom 'msg3'")
3058      command("echom 'msg4'")
3059      command("echom 'msg5'")
3060      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3061      api.nvim_input(':messages<CR>')
3062      eq({ mode = 'r', blocking = true }, api.nvim_get_mode())
3063    end)
3064
3065    it('during getchar() returns blocking=false', function()
3066      api.nvim_input(':let g:test_input = nr2char(getchar())<CR>')
3067      -- Events are enabled during getchar(), RPC calls are *not* blocked. #5384
3068      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3069      eq(0, api.nvim_eval("exists('g:test_input')"))
3070      api.nvim_input('J')
3071      eq('J', api.nvim_eval('g:test_input'))
3072      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3073    end)
3074
3075    -- TODO: bug #6247#issuecomment-286403810
3076    it('batched with input', function()
3077      api.nvim_ui_attach(80, 20, {})
3078      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3079      command("echom 'msg1'")
3080      command("echom 'msg2'")
3081      command("echom 'msg3'")
3082      command("echom 'msg4'")
3083      command("echom 'msg5'")
3084
3085      local req = {
3086        { 'nvim_get_mode', {} },
3087        { 'nvim_input', { ':messages<CR>' } },
3088        { 'nvim_get_mode', {} },
3089        { 'nvim_eval', { '1' } },
3090      }
3091      eq({
3092        {
3093          { mode = 'n', blocking = false },
3094          13,
3095          { mode = 'n', blocking = false }, -- TODO: should be blocked=true ?
3096          1,
3097        },
3098        NIL,
3099      }, api.nvim_call_atomic(req))
3100      eq({ mode = 'r', blocking = true }, api.nvim_get_mode())
3101    end)
3102    it('during insert-mode map-pending, returns blocking=true #6166', function()
3103      command('inoremap xx foo')
3104      api.nvim_input('ix')
3105      eq({ mode = 'i', blocking = true }, api.nvim_get_mode())
3106    end)
3107    it('during normal-mode gU, returns blocking=false #6166', function()
3108      api.nvim_input('gu')
3109      eq({ mode = 'no', blocking = false }, api.nvim_get_mode())
3110    end)
3111
3112    it("at '-- More --' prompt returns blocking=true #11899", function()
3113      command('set more')
3114      feed(':digraphs<cr>')
3115      eq({ mode = 'rm', blocking = true }, api.nvim_get_mode())
3116    end)
3117
3118    it('after <Nop> mapping returns blocking=false #17257', function()
3119      command('nnoremap <F2> <Nop>')
3120      feed('<F2>')
3121      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3122    end)
3123
3124    it('after empty string <expr> mapping returns blocking=false #17257', function()
3125      command('nnoremap <expr> <F2> ""')
3126      feed('<F2>')
3127      eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
3128    end)
3129
3130    it('returns "c" during number prompt', function()
3131      feed('ifoo<Esc>z=')
3132      eq({ mode = 'c', blocking = false }, api.nvim_get_mode())
3133    end)
3134  end)
3135
3136  describe('RPC (K_EVENT)', function()
3137    it('does not complete ("interrupt") normal-mode operator-pending #6166', function()
3138      n.insert([[
3139        FIRST LINE
3140        SECOND LINE]])
3141      api.nvim_input('gg')
3142      api.nvim_input('gu')
3143      -- Make any RPC request (can be non-async: op-pending does not block).
3144      api.nvim_get_current_buf()
3145      -- Buffer should not change.
3146      expect([[
3147        FIRST LINE
3148        SECOND LINE]])
3149      -- Now send input to complete the operator.
3150      api.nvim_input('j')
3151      expect([[
3152        first line
3153        second line]])
3154    end)
3155
3156    it('does not complete ("interrupt") `d` #3732', function()
3157      local screen = Screen.new(20, 4)
3158      command('set listchars=eol:$')
3159      command('set list')
3160      feed('ia<cr>b<cr>c<cr><Esc>kkk')
3161      feed('d')
3162      -- Make any RPC request (can be non-async: op-pending does not block).
3163      api.nvim_get_current_buf()
3164      screen:expect([[
3165       ^a{1:$}                  |
3166       b{1:$}                  |
3167       c{1:$}                  |
3168                           |
3169      ]])
3170    end)
3171
3172    it('does not complete ("interrupt") normal-mode map-pending #6166', function()
3173      command("nnoremap dd :let g:foo='it worked...'<CR>")
3174      n.insert([[
3175        FIRST LINE
3176        SECOND LINE]])
3177      api.nvim_input('gg')
3178      api.nvim_input('d')
3179      -- Make any RPC request (must be async, because map-pending blocks).
3180      api.nvim_get_api_info()
3181      -- Send input to complete the mapping.
3182      api.nvim_input('d')
3183      expect([[
3184        FIRST LINE
3185        SECOND LINE]])
3186      eq('it worked...', n.eval('g:foo'))
3187    end)
3188
3189    it('does not complete ("interrupt") insert-mode map-pending #6166', function()
3190      command('inoremap xx foo')
3191      command('set timeoutlen=9999')
3192      n.insert([[
3193        FIRST LINE
3194        SECOND LINE]])
3195      api.nvim_input('ix')
3196      -- Make any RPC request (must be async, because map-pending blocks).
3197      api.nvim_get_api_info()
3198      -- Send input to complete the mapping.
3199      api.nvim_input('x')
3200      expect([[
3201        FIRST LINE
3202        SECOND LINfooE]])
3203    end)
3204
3205    it('does not interrupt Insert mode i_CTRL-O #10035', function()
3206      feed('iHello World<c-o>')
3207      eq({ mode = 'niI', blocking = false }, api.nvim_get_mode()) -- fast event
3208      eq(2, eval('1+1')) -- causes K_EVENT key
3209      eq({ mode = 'niI', blocking = false }, api.nvim_get_mode()) -- still in ctrl-o mode
3210      feed('dd')
3211      eq({ mode = 'i', blocking = false }, api.nvim_get_mode()) -- left ctrl-o mode
3212      expect('') -- executed the command
3213    end)
3214
3215    it('does not interrupt Select mode v_CTRL-O #15688', function()
3216      feed('iHello World<esc>gh<c-o>')
3217      eq({ mode = 'vs', blocking = false }, api.nvim_get_mode()) -- fast event
3218      eq({ mode = 'vs', blocking = false }, api.nvim_get_mode()) -- again #15288
3219      eq(2, eval('1+1')) -- causes K_EVENT key
3220      eq({ mode = 'vs', blocking = false }, api.nvim_get_mode()) -- still in ctrl-o mode
3221      feed('^')
3222      eq({ mode = 's', blocking = false }, api.nvim_get_mode()) -- left ctrl-o mode
3223      feed('h')
3224      eq({ mode = 'i', blocking = false }, api.nvim_get_mode()) -- entered insert mode
3225      expect('h') -- selection is the whole line and is replaced
3226    end)
3227
3228    it('does not interrupt Insert mode i_0_CTRL-D #13997', function()
3229      command('set timeoutlen=9999')
3230      feed('i<Tab><Tab>a0')
3231      eq(2, eval('1+1')) -- causes K_EVENT key
3232      feed('<C-D>')
3233      expect('a') -- recognized i_0_CTRL-D
3234    end)
3235
3236    it("does not interrupt with 'digraph'", function()
3237      command('set digraph')
3238      feed('i,')
3239      eq(2, eval('1+1')) -- causes K_EVENT key
3240      feed('<BS>')
3241      eq(2, eval('1+1')) -- causes K_EVENT key
3242      feed('.')
3243      expect('…') -- digraph ",." worked
3244      feed('<Esc>')
3245      feed(':,')
3246      eq(2, eval('1+1')) -- causes K_EVENT key
3247      feed('<BS>')
3248      eq(2, eval('1+1')) -- causes K_EVENT key
3249      feed('.')
3250      eq('…', fn.getcmdline()) -- digraph ",." worked
3251    end)
3252  end)
3253
3254  describe('nvim_get_context', function()
3255    it('validation', function()
3256      eq("Invalid key: 'blah'", pcall_err(api.nvim_get_context, { blah = {} }))
3257      eq(
3258        "Invalid 'types': expected Array, got Integer",
3259        pcall_err(api.nvim_get_context, { types = 42 })
3260      )
3261      eq(
3262        "Invalid 'type': 'zub'",
3263        pcall_err(api.nvim_get_context, { types = { 'jumps', 'zub', 'zam' } })
3264      )
3265    end)
3266    it('returns map of current editor state', function()
3267      local opts = { types = { 'regs', 'jumps', 'bufs', 'gvars' } }
3268      eq({}, parse_context(api.nvim_get_context({})))
3269
3270      feed('i1<cr>2<cr>3<c-[>ddddddqahjklquuu')
3271      feed('gg')
3272      feed('G')
3273      command('edit! BUF1')
3274      command('edit BUF2')
3275      api.nvim_set_var('one', 1)
3276      api.nvim_set_var('Two', 2)
3277      api.nvim_set_var('THREE', 3)
3278
3279      local expected_ctx = {
3280        ['regs'] = {
3281          { ['rt'] = 1, ['rc'] = { '1' }, ['n'] = 49, ['ru'] = true },
3282          { ['rt'] = 1, ['rc'] = { '2' }, ['n'] = 50 },
3283          { ['rt'] = 1, ['rc'] = { '3' }, ['n'] = 51 },
3284          { ['rc'] = { 'hjkl' }, ['n'] = 97 },
3285        },
3286
3287        ['jumps'] = eval((([[
3288        filter(map(add(
3289        getjumplist()[0], { 'bufnr': bufnr('%'), 'lnum': getcurpos()[1] }),
3290        'filter(
3291        { "f": expand("#".v:val.bufnr.":p:gs?\\?/?"), "l": v:val.lnum },
3292        { k, v -> k != "l" || v != 1 })'), '!empty(v:val.f)')
3293        ]]):gsub('\n', ''))),
3294
3295        ['bufs'] = eval([[
3296        filter(map(getbufinfo(), '{ "f": v:val.name }'), '!empty(v:val.f)')
3297        ]]),
3298
3299        ['gvars'] = { { 'one', 1 }, { 'Two', 2 }, { 'THREE', 3 } },
3300      }
3301
3302      eq(expected_ctx, parse_context(api.nvim_get_context(opts)))
3303      eq(expected_ctx, parse_context(api.nvim_get_context({})))
3304      eq(expected_ctx, parse_context(api.nvim_get_context({ types = {} })))
3305    end)
3306  end)
3307
3308  describe('nvim_load_context', function()
3309    it('sets current editor state to given context dict', function()
3310      local opts = { types = { 'regs', 'jumps', 'bufs', 'gvars' } }
3311      eq({}, parse_context(api.nvim_get_context(opts)))
3312
3313      api.nvim_set_var('one', 1)
3314      api.nvim_set_var('Two', 2)
3315      api.nvim_set_var('THREE', 3)
3316      local ctx = api.nvim_get_context(opts)
3317      api.nvim_set_var('one', 'a')
3318      api.nvim_set_var('Two', 'b')
3319      api.nvim_set_var('THREE', 'c')
3320      eq({ 'a', 'b', 'c' }, eval('[g:one, g:Two, g:THREE]'))
3321      api.nvim_load_context(ctx)
3322      eq({ 1, 2, 3 }, eval('[g:one, g:Two, g:THREE]'))
3323
3324      -- Context restores what it saved, irrespective of 'shada'.
3325      command('set shada=')
3326      command('autocmd OptionSet shada let g:optionset = 1')
3327      api.nvim_set_var('one', 'a')
3328      api.nvim_load_context(ctx)
3329      eq(1, eval('g:one'))
3330      eq('', eval('&shada'))
3331      eq(0, eval("get(g:, 'optionset', 0)"))
3332
3333      -- Does not touch v:oldfiles (only ":rshada!" rebuilds it).
3334      command('let v:oldfiles = ["/a", "/b"]')
3335      api.nvim_load_context(ctx)
3336      eq({ '/a', '/b' }, eval('v:oldfiles'))
3337    end)
3338
3339    it('errors when context dict is invalid', function()
3340      eq(
3341        'E474: Failed to convert list to msgpack string buffer',
3342        pcall_err(api.nvim_load_context, { regs = { {} }, jumps = { {} } })
3343      )
3344      eq(
3345        'E474: Failed to convert list to msgpack string buffer',
3346        pcall_err(api.nvim_load_context, { regs = { { [''] = '' } } })
3347      )
3348    end)
3349  end)
3350
3351  describe('nvim_feedkeys', function()
3352    it('K_SPECIAL escaping', function()
3353      local function on_setup()
3354        -- notice the special char(…) \xe2\80\xa6
3355        api.nvim_feedkeys(':let x1="…"\n', '', true)
3356
3357        -- Both nvim_replace_termcodes and nvim_feedkeys escape \x80
3358        local inp = n.api.nvim_replace_termcodes(':let x2="…"<CR>', true, true, true)
3359        api.nvim_feedkeys(inp, '', true) -- escape_ks=true
3360
3361        -- nvim_feedkeys with K_SPECIAL escaping disabled
3362        inp = n.api.nvim_replace_termcodes(':let x3="…"<CR>', true, true, true)
3363        api.nvim_feedkeys(inp, '', false) -- escape_ks=false
3364
3365        n.stop()
3366      end
3367
3368      -- spin the loop a bit
3369      n.run(nil, nil, on_setup)
3370
3371      eq('…', api.nvim_get_var('x1'))
3372      -- Because of the double escaping this is neq
3373      neq('…', api.nvim_get_var('x2'))
3374      eq('…', api.nvim_get_var('x3'))
3375    end)
3376  end)
3377
3378  describe('nvim_out_write', function()
3379    local screen
3380
3381    before_each(function()
3382      screen = Screen.new(40, 8)
3383    end)
3384
3385    it('prints long messages correctly #20534', function()
3386      exec([[
3387        set more
3388        redir => g:out
3389          silent! call nvim_out_write('a')
3390          silent! call nvim_out_write('a')
3391          silent! call nvim_out_write('a')
3392          silent! call nvim_out_write("\n")
3393          silent! call nvim_out_write('a')
3394          silent! call nvim_out_write('a')
3395          silent! call nvim_out_write(repeat('a', 5000) .. "\n")
3396          silent! call nvim_out_write('a')
3397          silent! call nvim_out_write('a')
3398          silent! call nvim_out_write('a')
3399          silent! call nvim_out_write("\n")
3400        redir END
3401      ]])
3402      eq('\naaa\n' .. ('a'):rep(5002) .. '\naaa', api.nvim_get_var('out'))
3403    end)
3404
3405    it('blank line in message', function()
3406      feed([[:call nvim_out_write("\na\n")<CR>]])
3407      screen:expect {
3408        grid = [[
3409                                                |
3410        {1:~                                       }|*3
3411        {3:                                        }|
3412                                                |
3413        a                                       |
3414        {6:Press ENTER or type command to continue}^ |
3415      ]],
3416      }
3417      feed('<CR>')
3418      feed([[:call nvim_out_write("b\n\nc\n")<CR>]])
3419      screen:expect {
3420        grid = [[
3421                                                |
3422        {1:~                                       }|*2
3423        {3:                                        }|
3424        b                                       |
3425                                                |
3426        c                                       |
3427        {6:Press ENTER or type command to continue}^ |
3428      ]],
3429      }
3430    end)
3431
3432    it('NUL bytes in message', function()
3433      feed([[:lua vim.api.nvim_out_write('aaa\0bbb\0\0ccc\nddd\0\0\0eee\n')<CR>]])
3434      screen:expect {
3435        grid = [[
3436                                                |
3437        {1:~                                       }|*3
3438        {3:                                        }|
3439        aaa{18:^@}bbb{18:^@^@}ccc                         |
3440        ddd{18:^@^@^@}eee                            |
3441        {6:Press ENTER or type command to continue}^ |
3442      ]],
3443      }
3444    end)
3445  end)
3446
3447  describe('nvim_err_write', function()
3448    local screen
3449
3450    before_each(function()
3451      screen = Screen.new(40, 8)
3452    end)
3453
3454    it('can show one line', function()
3455      async_meths.nvim_err_write('has bork\n')
3456      screen:expect([[
3457        ^                                        |
3458        {1:~                                       }|*6
3459        {9:has bork}                                |
3460      ]])
3461    end)
3462
3463    it('shows return prompt when more than &cmdheight lines', function()
3464      async_meths.nvim_err_write('something happened\nvery bad\n')
3465      screen:expect([[
3466                                                |
3467        {1:~                                       }|*3
3468        {3:                                        }|
3469        {9:something happened}                      |
3470        {9:very bad}                                |
3471        {6:Press ENTER or type command to continue}^ |
3472      ]])
3473    end)
3474
3475    it('shows return prompt after all lines are shown', function()
3476      async_meths.nvim_err_write('FAILURE\nERROR\nEXCEPTION\nTRACEBACK\n')
3477      screen:expect([[
3478                                                |
3479        {1:~                                       }|
3480        {3:                                        }|
3481        {9:FAILURE}                                 |
3482        {9:ERROR}                                   |
3483        {9:EXCEPTION}                               |
3484        {9:TRACEBACK}                               |
3485        {6:Press ENTER or type command to continue}^ |
3486      ]])
3487    end)
3488
3489    it('handles multiple calls', function()
3490      -- without linebreak text is joined to one line
3491      async_meths.nvim_err_write('very ')
3492      async_meths.nvim_err_write('fail\n')
3493      screen:expect([[
3494        ^                                        |
3495        {1:~                                       }|*6
3496        {9:very fail}                               |
3497      ]])
3498      n.poke_eventloop()
3499
3500      -- shows up to &cmdheight lines
3501      async_meths.nvim_err_write('more fail\ntoo fail\n')
3502      screen:expect([[
3503                                                |
3504        {1:~                                       }|*3
3505        {3:                                        }|
3506        {9:more fail}                               |
3507        {9:too fail}                                |
3508        {6:Press ENTER or type command to continue}^ |
3509      ]])
3510      feed('<cr>') -- exit the press ENTER screen
3511    end)
3512
3513    it('NUL bytes in message', function()
3514      async_meths.nvim_err_write('aaa\0bbb\0\0ccc\nddd\0\0\0eee\n')
3515      screen:expect {
3516        grid = [[
3517                                                |
3518        {1:~                                       }|*3
3519        {3:                                        }|
3520        {9:aaa^@bbb^@^@ccc}                         |
3521        {9:ddd^@^@^@eee}                            |
3522        {6:Press ENTER or type command to continue}^ |
3523      ]],
3524      }
3525    end)
3526  end)
3527
3528  describe('nvim_err_writeln', function()
3529    local screen
3530
3531    before_each(function()
3532      screen = Screen.new(40, 8)
3533    end)
3534
3535    it('shows only one return prompt after all lines are shown', function()
3536      async_meths.nvim_err_writeln('FAILURE\nERROR\nEXCEPTION\nTRACEBACK')
3537      screen:expect([[
3538                                                |
3539        {1:~                                       }|
3540        {3:                                        }|
3541        {9:FAILURE}                                 |
3542        {9:ERROR}                                   |
3543        {9:EXCEPTION}                               |
3544        {9:TRACEBACK}                               |
3545        {6:Press ENTER or type command to continue}^ |
3546      ]])
3547      feed('<CR>')
3548      screen:expect([[
3549        ^                                        |
3550        {1:~                                       }|*6
3551                                                |
3552      ]])
3553    end)
3554  end)
3555
3556  describe('nvim_list_chans, nvim_get_chan_info', function()
3557    before_each(function()
3558      command('autocmd ChanOpen * let g:opened_event = deepcopy(v:event)')
3559      command('autocmd ChanInfo * let g:info_event = deepcopy(v:event)')
3560    end)
3561    local testinfo = {
3562      stream = 'stdio',
3563      id = 1,
3564      mode = 'rpc',
3565      client = {},
3566    }
3567    local stderr = {
3568      stream = 'stderr',
3569      id = 2,
3570      mode = 'bytes',
3571    }
3572
3573    it('returns {} for invalid channel', function()
3574      eq({}, api.nvim_get_chan_info(-1))
3575      -- more preallocated numbers might be added, try something high
3576      eq({}, api.nvim_get_chan_info(10))
3577    end)
3578
3579    it('stream=stdio channel', function()
3580      eq({ [1] = testinfo, [2] = stderr }, api.nvim_list_chans())
3581      -- 0 should return current channel
3582      eq(testinfo, api.nvim_get_chan_info(0))
3583      eq(testinfo, api.nvim_get_chan_info(1))
3584      eq(stderr, api.nvim_get_chan_info(2))
3585
3586      api.nvim_set_client_info(
3587        'functionaltests',
3588        { major = 0, minor = 3, patch = 17 },
3589        'ui',
3590        { do_stuff = { n_args = { 2, 3 } } },
3591        { license = 'Apache2' }
3592      )
3593      local info = {
3594        stream = 'stdio',
3595        id = 1,
3596        mode = 'rpc',
3597        client = {
3598          name = 'functionaltests',
3599          version = { major = 0, minor = 3, patch = 17 },
3600          type = 'ui',
3601          methods = { do_stuff = { n_args = { 2, 3 } } },
3602          attributes = { license = 'Apache2' },
3603        },
3604      }
3605      eq({ info = info }, api.nvim_get_var('info_event'))
3606      eq({ [1] = info, [2] = stderr }, api.nvim_list_chans())
3607      eq(info, api.nvim_get_chan_info(1))
3608    end)
3609
3610    it('stream=job channel', function()
3611      eq(3, eval("jobstart(['cat'], {'rpc': v:true})"))
3612      local catpath = vim.fs.normalize(eval('exepath("cat")'))
3613      local info = {
3614        stream = 'job',
3615        id = 3,
3616        argv = { catpath },
3617        mode = 'rpc',
3618        client = {},
3619      }
3620      eq({ info = info }, api.nvim_get_var('opened_event'))
3621      eq({ [1] = testinfo, [2] = stderr, [3] = info }, api.nvim_list_chans())
3622      eq(info, api.nvim_get_chan_info(3))
3623      eval(
3624        'rpcrequest(3, "nvim_set_client_info", "amazing-cat", {}, "remote",'
3625          .. '{"nvim_command":{"n_args":1}},' -- and so on
3626          .. '{"description":"The Amazing Cat"})'
3627      )
3628      info = {
3629        stream = 'job',
3630        id = 3,
3631        argv = { catpath },
3632        mode = 'rpc',
3633        client = {
3634          name = 'amazing-cat',
3635          version = { major = 0 },
3636          type = 'remote',
3637          methods = { nvim_command = { n_args = 1 } },
3638          attributes = { description = 'The Amazing Cat' },
3639        },
3640      }
3641      eq({ info = info }, api.nvim_get_var('info_event'))
3642      eq({ [1] = testinfo, [2] = stderr, [3] = info }, api.nvim_list_chans())
3643
3644      eq(
3645        "Vim:Invoking 'nvim_set_current_buf' on channel 3 (amazing-cat):\nWrong type for argument 1 when calling nvim_set_current_buf, expecting Buffer",
3646        pcall_err(eval, 'rpcrequest(3, "nvim_set_current_buf", -1)')
3647      )
3648      eq(info, eval('rpcrequest(3, "nvim_get_chan_info", 0)'))
3649    end)
3650
3651    local function term_channel_info(id, buffer, argv)
3652      return {
3653        stream = 'job',
3654        id = id,
3655        argv = argv,
3656        mode = 'terminal',
3657        buf = buffer,
3658        buffer = buffer, -- deprecated
3659        pty = '?',
3660        exitcode = -1,
3661      }
3662    end
3663
3664    it('stream=job :terminal channel', function()
3665      Screen.new(80, 24)
3666
3667      command(':terminal')
3668      eq(1, api.nvim_get_current_buf())
3669      eq(3, api.nvim_get_option_value('channel', { buf = 1 }))
3670
3671      local info = term_channel_info(3, 1, { vim.fs.normalize(eval('exepath(&shell)')) })
3672      local event = api.nvim_get_var('opened_event')
3673      if not is_os('win') then
3674        info.pty = event.info.pty
3675        neq(nil, string.match(info.pty, '^/dev/'))
3676      end
3677      eq({ info = info }, event)
3678      info.buf = 1
3679      info.buffer = 1 -- deprecated
3680      eq({ [1] = testinfo, [2] = stderr, [3] = info }, api.nvim_list_chans())
3681      eq(info, api.nvim_get_chan_info(3))
3682
3683      -- :terminal with args + running process (Nvim TUI).
3684      -- Don't use a shell here, so that SIGHUP handling doesn't depend on the shell.
3685      command('enew')
3686      local argv = { n.nvim_prog, '-u', 'NONE', '-i', 'NONE' }
3687      fn.jobstart(argv, {
3688        term = true,
3689        env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
3690      })
3691      eq(-1, eval('jobwait([&channel], 0)[0]')) -- Running?
3692      local expected2 = term_channel_info(4, 2, argv)
3693      local actual2 = eval('nvim_get_chan_info(&channel)')
3694      expected2.pty = actual2.pty
3695      eq(expected2, actual2)
3696
3697      -- Make sure Nvim TUI is started (which is after registering SIGHUP handler).
3698      t.retry(nil, nil, function()
3699        matches('Nvim is open source and freely distributable', n.curbuf_contents())
3700      end)
3701
3702      -- :terminal with args + stopped process (Nvim TUI).
3703      eq(1, eval('jobstop(&channel)'))
3704      eval('jobwait([&channel], 1000)') -- Wait.
3705      expected2.pty = (is_os('win') and '?' or '') -- pty stream was closed.
3706      -- On Unix, SIGHUP is handled by Nvim TUI, so exit code is 1.
3707      -- On Windows, even though Nvim TUI handles SIGHUP, it's not possible for the
3708      -- parent process to know that, so exit code reflects SIGHUP.
3709      expected2.exitcode = (is_os('win') and 129 or 1)
3710      eq(expected2, eval('nvim_get_chan_info(&channel)'))
3711
3712      -- :terminal with args + stopped process (shell-test).
3713      command('enew')
3714      -- Use a process that doesn't read stdin, so PTY EOF can't race SIGHUP.
3715      argv = { n.testprg('shell-test'), 'HOLD' }
3716      fn.jobstart(argv, { term = true })
3717      t.retry(nil, nil, function()
3718        matches('holding %$', n.curbuf_contents())
3719      end)
3720      eq(1, eval('jobstop(&channel)'))
3721      eval('jobwait([&channel], 1000)') -- Wait.
3722      local expected3 = term_channel_info(5, 3, argv)
3723      expected3.pty = (is_os('win') and '?' or '') -- pty stream was closed.
3724      -- Exit code should reflect SIGHUP as shell-test doesn't handle it.
3725      expected3.exitcode = 129
3726      eq(expected3, eval('nvim_get_chan_info(&channel)'))
3727    end)
3728  end)
3729
3730  describe('nvim_call_atomic', function()
3731    it('works', function()
3732      api.nvim_buf_set_lines(0, 0, -1, true, { 'first' })
3733      local req = {
3734        { 'nvim_get_current_line', {} },
3735        { 'nvim_set_current_line', { 'second' } },
3736      }
3737      eq({ { 'first', NIL }, NIL }, api.nvim_call_atomic(req))
3738      eq({ 'second' }, api.nvim_buf_get_lines(0, 0, -1, true))
3739    end)
3740
3741    it('allows multiple return values', function()
3742      local req = {
3743        { 'nvim_set_var', { 'avar', true } },
3744        { 'nvim_set_var', { 'bvar', 'string' } },
3745        { 'nvim_get_var', { 'avar' } },
3746        { 'nvim_get_var', { 'bvar' } },
3747      }
3748      eq({ { NIL, NIL, true, 'string' }, NIL }, api.nvim_call_atomic(req))
3749    end)
3750
3751    it('is aborted by errors in call', function()
3752      local error_types = api.nvim_get_api_info()[2].error_types
3753      local req = {
3754        { 'nvim_set_var', { 'one', 1 } },
3755        { 'nvim_buf_set_lines', {} },
3756        { 'nvim_set_var', { 'two', 2 } },
3757      }
3758      eq({
3759        { NIL },
3760        {
3761          1,
3762          error_types.Exception.id,
3763          'Wrong number of arguments: expecting 5 but got 0',
3764        },
3765      }, api.nvim_call_atomic(req))
3766      eq(1, api.nvim_get_var('one'))
3767      eq(false, pcall(api.nvim_get_var, 'two'))
3768
3769      -- still returns all previous successful calls
3770      req = {
3771        { 'nvim_set_var', { 'avar', 5 } },
3772        { 'nvim_set_var', { 'bvar', 'string' } },
3773        { 'nvim_get_var', { 'avar' } },
3774        { 'nvim_buf_get_lines', { 0, 10, 20, true } },
3775        { 'nvim_get_var', { 'bvar' } },
3776      }
3777      eq(
3778        { { NIL, NIL, 5 }, { 3, error_types.Validation.id, 'Index out of bounds' } },
3779        api.nvim_call_atomic(req)
3780      )
3781
3782      req = {
3783        { 'i_am_not_a_method', { 'xx' } },
3784        { 'nvim_set_var', { 'avar', 10 } },
3785      }
3786      eq(
3787        { {}, { 0, error_types.Exception.id, 'Invalid method: i_am_not_a_method' } },
3788        api.nvim_call_atomic(req)
3789      )
3790      eq(5, api.nvim_get_var('avar'))
3791    end)
3792
3793    it('validation', function()
3794      local req = {
3795        { 'nvim_set_var', { 'avar', 1 } },
3796        { 'nvim_set_var' },
3797        { 'nvim_set_var', { 'avar', 2 } },
3798      }
3799      eq("Invalid 'calls' item: expected 2-item Array", pcall_err(api.nvim_call_atomic, req))
3800      -- call before was done, but not after
3801      eq(1, api.nvim_get_var('avar'))
3802
3803      req = {
3804        { 'nvim_set_var', { 'bvar', { 2, 3 } } },
3805        12,
3806      }
3807      eq("Invalid 'calls' item: expected Array, got Integer", pcall_err(api.nvim_call_atomic, req))
3808      eq({ 2, 3 }, api.nvim_get_var('bvar'))
3809
3810      req = {
3811        { 'nvim_set_current_line', 'little line' },
3812        { 'nvim_set_var', { 'avar', 3 } },
3813      }
3814      eq('Invalid call args: expected Array, got String', pcall_err(api.nvim_call_atomic, req))
3815      -- call before was done, but not after
3816      eq(1, api.nvim_get_var('avar'))
3817      eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, true))
3818    end)
3819  end)
3820
3821  describe('nvim_list_runtime_paths', function()
3822    local test_dir = 'Xtest_list_runtime_paths'
3823
3824    setup(function()
3825      mkdir_p(('%s/a'):format(test_dir))
3826      mkdir_p(('%s/b'):format(test_dir))
3827    end)
3828    teardown(function()
3829      rmdir(test_dir)
3830    end)
3831    before_each(function()
3832      api.nvim_set_current_dir(test_dir)
3833    end)
3834
3835    it('returns nothing with empty &runtimepath', function()
3836      api.nvim_set_option_value('runtimepath', '', {})
3837      eq({}, api.nvim_list_runtime_paths())
3838    end)
3839    it('returns single runtimepath', function()
3840      api.nvim_set_option_value('runtimepath', 'a', {})
3841      eq({ 'a' }, api.nvim_list_runtime_paths())
3842    end)
3843    it('returns two runtimepaths', function()
3844      api.nvim_set_option_value('runtimepath', 'a,b', {})
3845      eq({ 'a', 'b' }, api.nvim_list_runtime_paths())
3846    end)
3847    it('returns empty strings when appropriate', function()
3848      api.nvim_set_option_value('runtimepath', 'a,,b', {})
3849      eq({ 'a', '', 'b' }, api.nvim_list_runtime_paths())
3850      api.nvim_set_option_value('runtimepath', ',a,b', {})
3851      eq({ '', 'a', 'b' }, api.nvim_list_runtime_paths())
3852      -- Trailing "," is ignored. Use ",," if you really really want CWD.
3853      api.nvim_set_option_value('runtimepath', 'a,b,', {})
3854      eq({ 'a', 'b' }, api.nvim_list_runtime_paths())
3855      api.nvim_set_option_value('runtimepath', 'a,b,,', {})
3856      eq({ 'a', 'b', '' }, api.nvim_list_runtime_paths())
3857    end)
3858    it('truncates too long paths', function()
3859      local long_path = ('/a'):rep(8192)
3860      api.nvim_set_option_value('runtimepath', long_path, {})
3861      local paths_list = api.nvim_list_runtime_paths()
3862      eq({}, paths_list)
3863    end)
3864  end)
3865
3866  it('can throw exceptions', function()
3867    local status, err = pcall(api.nvim_get_option_value, 'invalid-option', {})
3868    eq(false, status)
3869    matches("Unknown option 'invalid%-option'", err)
3870  end)
3871
3872  it('does not truncate error message <1 MB #5984', function()
3873    local very_long_name = 'A' .. ('x'):rep(10000) .. 'Z'
3874    local status, err = pcall(api.nvim_get_option_value, very_long_name, {})
3875    eq(false, status)
3876    eq(very_long_name, err:match('Ax+Z?'))
3877  end)
3878
3879  it('does not leak memory on incorrect argument types', function()
3880    local status, err = pcall(api.nvim_set_current_dir, { 'not', 'a', 'dir' })
3881    eq(false, status)
3882    matches(': Wrong type for argument 1 when calling nvim_set_current_dir, expecting String', err)
3883  end)
3884
3885  describe('nvim_parse_expression', function()
3886    before_each(function()
3887      api.nvim_set_option_value('isident', '', {})
3888    end)
3889
3890    local function simplify_east_api_node(line, east_api_node)
3891      if east_api_node == NIL then
3892        return nil
3893      end
3894      if east_api_node.children then
3895        for k, v in pairs(east_api_node.children) do
3896          east_api_node.children[k] = simplify_east_api_node(line, v)
3897        end
3898      end
3899      local typ = east_api_node.type
3900      if typ == 'Register' then
3901        typ = typ .. ('(name=%s)'):format(tostring(intchar2lua(east_api_node.name)))
3902        east_api_node.name = nil
3903      elseif typ == 'PlainIdentifier' then
3904        typ = typ
3905          .. ('(scope=%s,ident=%s)'):format(
3906            tostring(intchar2lua(east_api_node.scope)),
3907            east_api_node.ident
3908          )
3909        east_api_node.scope = nil
3910        east_api_node.ident = nil
3911      elseif typ == 'PlainKey' then
3912        typ = typ .. ('(key=%s)'):format(east_api_node.ident)
3913        east_api_node.ident = nil
3914      elseif typ == 'Comparison' then
3915        typ = typ
3916          .. ('(type=%s,inv=%u,ccs=%s)'):format(
3917            east_api_node.cmp_type,
3918            east_api_node.invert and 1 or 0,
3919            east_api_node.ccs_strategy
3920          )
3921        east_api_node.ccs_strategy = nil
3922        east_api_node.cmp_type = nil
3923        east_api_node.invert = nil
3924      elseif typ == 'Integer' then
3925        typ = typ .. ('(val=%u)'):format(east_api_node.ivalue)
3926        east_api_node.ivalue = nil
3927      elseif typ == 'Float' then
3928        typ = typ .. format_string('(val=%e)', east_api_node.fvalue)
3929        east_api_node.fvalue = nil
3930      elseif typ == 'SingleQuotedString' or typ == 'DoubleQuotedString' then
3931        typ = format_string('%s(val=%q)', typ, east_api_node.svalue)
3932        east_api_node.svalue = nil
3933      elseif typ == 'Option' then
3934        typ = ('%s(scope=%s,ident=%s)'):format(
3935          typ,
3936          tostring(intchar2lua(east_api_node.scope)),
3937          east_api_node.ident
3938        )
3939        east_api_node.ident = nil
3940        east_api_node.scope = nil
3941      elseif typ == 'Environment' then
3942        typ = ('%s(ident=%s)'):format(typ, east_api_node.ident)
3943        east_api_node.ident = nil
3944      elseif typ == 'Assignment' then
3945        local aug = east_api_node.augmentation
3946        if aug == '' then
3947          aug = 'Plain'
3948        end
3949        typ = ('%s(%s)'):format(typ, aug)
3950        east_api_node.augmentation = nil
3951      end
3952      typ = ('%s:%u:%u:%s'):format(
3953        typ,
3954        east_api_node.start[1],
3955        east_api_node.start[2],
3956        line:sub(east_api_node.start[2] + 1, east_api_node.start[2] + 1 + east_api_node.len - 1)
3957      )
3958      assert(east_api_node.start[2] + east_api_node.len - 1 <= #line)
3959      for k, _ in pairs(east_api_node.start) do
3960        assert(({ true, true })[k])
3961      end
3962      east_api_node.start = nil
3963      east_api_node.type = nil
3964      east_api_node.len = nil
3965      local can_simplify = true
3966      for _, _ in pairs(east_api_node) do
3967        if can_simplify then
3968          can_simplify = false
3969        end
3970      end
3971      if can_simplify then
3972        return typ
3973      else
3974        east_api_node[1] = typ
3975        return east_api_node
3976      end
3977    end
3978    local function simplify_east_api(line, east_api)
3979      if east_api.error then
3980        east_api.err = east_api.error
3981        east_api.error = nil
3982        east_api.err.msg = east_api.err.message
3983        east_api.err.message = nil
3984      end
3985      if east_api.ast then
3986        east_api.ast = { simplify_east_api_node(line, east_api.ast) }
3987        if #east_api.ast == 0 then
3988          east_api.ast = nil
3989        end
3990      end
3991      if east_api.len == #line then
3992        east_api.len = nil
3993      end
3994      return east_api
3995    end
3996    local function simplify_east_hl(line, east_hl)
3997      for i, v in ipairs(east_hl) do
3998        east_hl[i] = ('%s:%u:%u:%s'):format(v[4], v[1], v[2], line:sub(v[2] + 1, v[3]))
3999      end
4000      return east_hl
4001    end
4002    local FLAGS_TO_STR = {
4003      [0] = '',
4004      [1] = 'm',
4005      [2] = 'E',
4006      [3] = 'mE',
4007      [4] = 'l',
4008      [5] = 'lm',
4009      [6] = 'lE',
4010      [7] = 'lmE',
4011    }
4012    local function _check_parsing(opts, str, exp_ast, exp_highlighting_fs, nz_flags_exps)
4013      if type(str) ~= 'string' then
4014        return
4015      end
4016      local zflags = opts.flags[1]
4017      nz_flags_exps = nz_flags_exps or {}
4018      for _, flags in ipairs(opts.flags) do
4019        local err, msg = pcall(function()
4020          local east_api = api.nvim_parse_expression(str, FLAGS_TO_STR[flags], true)
4021          local east_hl = east_api.highlight
4022          east_api.highlight = nil
4023          local ast = simplify_east_api(str, east_api)
4024          local hls = simplify_east_hl(str, east_hl)
4025          local exps = {
4026            ast = exp_ast,
4027            hl_fs = exp_highlighting_fs,
4028          }
4029          local add_exps = nz_flags_exps[flags]
4030          if not add_exps and flags == 3 + zflags then
4031            add_exps = nz_flags_exps[1 + zflags] or nz_flags_exps[2 + zflags]
4032          end
4033          if add_exps then
4034            if add_exps.ast then
4035              exps.ast = mergedicts_copy(exps.ast, add_exps.ast)
4036            end
4037            if add_exps.hl_fs then
4038              exps.hl_fs = mergedicts_copy(exps.hl_fs, add_exps.hl_fs)
4039            end
4040          end
4041          eq(exps.ast, ast)
4042          if exp_highlighting_fs then
4043            local exp_highlighting = {}
4044            local next_col = 0
4045            for i, h in ipairs(exps.hl_fs) do
4046              exp_highlighting[i], next_col = h(next_col)
4047            end
4048            eq(exp_highlighting, hls)
4049          end
4050        end)
4051        if not err then
4052          if type(msg) == 'table' then
4053            local merr, new_msg = pcall(format_string, 'table error:\n%s\n\n(%r)', msg.message, msg)
4054            if merr then
4055              msg = new_msg
4056            else
4057              msg = format_string('table error without .message:\n(%r)', msg)
4058            end
4059          elseif type(msg) ~= 'string' then
4060            msg = format_string('non-string non-table error:\n%r', msg)
4061          end
4062          error(
4063            format_string(
4064              'Error while processing test (%r, %s):\n%s',
4065              str,
4066              FLAGS_TO_STR[flags],
4067              msg
4068            )
4069          )
4070        end
4071      end
4072    end
4073    local function hl(group, str, shift)
4074      return function(next_col)
4075        local col = next_col + (shift or 0)
4076        return (('%s:%u:%u:%s'):format('Nvim' .. group, 0, col, str)), (col + #str)
4077      end
4078    end
4079    local function fmtn(typ, args, rest)
4080      if
4081        typ == 'UnknownFigure'
4082        or typ == 'DictLiteral'
4083        or typ == 'CurlyBracesIdentifier'
4084        or typ == 'Lambda'
4085      then
4086        return ('%s%s'):format(typ, rest)
4087      elseif typ == 'DoubleQuotedString' or typ == 'SingleQuotedString' then
4088        if args:sub(-4) == 'NULL' then
4089          args = args:sub(1, -5) .. '""'
4090        end
4091        return ('%s(%s)%s'):format(typ, args, rest)
4092      end
4093    end
4094
4095    it('does not crash parsing invalid VimL expression', function()
4096      api.nvim_input(':<C-r>=')
4097      api.nvim_input('1bork/') -- #29648
4098      assert_alive()
4099      api.nvim_input('<C-u>];')
4100      assert_alive()
4101      api.nvim_parse_expression('a{b}', '', false)
4102      assert_alive()
4103    end)
4104
4105    require('test.unit.viml.expressions.parser_tests')(it, _check_parsing, hl, fmtn)
4106  end)
4107
4108  describe('nvim_list_uis', function()
4109    it('returns empty if --headless', function()
4110      -- Test runner defaults to --headless.
4111      eq({}, api.nvim_list_uis())
4112    end)
4113    it('returns attached UIs', function()
4114      local screen = Screen.new(20, 4, { override = true })
4115      local expected = {
4116        {
4117          chan = 1,
4118          ext_cmdline = false,
4119          ext_hlstate = false,
4120          ext_linegrid = screen._options.ext_linegrid or false,
4121          ext_messages = false,
4122          ext_multigrid = false,
4123          ext_popupmenu = false,
4124          ext_tabline = false,
4125          ext_termcolors = false,
4126          ext_wildmenu = false,
4127          height = 4,
4128          override = true,
4129          rgb = true,
4130          stdin_tty = false,
4131          stdout_tty = false,
4132          term_background = '',
4133          term_colors = 0,
4134          term_name = '',
4135          width = 20,
4136        },
4137      }
4138
4139      eq(expected, api.nvim_list_uis())
4140
4141      screen:detach()
4142      screen = Screen.new(44, 99, { rgb = false }) -- luacheck: ignore
4143      expected[1].rgb = false
4144      expected[1].override = false
4145      expected[1].width = 44
4146      expected[1].height = 99
4147      eq(expected, api.nvim_list_uis())
4148    end)
4149  end)
4150
4151  describe('nvim_create_namespace', function()
4152    it('works', function()
4153      local orig = api.nvim_get_namespaces()
4154      local base = vim.iter(orig):fold(0, function(acc, _, v)
4155        return math.max(acc, v)
4156      end)
4157      eq(base + 1, api.nvim_create_namespace('ns-1'))
4158      eq(base + 2, api.nvim_create_namespace('ns-2'))
4159      eq(base + 1, api.nvim_create_namespace('ns-1'))
4160
4161      local expected = vim.tbl_extend('error', orig, {
4162        ['ns-1'] = base + 1,
4163        ['ns-2'] = base + 2,
4164      })
4165
4166      eq(expected, api.nvim_get_namespaces())
4167      eq(base + 3, api.nvim_create_namespace(''))
4168      eq(base + 4, api.nvim_create_namespace(''))
4169      eq(expected, api.nvim_get_namespaces())
4170    end)
4171  end)
4172
4173  describe('nvim_create_buf', function()
4174    it('works', function()
4175      eq(2, api.nvim_create_buf(true, false))
4176      eq(3, api.nvim_create_buf(false, false))
4177      eq(
4178        '  1 %a   "[No Name]"                    line 1\n'
4179          .. '  2  h   "[No Name]"                    line 0',
4180        command_output('ls')
4181      )
4182      -- current buffer didn't change
4183      eq(1, api.nvim_get_current_buf())
4184
4185      local screen = Screen.new(20, 4)
4186      api.nvim_buf_set_lines(2, 0, -1, true, { 'some text' })
4187      api.nvim_set_current_buf(2)
4188      screen:expect(
4189        [[
4190        ^some text           |
4191        {1:~                   }|*2
4192                            |
4193      ]],
4194        {
4195          [1] = { bold = true, foreground = Screen.colors.Blue1 },
4196        }
4197      )
4198    end)
4199
4200    it('can change buftype before visiting', function()
4201      api.nvim_set_option_value('hidden', false, {})
4202      eq(2, api.nvim_create_buf(true, false))
4203      api.nvim_set_option_value('buftype', 'nofile', { buf = 2 })
4204      api.nvim_buf_set_lines(2, 0, -1, true, { 'test text' })
4205      command('split | buffer 2')
4206      eq(2, api.nvim_get_current_buf())
4207      -- if the buf_set_option("buftype") didn't work, this would error out.
4208      command('close')
4209      eq(1, api.nvim_get_current_buf())
4210    end)
4211
4212    it('does not trigger BufEnter, BufWinEnter', function()
4213      command('let g:fired = v:false')
4214      command('au BufEnter,BufWinEnter * let g:fired = v:true')
4215
4216      eq(2, api.nvim_create_buf(true, false))
4217      api.nvim_buf_set_lines(2, 0, -1, true, { 'test', 'text' })
4218
4219      eq(false, eval('g:fired'))
4220    end)
4221
4222    it('TextChanged and TextChangedI do not trigger without changes', function()
4223      local buf = api.nvim_create_buf(true, false)
4224      command([[let g:changed = '']])
4225      api.nvim_create_autocmd({ 'TextChanged', 'TextChangedI' }, {
4226        buffer = buf,
4227        command = 'let g:changed ..= mode()',
4228      })
4229      api.nvim_set_current_buf(buf)
4230      feed('i')
4231      eq('', api.nvim_get_var('changed'))
4232    end)
4233
4234    it('scratch-buffer', function()
4235      eq(2, api.nvim_create_buf(false, true))
4236      eq(3, api.nvim_create_buf(true, true))
4237      eq(4, api.nvim_create_buf(true, true))
4238      local scratch_bufs = { 2, 3, 4 }
4239      eq(
4240        '  1 %a   "[No Name]"                    line 1\n'
4241          .. '  3  h   "[Scratch]"                    line 0\n'
4242          .. '  4  h   "[Scratch]"                    line 0',
4243        exec_capture('ls')
4244      )
4245      -- current buffer didn't change
4246      eq(1, api.nvim_get_current_buf())
4247
4248      local screen = Screen.new(20, 4)
4249
4250      --
4251      -- Editing a scratch-buffer does NOT change its properties.
4252      --
4253      local edited_buf = 2
4254      api.nvim_buf_set_lines(edited_buf, 0, -1, true, { 'some text' })
4255      for _, b in ipairs(scratch_bufs) do
4256        eq('nofile', api.nvim_get_option_value('buftype', { buf = b }))
4257        eq('hide', api.nvim_get_option_value('bufhidden', { buf = b }))
4258        eq(false, api.nvim_get_option_value('swapfile', { buf = b }))
4259        eq(false, api.nvim_get_option_value('modeline', { buf = b }))
4260      end
4261
4262      --
4263      -- Visiting a scratch-buffer DOES NOT change its properties.
4264      --
4265      api.nvim_set_current_buf(edited_buf)
4266      screen:expect([[
4267        ^some text           |
4268        {1:~                   }|*2
4269                            |
4270      ]])
4271      eq('nofile', api.nvim_get_option_value('buftype', { buf = edited_buf }))
4272      eq('hide', api.nvim_get_option_value('bufhidden', { buf = edited_buf }))
4273      eq(false, api.nvim_get_option_value('swapfile', { buf = edited_buf }))
4274      eq(false, api.nvim_get_option_value('modeline', { buf = edited_buf }))
4275
4276      -- Scratch buffer can be wiped without error.
4277      command('bwipe')
4278      screen:expect([[
4279        ^                    |
4280        {1:~                   }|*2
4281                            |
4282      ]])
4283    end)
4284
4285    it('does not cause heap-use-after-free on exit while setting options', function()
4286      command('au OptionSet * q')
4287      command('silent! call nvim_create_buf(0, 1)')
4288      -- nowadays this works because we don't execute any spurious autocmds at all #24824
4289      assert_alive()
4290    end)
4291
4292    it('no memory leak when autocommands load the buffer immediately', function()
4293      exec([[
4294        autocmd BufNew * ++once call bufload(expand("<abuf>")->str2nr())
4295                             \| let loaded = bufloaded(expand("<abuf>")->str2nr())
4296      ]])
4297      api.nvim_create_buf(false, true)
4298      eq(1, eval('g:loaded'))
4299    end)
4300
4301    it('creating scratch buffer where autocommands set &swapfile works', function()
4302      exec([[
4303        autocmd BufNew * ++once execute expand("<abuf>") "buffer"
4304                             \| file foobar
4305                             \| setlocal swapfile
4306      ]])
4307      local new_buf = api.nvim_create_buf(false, true)
4308      neq('', fn.swapname(new_buf))
4309    end)
4310
4311    it('fires expected autocommands', function()
4312      exec([=[
4313        " Append the &buftype to check autocommands trigger *after* the buffer was configured to be
4314        " scratch, if applicable.
4315        autocmd BufNew * let fired += [["BufNew", expand("<abuf>")->str2nr(),
4316                                      \ getbufvar(expand("<abuf>")->str2nr(), "&buftype")]]
4317        autocmd BufAdd * let fired += [["BufAdd", expand("<abuf>")->str2nr(),
4318                                      \ getbufvar(expand("<abuf>")->str2nr(), "&buftype")]]
4319
4320        " Don't want to see OptionSet; buffer options set from passing true for "scratch", etc.
4321        " should be configured invisibly, and before autocommands.
4322        autocmd OptionSet * let fired += [["OptionSet", expand("<amatch>")]]
4323
4324        let fired = []
4325      ]=])
4326      local new_buf = api.nvim_create_buf(false, false)
4327      eq({ { 'BufNew', new_buf, '' } }, eval('g:fired'))
4328
4329      command('let fired = []')
4330      new_buf = api.nvim_create_buf(false, true)
4331      eq({ { 'BufNew', new_buf, 'nofile' } }, eval('g:fired'))
4332
4333      command('let fired = []')
4334      new_buf = api.nvim_create_buf(true, false)
4335      eq({ { 'BufNew', new_buf, '' }, { 'BufAdd', new_buf, '' } }, eval('g:fired'))
4336
4337      command('let fired = []')
4338      new_buf = api.nvim_create_buf(true, true)
4339      eq({ { 'BufNew', new_buf, 'nofile' }, { 'BufAdd', new_buf, 'nofile' } }, eval('g:fired'))
4340    end)
4341  end)
4342
4343  describe('nvim_get_runtime_file', function()
4344    it('can find files', function()
4345      eq({}, api.nvim_get_runtime_file('bork.borkbork', false))
4346      eq({}, api.nvim_get_runtime_file('bork.borkbork', true))
4347      eq(1, #api.nvim_get_runtime_file('autoload/msgpack.vim', false))
4348      eq(1, #api.nvim_get_runtime_file('autoload/msgpack.vim', true))
4349      local val = api.nvim_get_runtime_file('autoload/remote/*.vim', true)
4350      eq(2, #val)
4351      if endswith(val[1], 'define.vim') then
4352        ok(endswith(val[1], 'autoload/remote/define.vim'))
4353        ok(endswith(val[2], 'autoload/remote/host.vim'))
4354      else
4355        ok(endswith(val[1], 'autoload/remote/host.vim'))
4356        ok(endswith(val[2], 'autoload/remote/define.vim'))
4357      end
4358      val = api.nvim_get_runtime_file('autoload/remote/*.vim', false)
4359      eq(1, #val)
4360      ok(
4361        endswith(val[1], 'autoload/remote/define.vim')
4362          or endswith(val[1], 'autoload/remote/host.vim')
4363      )
4364
4365      val = api.nvim_get_runtime_file('lua', true)
4366      eq(1, #val)
4367      ok(endswith(val[1], 'lua'))
4368
4369      val = api.nvim_get_runtime_file('lua/vim', true)
4370      eq(1, #val)
4371      ok(endswith(val[1], 'lua/vim'))
4372    end)
4373
4374    it('can find directories', function()
4375      local val = api.nvim_get_runtime_file('lua/', true)
4376      eq(1, #val)
4377      ok(endswith(val[1], 'lua/'))
4378
4379      val = api.nvim_get_runtime_file('lua/vim/', true)
4380      eq(1, #val)
4381      ok(endswith(val[1], 'lua/vim/'))
4382
4383      eq({}, api.nvim_get_runtime_file('foobarlang/', true))
4384    end)
4385    it('can handle bad patterns', function()
4386      skip(is_os('win'))
4387
4388      eq('Vim:E220: Missing }.', pcall_err(api.nvim_get_runtime_file, '{', false))
4389
4390      eq(
4391        'Vim(echo):E5555: API call: Vim:E220: Missing }.',
4392        pcall_err(command, "echo nvim_get_runtime_file('{', v:false)")
4393      )
4394    end)
4395    it('preserves order of runtimepath', function()
4396      local vimruntime = fn.getenv('VIMRUNTIME')
4397      local rtp = string.format('%s/syntax,%s/ftplugin', vimruntime, vimruntime)
4398      api.nvim_set_option_value('runtimepath', rtp, {})
4399
4400      local val = api.nvim_get_runtime_file('vim.vim', true)
4401      eq(2, #val)
4402      eq(val[1], ('%s/syntax/vim.vim'):format(vimruntime))
4403      eq(val[2], ('%s/ftplugin/vim.vim'):format(vimruntime))
4404    end)
4405
4406    it('finds files via an 8.3 filename path #25019', function()
4407      skip(not is_os('win'), 'N/A: 8.3 filenames are only available on Windows')
4408      fn.system(('fsutil 8dot3name set %s 0'):format(n.nvim_dir:sub(1, 2)))
4409      local path = 'Xtest_runtime_path'
4410      mkdir_p(('%s/subdir/lua'):format(path))
4411      write_file(('%s/subdir/lua/foo.lua'):format(path), '')
4412      finally(function()
4413        rmdir(path)
4414      end)
4415      local path_with_shortname = fn.system(('for %%I in ("%s") do @echo %%~sI'):format(path), '')
4416      path_with_shortname = vim.fs.normalize(vim.trim(path_with_shortname))
4417      eq('XTEST_~1', vim.fs.basename(path_with_shortname))
4418      exec_lua(('vim.opt.rtp:prepend("%s/*")'):format(path_with_shortname))
4419      local val = api.nvim_get_runtime_file('lua/foo.lua', true)
4420      eq(1, #val)
4421      eq(('%s/subdir/lua/foo.lua'):format(path_with_shortname), val[1])
4422    end)
4423  end)
4424
4425  describe('nvim_get_all_options_info', function()
4426    it('should have key value pairs of option names', function()
4427      local options_info = api.nvim_get_all_options_info()
4428      neq(nil, options_info.listchars)
4429      neq(nil, options_info.tabstop)
4430
4431      eq(api.nvim_get_option_info 'winhighlight', options_info.winhighlight)
4432    end)
4433
4434    it('should not crash when echoed', function()
4435      api.nvim_exec2('echo nvim_get_all_options_info()', { output = true })
4436    end)
4437  end)
4438
4439  describe('nvim_get_option_info', function()
4440    it('should error for unknown options', function()
4441      eq("Invalid option (not found): 'bogus'", pcall_err(api.nvim_get_option_info, 'bogus'))
4442    end)
4443
4444    it('should return the same options for short and long name', function()
4445      eq(api.nvim_get_option_info 'winhl', api.nvim_get_option_info 'winhighlight')
4446    end)
4447
4448    it('should have information about window options', function()
4449      eq({
4450        allows_duplicates = false,
4451        commalist = true,
4452        default = '',
4453        flaglist = false,
4454        global_local = false,
4455        last_set_chan = 0,
4456        last_set_linenr = 0,
4457        last_set_sid = 0,
4458        name = 'winhighlight',
4459        scope = 'win',
4460        shortname = 'winhl',
4461        type = 'string',
4462        was_set = false,
4463      }, api.nvim_get_option_info 'winhl')
4464    end)
4465
4466    it('should have information about buffer options', function()
4467      eq({
4468        allows_duplicates = true,
4469        commalist = false,
4470        default = '',
4471        flaglist = false,
4472        global_local = false,
4473        last_set_chan = 0,
4474        last_set_linenr = 0,
4475        last_set_sid = 0,
4476        name = 'filetype',
4477        scope = 'buf',
4478        shortname = 'ft',
4479        type = 'string',
4480        was_set = false,
4481      }, api.nvim_get_option_info 'filetype')
4482    end)
4483
4484    it('should have information about global options', function()
4485      -- precondition: the option was changed from its default
4486      -- in test setup.
4487      eq(false, api.nvim_get_option_value('showcmd', {}))
4488
4489      eq({
4490        allows_duplicates = true,
4491        commalist = false,
4492        default = true,
4493        flaglist = false,
4494        global_local = false,
4495        last_set_chan = 0,
4496        last_set_linenr = 0,
4497        last_set_sid = -2,
4498        name = 'showcmd',
4499        scope = 'global',
4500        shortname = 'sc',
4501        type = 'boolean',
4502        was_set = true,
4503      }, api.nvim_get_option_info 'showcmd')
4504
4505      api.nvim_set_option_value('showcmd', true, {})
4506
4507      eq({
4508        allows_duplicates = true,
4509        commalist = false,
4510        default = true,
4511        flaglist = false,
4512        global_local = false,
4513        last_set_chan = 1,
4514        last_set_linenr = 0,
4515        last_set_sid = -9,
4516        name = 'showcmd',
4517        scope = 'global',
4518        shortname = 'sc',
4519        type = 'boolean',
4520        was_set = true,
4521      }, api.nvim_get_option_info 'showcmd')
4522    end)
4523  end)
4524
4525  describe('nvim_get_option_info2', function()
4526    local fname
4527    local bufs
4528    local wins
4529
4530    before_each(function()
4531      fname = tmpname()
4532      write_file(
4533        fname,
4534        [[
4535        setglobal dictionary=mydict " 1, global-local (buffer)
4536        setlocal  formatprg=myprg   " 2, global-local (buffer)
4537        setglobal equalprg=prg1     " 3, global-local (buffer)
4538        setlocal  equalprg=prg2     " 4, global-local (buffer)
4539        setglobal fillchars=stl:x   " 5, global-local (window)
4540        setlocal  listchars=eol:c   " 6, global-local (window)
4541        setglobal showbreak=aaa     " 7, global-local (window)
4542        setlocal  showbreak=bbb     " 8, global-local (window)
4543        setglobal completeopt=menu  " 9, global
4544      ]]
4545      )
4546
4547      exec_lua 'vim.cmd.vsplit()'
4548      api.nvim_create_buf(false, false)
4549
4550      bufs = api.nvim_list_bufs()
4551      wins = api.nvim_list_wins()
4552
4553      api.nvim_win_set_buf(wins[1], bufs[1])
4554      api.nvim_win_set_buf(wins[2], bufs[2])
4555
4556      api.nvim_set_current_win(wins[2])
4557      api.nvim_exec('source ' .. fname, false)
4558
4559      api.nvim_set_current_win(wins[1])
4560    end)
4561
4562    after_each(function()
4563      os.remove(fname)
4564    end)
4565
4566    it('gets option info', function()
4567      eq(api.nvim_get_option_info('dictionary'), api.nvim_get_option_info2('dictionary', {})) -- buffer
4568      eq(api.nvim_get_option_info('fillchars'), api.nvim_get_option_info2('fillchars', {})) -- window
4569      eq(api.nvim_get_option_info('completeopt'), api.nvim_get_option_info2('completeopt', {})) -- global
4570      eq('tab', api.nvim_get_option_info2('cmdheight', {}).scope) -- tab #31140
4571    end)
4572
4573    describe('last set', function()
4574      -- stylua: ignore
4575      local tests = {
4576        {desc="(buf option, global requested, global set) points to global",   linenr=1, sid=1, args={'dictionary', {scope='global'}}},
4577        {desc="(buf option, global requested, local set) is not set",          linenr=0, sid=0, args={'formatprg',  {scope='global'}}},
4578        {desc="(buf option, global requested, both set) points to global",     linenr=3, sid=1, args={'equalprg',   {scope='global'}}},
4579        {desc="(buf option, local requested, global set) is not set",          linenr=0, sid=0, args={'dictionary', {scope='local'}}},
4580        {desc="(buf option, local requested, local set) points to local",      linenr=2, sid=1, args={'formatprg',  {scope='local'}}},
4581        {desc="(buf option, local requested, both set) points to local",       linenr=4, sid=1, args={'equalprg',   {scope='local'}}},
4582        {desc="(buf option, fallback requested, global set) points to global", linenr=1, sid=1, args={'dictionary', {}}},
4583        {desc="(buf option, fallback requested, local set) points to local",   linenr=2, sid=1, args={'formatprg',  {}}},
4584        {desc="(buf option, fallback requested, both set) points to local",    linenr=4, sid=1, args={'equalprg',   {}}},
4585        {desc="(win option, global requested, global set) points to global",   linenr=5, sid=1, args={'fillchars', {scope='global'}}},
4586        {desc="(win option, global requested, local set) is not set",          linenr=0, sid=0, args={'listchars', {scope='global'}}},
4587        {desc="(win option, global requested, both set) points to global",     linenr=7, sid=1, args={'showbreak', {scope='global'}}},
4588        {desc="(win option, local requested, global set) is not set",          linenr=0, sid=0, args={'fillchars', {scope='local'}}},
4589        {desc="(win option, local requested, local set) points to local",      linenr=6, sid=1, args={'listchars', {scope='local'}}},
4590        {desc="(win option, local requested, both set) points to local",       linenr=8, sid=1, args={'showbreak', {scope='local'}}},
4591        {desc="(win option, fallback requested, global set) points to global", linenr=5, sid=1, args={'fillchars', {}}},
4592        {desc="(win option, fallback requested, local set) points to local",   linenr=6, sid=1, args={'listchars', {}}},
4593        {desc="(win option, fallback requested, both set) points to local",    linenr=8, sid=1, args={'showbreak', {}}},
4594        {desc="(global option, global requested) points to global",            linenr=9, sid=1, args={'completeopt', {scope='global'}}},
4595        {desc="(global option, local requested) is not set",                   linenr=0, sid=0, args={'completeopt', {scope='local'}}},
4596        {desc="(global option, fallback requested) points to global",          linenr=9, sid=1, args={'completeopt', {}}},
4597      }
4598
4599      for _, test in pairs(tests) do
4600        it(test.desc, function()
4601          -- Switch to the target buffer/window so that curbuf/curwin are used.
4602          api.nvim_set_current_win(wins[2])
4603          local info = api.nvim_get_option_info2(unpack(test.args))
4604          eq(test.linenr, info.last_set_linenr)
4605          eq(test.sid, info.last_set_sid)
4606        end)
4607      end
4608
4609      it('cross-buffer', function()
4610        local info = api.nvim_get_option_info2('formatprg', { buf = bufs[2] })
4611        eq(2, info.last_set_linenr)
4612        eq(1, info.last_set_sid)
4613      end)
4614
4615      it('cross-window', function()
4616        local info = api.nvim_get_option_info2('listchars', { win = wins[2] })
4617        eq(6, info.last_set_linenr)
4618        eq(1, info.last_set_sid)
4619      end)
4620    end)
4621  end)
4622
4623  describe('nvim_echo', function()
4624    local screen
4625
4626    before_each(function()
4627      screen = Screen.new(40, 8)
4628      command('highlight Statement gui=bold guifg=Brown')
4629      command('highlight Special guifg=SlateBlue')
4630    end)
4631
4632    it('validation', function()
4633      eq("Invalid 'chunk': expected Array, got String", pcall_err(api.nvim_echo, { 'msg' }, 1, {}))
4634      eq(
4635        'Invalid chunk: expected Array with 1 or 2 Strings',
4636        pcall_err(api.nvim_echo, { { '', '', '' } }, 1, {})
4637      )
4638      eq("Invalid 'hl_group': 'text highlight'", pcall_err(api.nvim_echo, { { '', false } }, 1, {}))
4639      eq("Invalid 'id': 4", pcall_err(api.nvim_echo, { { 'foo' } }, false, { id = 4 }))
4640      eq("Invalid 'id': 0", pcall_err(api.nvim_echo, { { 'foo' } }, false, { id = 0 }))
4641      eq("Invalid 'id': -1", pcall_err(api.nvim_echo, { { 'foo' } }, false, { id = -1 }))
4642      -- String ids are always allowed (user-defined).
4643      eq('my.msg.id', api.nvim_echo({ { 'foo' } }, false, { id = 'my.msg.id' }))
4644      local opts = { kind = 'progress', source = 'nvim', status = 'success' }
4645      eq("Invalid 'source': 'nvim'", pcall_err(api.nvim_echo, { { '' } }, 1, opts))
4646    end)
4647
4648    it('should clear cmdline message before echo', function()
4649      feed(':call nvim_echo([["msg"]], v:false, {})<CR>')
4650      screen:expect {
4651        grid = [[
4652        ^                                        |
4653        {1:~                                       }|*6
4654        msg                                     |
4655      ]],
4656      }
4657    end)
4658
4659    it('can show highlighted line', function()
4660      async_meths.nvim_echo(
4661        { { 'msg_a' }, { 'msg_b', 'Statement' }, { 'msg_c', 'Special' } },
4662        true,
4663        {}
4664      )
4665      screen:expect {
4666        grid = [[
4667        ^                                        |
4668        {1:~                                       }|*6
4669        msg_a{15:msg_b}{16:msg_c}                         |
4670      ]],
4671      }
4672      async_meths.nvim_echo({
4673        { 'msg_d' },
4674        { 'msg_e', api.nvim_get_hl_id_by_name('Statement') },
4675        { 'msg_f', api.nvim_get_hl_id_by_name('Special') },
4676      }, true, {})
4677      screen:expect {
4678        grid = [[
4679        ^                                        |
4680        {1:~                                       }|*6
4681        msg_d{15:msg_e}{16:msg_f}                         |
4682      ]],
4683      }
4684    end)
4685
4686    it('can show highlighted multiline', function()
4687      async_meths.nvim_echo({ { 'msg_a\nmsg_a', 'Statement' }, { 'msg_b', 'Special' } }, true, {})
4688      screen:expect {
4689        grid = [[
4690                                                |
4691        {1:~                                       }|*3
4692        {3:                                        }|
4693        {15:msg_a}                                   |
4694        {15:msg_a}{16:msg_b}                              |
4695        {6:Press ENTER or type command to continue}^ |
4696      ]],
4697      }
4698    end)
4699
4700    it('can save message history', function()
4701      command('set cmdheight=2') -- suppress Press ENTER
4702      api.nvim_echo({ { 'msg\nmsg' }, { 'msg' } }, true, {})
4703      eq('msg\nmsgmsg', exec_capture('messages'))
4704    end)
4705
4706    it('can disable saving message history', function()
4707      command('set cmdheight=2') -- suppress Press ENTER
4708      async_meths.nvim_echo({ { 'msg\nmsg' }, { 'msg' } }, false, {})
4709      eq('', exec_capture('messages'))
4710    end)
4711
4712    it('can print error message', function()
4713      async_meths.nvim_echo({ { 'Error\nMessage' } }, false, { err = true })
4714      screen:expect([[
4715                                                |
4716        {1:~                                       }|*3
4717        {3:                                        }|
4718        {9:Error}                                   |
4719        {9:Message}                                 |
4720        {6:Press ENTER or type command to continue}^ |
4721      ]])
4722      feed(':messages<CR>')
4723      screen:expect([[
4724        ^                                        |
4725        {1:~                                       }|*6
4726                                                |
4727      ]])
4728      async_meths.nvim_echo({ { 'Error' }, { 'Message', 'Special' } }, false, { err = true })
4729      screen:expect([[
4730        ^                                        |
4731        {1:~                                       }|*6
4732        {9:Error}{16:Message}                            |
4733      ]])
4734    end)
4735
4736    it('increments message ID', function()
4737      eq(1, api.nvim_echo({ { 'foo' } }, false, {}))
4738      eq(1, api.nvim_echo({ { 'foo' } }, false, { id = 1 })) -- User may pass existing id.
4739      eq(2, api.nvim_echo({ { 'foo' } }, false, {}))
4740    end)
4741
4742    it('no use-after-free for custom kind with :messages #38289', function()
4743      exec_lua(function()
4744        vim.api.nvim_echo({ { 'a' } }, true, { kind = 'foo' })
4745        vim.o.guicursor = '' -- pending mode update go brrr
4746        vim.api.nvim__redraw({ flush = true }) -- ui_flush -> arena_mem_free go brrr
4747        vim.cmd.messages()
4748      end)
4749    end)
4750  end)
4751
4752  describe('nvim_open_term', function()
4753    local screen
4754
4755    before_each(function()
4756      screen = Screen.new(100, 35)
4757      screen:add_extra_attr_ids {
4758        [100] = { background = tonumber('0xffff40'), bg_indexed = true },
4759        [101] = {
4760          background = Screen.colors.LightMagenta,
4761          foreground = tonumber('0x00e000'),
4762          fg_indexed = true,
4763        },
4764        [102] = { background = Screen.colors.LightMagenta, reverse = true },
4765        [103] = { background = Screen.colors.LightMagenta, bold = true, reverse = true },
4766        [104] = { fg_indexed = true, foreground = tonumber('0xe00000') },
4767        [105] = { fg_indexed = true, foreground = tonumber('0xe0e000') },
4768      }
4769    end)
4770
4771    it('can batch process sequences', function()
4772      local b = api.nvim_create_buf(true, true)
4773      api.nvim_open_win(
4774        b,
4775        false,
4776        { width = 79, height = 31, row = 1, col = 1, relative = 'editor' }
4777      )
4778      local term = api.nvim_open_term(b, {})
4779
4780      api.nvim_chan_send(term, io.open('test/functional/fixtures/smile2.cat', 'r'):read('*a'))
4781      screen:expect {
4782        grid = [[
4783        ^                                                                                                    |
4784        {1:~}{4::smile                                                                         }{1:                    }|
4785        {1:~}{4:                            }{100:oooo$$$$$$$$$$$$oooo}{4:                               }{1:                    }|
4786        {1:~}{4:                        }{100:oo$$$$$$$$$$$$$$$$$$$$$$$$o}{4:                            }{1:                    }|
4787        {1:~}{4:                     }{100:oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o}{4:         }{100:o$}{4:   }{100:$$}{4: }{100:o$}{4:      }{1:                    }|
4788        {1:~}{4:     }{100:o}{4: }{100:$}{4: }{100:oo}{4:        }{100:o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o}{4:       }{100:$$}{4: }{100:$$}{4: }{100:$$o$}{4:     }{1:                    }|
4789        {1:~}{4:  }{100:oo}{4: }{100:$}{4: }{100:$}{4: "}{100:$}{4:      }{100:o$$$$$$$$$}{4:    }{100:$$$$$$$$$$$$$}{4:    }{100:$$$$$$$$$o}{4:       }{100:$$$o$$o$}{4:      }{1:                    }|
4790        {1:~}{4:  "}{100:$$$$$$o$}{4:     }{100:o$$$$$$$$$}{4:      }{100:$$$$$$$$$$$}{4:      }{100:$$$$$$$$$$o}{4:    }{100:$$$$$$$$}{4:       }{1:                    }|
4791        {1:~}{4:    }{100:$$$$$$$}{4:    }{100:$$$$$$$$$$$}{4:      }{100:$$$$$$$$$$$}{4:      }{100:$$$$$$$$$$$$$$$$$$$$$$$}{4:       }{1:                    }|
4792        {1:~}{4:    }{100:$$$$$$$$$$$$$$$$$$$$$$$}{4:    }{100:$$$$$$$$$$$$$}{4:    }{100:$$$$$$$$$$$$$$}{4:  """}{100:$$$}{4:         }{1:                    }|
4793        {1:~}{4:     "}{100:$$$}{4:""""}{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:     "}{100:$$$}{4:        }{1:                    }|
4794        {1:~}{4:      }{100:$$$}{4:   }{100:o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:     "}{100:$$$o}{4:      }{1:                    }|
4795        {1:~}{4:     }{100:o$$}{4:"   }{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:       }{100:$$$o}{4:     }{1:                    }|
4796        {1:~}{4:     }{100:$$$}{4:    }{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:" "}{100:$$$$$$ooooo$$$$o}{4:   }{1:                    }|
4797        {1:~}{4:    }{100:o$$$oooo$$$$$}{4:  }{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:   }{100:o$$$$$$$$$$$$$$$$$}{4:  }{1:                    }|
4798        {1:~}{4:    }{100:$$$$$$$$}{4:"}{100:$$$$}{4:   }{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:     }{100:$$$$}{4:""""""""        }{1:                    }|
4799        {1:~}{4:   """"       }{100:$$$$}{4:    "}{100:$$$$$$$$$$$$$$$$$$$$$$$$$$$$}{4:"      }{100:o$$$}{4:                 }{1:                    }|
4800        {1:~}{4:              "}{100:$$$o}{4:     """}{100:$$$$$$$$$$$$$$$$$$}{4:"}{100:$$}{4:"         }{100:$$$}{4:                  }{1:                    }|
4801        {1:~}{4:                }{100:$$$o}{4:          "}{100:$$}{4:""}{100:$$$$$$}{4:""""           }{100:o$$$}{4:                   }{1:                    }|
4802        {1:~}{4:                 }{100:$$$$o}{4:                                }{100:o$$$}{4:"                    }{1:                    }|
4803        {1:~}{4:                  "}{100:$$$$o}{4:      }{100:o$$$$$$o}{4:"}{100:$$$$o}{4:        }{100:o$$$$}{4:                      }{1:                    }|
4804        {1:~}{4:                    "}{100:$$$$$oo}{4:     ""}{100:$$$$o$$$$$o}{4:   }{100:o$$$$}{4:""                       }{1:                    }|
4805        {1:~}{4:                       ""}{100:$$$$$oooo}{4:  "}{100:$$$o$$$$$$$$$}{4:"""                          }{1:                    }|
4806        {1:~}{4:                          ""}{100:$$$$$$$oo}{4: }{100:$$$$$$$$$$}{4:                               }{1:                    }|
4807        {1:~}{4:                                  """"}{100:$$$$$$$$$$$}{4:                              }{1:                    }|
4808        {1:~}{4:                                      }{100:$$$$$$$$$$$$}{4:                             }{1:                    }|
4809        {1:~}{4:                                       }{100:$$$$$$$$$$}{4:"                             }{1:                    }|
4810        {1:~}{4:                                        "}{100:$$$}{4:""""                               }{1:                    }|
4811        {1:~}{4:                                                                               }{1:                    }|
4812        {1:~}{101:Press ENTER or type command to continue}{4:                                        }{1:                    }|
4813        {1:~}{103:term://~/config2/docs/pres//32693:vim --clean +smile         29,39          All}{1:                    }|
4814        {1:~}{4::call nvim__screenshot("smile2.cat")                                           }{1:                    }|
4815        {1:~                                                                                                   }|*2
4816                                                                                                            |
4817      ]],
4818      }
4819    end)
4820
4821    it('can handle input', function()
4822      screen:try_resize(50, 10)
4823      eq(
4824        { 3, 2 },
4825        exec_lua [[
4826        buf = vim.api.nvim_create_buf(1,1)
4827
4828        stream = ''
4829        do_the_echo = false
4830        function input(_,t1,b1,data)
4831          stream = stream .. data
4832          _G.vals = {t1, b1}
4833          if do_the_echo then
4834            vim.api.nvim_chan_send(t1, data)
4835          end
4836        end
4837
4838        term = vim.api.nvim_open_term(buf, {on_input=input})
4839        vim.api.nvim_open_win(buf, true, {width=40, height=5, row=1, col=1, relative='editor'})
4840        return {term, buf}
4841      ]]
4842      )
4843
4844      screen:expect {
4845        grid = [[
4846                                                          |
4847        {1:~}{4:^                                        }{1:         }|
4848        {1:~}{4:                                        }{1:         }|*4
4849        {1:~                                                 }|*3
4850                                                          |
4851      ]],
4852      }
4853
4854      feed 'iba<c-x>bla'
4855      screen:expect {
4856        grid = [[
4857                                                          |
4858        {1:~}{4:^                                        }{1:         }|
4859        {1:~}{4:                                        }{1:         }|*4
4860        {1:~                                                 }|*3
4861        {5:-- TERMINAL --}                                    |
4862      ]],
4863      }
4864
4865      eq('ba\024bla', exec_lua [[ return stream ]])
4866      eq({ 3, 2 }, exec_lua [[ return vals ]])
4867
4868      exec_lua [[ do_the_echo = true ]]
4869      feed 'herrejösses!'
4870
4871      screen:expect {
4872        grid = [[
4873                                                          |
4874        {1:~}{4:herrejösses!^                            }{1:         }|
4875        {1:~}{4:                                        }{1:         }|*4
4876        {1:~                                                 }|*3
4877        {5:-- TERMINAL --}                                    |
4878      ]],
4879      }
4880      eq('ba\024blaherrejösses!', exec_lua [[ return stream ]])
4881    end)
4882
4883    it('parses text from the current buffer', function()
4884      local b = api.nvim_create_buf(true, true)
4885      api.nvim_buf_set_lines(b, 0, -1, true, { '\027[31mHello\000\027[0m', '\027[33mworld\027[0m' })
4886      api.nvim_set_current_buf(b)
4887      screen:expect([[
4888        {18:^^[}[31mHello{18:^@^[}[0m                                                                                  |
4889        {18:^[}[33mworld{18:^[}[0m                                                                                    |
4890        {1:~                                                                                                   }|*32
4891                                                                                                            |
4892      ]])
4893      api.nvim_open_term(b, {})
4894      screen:expect([[
4895        {104:^Hello}                                                                                               |
4896        {105:world}                                                                                               |
4897                                                                                                            |*33
4898      ]])
4899    end)
4900  end)
4901
4902  describe('nvim_del_mark', function()
4903    it('works', function()
4904      local buf = api.nvim_create_buf(false, true)
4905      api.nvim_buf_set_lines(buf, -1, -1, true, { 'a', 'bit of', 'text' })
4906      eq(true, api.nvim_buf_set_mark(buf, 'F', 2, 2, {}))
4907      eq(true, api.nvim_del_mark('F'))
4908      eq({ 0, 0 }, api.nvim_buf_get_mark(buf, 'F'))
4909    end)
4910    it('validation', function()
4911      eq("Invalid mark name (must be file/uppercase): 'f'", pcall_err(api.nvim_del_mark, 'f'))
4912      eq("Invalid mark name (must be file/uppercase): '!'", pcall_err(api.nvim_del_mark, '!'))
4913      eq("Invalid mark name (must be a single char): 'fail'", pcall_err(api.nvim_del_mark, 'fail'))
4914    end)
4915  end)
4916  describe('nvim_get_mark', function()
4917    it('works', function()
4918      local buf = api.nvim_create_buf(false, true)
4919      api.nvim_buf_set_lines(buf, -1, -1, true, { 'a', 'bit of', 'text' })
4920      api.nvim_buf_set_mark(buf, 'F', 2, 2, {})
4921      api.nvim_buf_set_name(buf, 'mybuf')
4922      local mark = api.nvim_get_mark('F', {})
4923      -- Compare the path tail only
4924      matches('mybuf$', mark[4])
4925      eq({ 2, 2, buf, mark[4] }, mark)
4926    end)
4927    it('validation', function()
4928      eq("Invalid mark name (must be file/uppercase): 'f'", pcall_err(api.nvim_get_mark, 'f', {}))
4929      eq("Invalid mark name (must be file/uppercase): '!'", pcall_err(api.nvim_get_mark, '!', {}))
4930      eq(
4931        "Invalid mark name (must be a single char): 'fail'",
4932        pcall_err(api.nvim_get_mark, 'fail', {})
4933      )
4934    end)
4935    it('returns the expected when mark is not set', function()
4936      eq(true, api.nvim_del_mark('A'))
4937      eq({ 0, 0, 0, '' }, api.nvim_get_mark('A', {}))
4938    end)
4939    it('works with deleted buffers', function()
4940      local fname = tmpname()
4941      write_file(fname, 'a\nbit of\text')
4942      command('edit ' .. fname)
4943      local buf = api.nvim_get_current_buf()
4944
4945      api.nvim_buf_set_mark(buf, 'F', 2, 2, {})
4946      command('new') -- Create new buf to avoid :bd failing
4947      command('bd! ' .. buf)
4948      os.remove(fname)
4949
4950      local mark = api.nvim_get_mark('F', {})
4951      -- To avoid comparing relative vs absolute path
4952      local mfname = mark[4]
4953      local tail_patt = [[[\/][^\/]*$]]
4954      -- tail of paths should be equals
4955      eq(fname:match(tail_patt), mfname:match(tail_patt))
4956      eq({ 2, 2, buf, mark[4] }, mark)
4957    end)
4958  end)
4959
4960  describe('nvim_eval_statusline', function()
4961    it('works', function()
4962      eq({
4963        str = '%StatusLineStringWithHighlights',
4964        width = 31,
4965      }, api.nvim_eval_statusline('%%StatusLineString%#WarningMsg#WithHighlights', {}))
4966    end)
4967
4968    it('rejects invalid format characters', function()
4969      eq('E539: Illegal character <^>', pcall_err(api.nvim_eval_statusline, '%^', {}))
4970      eq('E539: Illegal character <}>', pcall_err(api.nvim_eval_statusline, '%{%}', {}))
4971    end)
4972
4973    it('reports an invalid window once', function()
4974      -- find_window_by_handle() already sets the error, so a second
4975      -- api_set_error() here would allocate a message over that one and leak it.
4976      eq('Invalid window id: 23', pcall_err(api.nvim_eval_statusline, 'a', { winid = 23 }))
4977    end)
4978
4979    it("doesn't exceed maxwidth", function()
4980      eq({
4981        str = 'Should be trun>',
4982        width = 15,
4983      }, api.nvim_eval_statusline('Should be truncated%<', { maxwidth = 15 }))
4984    end)
4985
4986    it('does not take a zero item width literally', function()
4987      command('file some/dir/testfile.txt')
4988      eq({ str = 'abc', width = 3 }, api.nvim_eval_statusline('%.0(abc%)', {}))
4989      eq(api.nvim_eval_statusline('%.50f', {}), api.nvim_eval_statusline('%.0f', {}))
4990      eq(api.nvim_eval_statusline('%.50l', {}), api.nvim_eval_statusline('%.0l', {}))
4991    end)
4992
4993    it('has correct default fillchar', function()
4994      local oldwin = api.nvim_get_current_win()
4995      command('set fillchars=stl:#,stlnc:$,wbr:%')
4996      command('new')
4997      eq({ str = 'a###b', width = 5 }, api.nvim_eval_statusline('a%=b', { maxwidth = 5 }))
4998      eq(
4999        { str = 'a$$$b', width = 5 },
5000        api.nvim_eval_statusline('a%=b', { winid = oldwin, maxwidth = 5 })
5001      )
5002      eq(
5003        { str = 'a%%%b', width = 5 },
5004        api.nvim_eval_statusline('a%=b', { use_winbar = true, maxwidth = 5 })
5005      )
5006      eq(
5007        { str = 'a   b', width = 5 },
5008        api.nvim_eval_statusline('a%=b', { use_tabline = true, maxwidth = 5 })
5009      )
5010      eq(
5011        { str = 'a   b', width = 5 },
5012        api.nvim_eval_statusline('a%=b', { use_statuscol_lnum = 1, maxwidth = 5 })
5013      )
5014    end)
5015
5016    for fc, desc in pairs({
5017      ['~'] = 'supports ASCII fillchar',
5018      ['━'] = 'supports single-width multibyte fillchar',
5019      ['c̳'] = 'supports single-width fillchar with composing',
5020      ['哦'] = 'treats double-width fillchar as single-width',
5021      ['\031'] = 'treats control character fillchar as single-width',
5022    }) do
5023      it(desc, function()
5024        eq(
5025          { str = 'a' .. fc:rep(3) .. 'b', width = 5 },
5026          api.nvim_eval_statusline('a%=b', { fillchar = fc, maxwidth = 5 })
5027        )
5028        eq(
5029          { str = 'a' .. fc:rep(3) .. 'b', width = 5 },
5030          api.nvim_eval_statusline('a%=b', { fillchar = fc, use_winbar = true, maxwidth = 5 })
5031        )
5032        eq(
5033          { str = 'a' .. fc:rep(3) .. 'b', width = 5 },
5034          api.nvim_eval_statusline('a%=b', { fillchar = fc, use_tabline = true, maxwidth = 5 })
5035        )
5036        eq(
5037          { str = 'a' .. fc:rep(3) .. 'b', width = 5 },
5038          api.nvim_eval_statusline('a%=b', { fillchar = fc, use_statuscol_lnum = 1, maxwidth = 5 })
5039        )
5040      end)
5041    end
5042
5043    it('rejects multiple-character fillchar', function()
5044      eq(
5045        "Invalid 'fillchar': expected single character",
5046        pcall_err(api.nvim_eval_statusline, '', { fillchar = 'aa' })
5047      )
5048    end)
5049
5050    it('rejects empty string fillchar', function()
5051      eq(
5052        "Invalid 'fillchar': expected single character",
5053        pcall_err(api.nvim_eval_statusline, '', { fillchar = '' })
5054      )
5055    end)
5056
5057    it('rejects non-string fillchar', function()
5058      eq(
5059        "Invalid 'fillchar': expected String, got Integer",
5060        pcall_err(api.nvim_eval_statusline, '', { fillchar = 1 })
5061      )
5062    end)
5063
5064    it('rejects invalid string', function()
5065      eq('E539: Illegal character <}>', pcall_err(api.nvim_eval_statusline, '%{%}', {}))
5066    end)
5067
5068    it('supports various items', function()
5069      eq({ str = '0', width = 1 }, api.nvim_eval_statusline('%l', { maxwidth = 5 }))
5070      command('set readonly')
5071      eq({ str = '[RO]', width = 4 }, api.nvim_eval_statusline('%r', { maxwidth = 5 }))
5072      local screen = Screen.new(80, 24)
5073      command('set showcmd')
5074      feed('1234')
5075      screen:expect({ any = '1234' })
5076      eq({ str = '1234', width = 4 }, api.nvim_eval_statusline('%S', { maxwidth = 5 }))
5077      feed('56')
5078      screen:expect({ any = '123456' })
5079      eq({ str = '<3456', width = 5 }, api.nvim_eval_statusline('%S', { maxwidth = 5 }))
5080    end)
5081
5082    it('does not include internal mapping keys in %S', function()
5083      command('set showcmd')
5084      command(
5085        [[nnoremap <F3> <Cmd>let g:showcmd_statusline = nvim_eval_statusline('AAA%SBBB', {}).str<CR>]]
5086      )
5087      exec_lua([[vim.api.nvim_feedkeys(vim.keycode('<F3>'), 'xt', false)]])
5088      eq('AAABBB', api.nvim_get_var('showcmd_statusline'))
5089      command('nunmap <F3>')
5090
5091      exec_lua [[
5092        vim.g.showcmd_statusline = ''
5093        vim.keymap.set('n', '<F3>', function()
5094          vim.g.showcmd_statusline = vim.api.nvim_eval_statusline('AAA%SBBB', {}).str
5095        end)
5096        vim.api.nvim_feedkeys(vim.keycode('<F3>'), 'xt', false)
5097      ]]
5098      eq('AAABBB', api.nvim_get_var('showcmd_statusline'))
5099    end)
5100
5101    describe('highlight parsing', function()
5102      it('works', function()
5103        eq(
5104          {
5105            str = 'TextWithWarningHighlightTextWithUserHighlight',
5106            width = 45,
5107            highlights = {
5108              { start = 0, group = 'WarningMsg', groups = { 'StatusLine', 'WarningMsg' } },
5109              { start = 24, group = 'User1', groups = { 'StatusLine', 'User1' } },
5110            },
5111          },
5112          api.nvim_eval_statusline(
5113            '%#WarningMsg#TextWithWarningHighlight%1*TextWithUserHighlight',
5114            { highlights = true }
5115          )
5116        )
5117      end)
5118
5119      it('works with no highlight', function()
5120        eq({
5121          str = 'TextWithNoHighlight',
5122          width = 19,
5123          highlights = {
5124            { start = 0, group = 'StatusLine', groups = { 'StatusLine' } },
5125          },
5126        }, api.nvim_eval_statusline('TextWithNoHighlight', { highlights = true }))
5127      end)
5128
5129      it('works with inactive statusline', function()
5130        command('split')
5131        eq(
5132          {
5133            str = 'TextWithNoHighlightTextWithWarningHighlight',
5134            width = 43,
5135            highlights = {
5136              { start = 0, group = 'StatusLineNC', groups = { 'StatusLineNC' } },
5137              { start = 19, group = 'WarningMsg', groups = { 'StatusLineNC', 'WarningMsg' } },
5138            },
5139          },
5140          api.nvim_eval_statusline(
5141            'TextWithNoHighlight%#WarningMsg#TextWithWarningHighlight',
5142            { winid = api.nvim_list_wins()[2], highlights = true }
5143          )
5144        )
5145      end)
5146
5147      it('works with tabline', function()
5148        eq(
5149          {
5150            str = 'TextWithNoHighlightTextWithWarningHighlight',
5151            width = 43,
5152            highlights = {
5153              { start = 0, group = 'TabLineFill', groups = { 'TabLineFill' } },
5154              { start = 19, group = 'WarningMsg', groups = { 'TabLineFill', 'WarningMsg' } },
5155            },
5156          },
5157          api.nvim_eval_statusline(
5158            'TextWithNoHighlight%#WarningMsg#TextWithWarningHighlight',
5159            { use_tabline = true, highlights = true }
5160          )
5161        )
5162      end)
5163
5164      it('works with winbar', function()
5165        eq(
5166          {
5167            str = 'TextWithNoHighlightTextWithWarningHighlight',
5168            width = 43,
5169            highlights = {
5170              { start = 0, group = 'WinBar', groups = { 'WinBar' } },
5171              { start = 19, group = 'WarningMsg', groups = { 'WinBar', 'WarningMsg' } },
5172            },
5173          },
5174          api.nvim_eval_statusline(
5175            'TextWithNoHighlight%#WarningMsg#TextWithWarningHighlight',
5176            { use_winbar = true, highlights = true }
5177          )
5178        )
5179      end)
5180
5181      it('works with statuscolumn', function()
5182        exec([[
5183          let &stc='%C%s%=%l '
5184          " should not use "stl" from 'fillchars'
5185          set cul nu nuw=3 scl=yes:2 fdc=2 fillchars=stl:#
5186          call setline(1, repeat(['aaaaa'], 5))
5187          let g:ns = nvim_create_namespace('')
5188          call sign_define('a', {'text':'aa', 'texthl':'IncSearch', 'numhl':'Normal'})
5189          call sign_place(2, 1, 'a', bufnr(), {'lnum':4})
5190          call nvim_buf_set_extmark(0, g:ns, 3, 1, { 'sign_text':'bb', 'sign_hl_group':'ErrorMsg' })
5191          1,5fold | 1,5 fold | foldopen!
5192          norm 4G
5193        ]])
5194        eq({
5195          str = '││bbaa 4 ',
5196          width = 9,
5197          highlights = {
5198            { group = 'CursorLineFold', start = 0, groups = { 'CursorLineFold' } },
5199            { group = 'Normal', start = 6, groups = { 'Normal' } },
5200            { group = 'ErrorMsg', start = 6, groups = { 'CursorLineSign', 'ErrorMsg' } },
5201            { group = 'IncSearch', start = 8, groups = { 'CursorLineSign', 'IncSearch' } },
5202            { group = 'Normal', start = 10, groups = { 'Normal' } },
5203          },
5204        }, api.nvim_eval_statusline(
5205          '%C%s%=%l ',
5206          { use_statuscol_lnum = 4, highlights = true }
5207        ))
5208        eq(
5209          {
5210            str = '       3 ',
5211            width = 9,
5212            highlights = {
5213              { group = 'LineNr', start = 0, groups = { 'LineNr' } },
5214              { group = 'ErrorMsg', start = 8, groups = { 'LineNr', 'ErrorMsg' } },
5215            },
5216          },
5217          api.nvim_eval_statusline('%l%#ErrorMsg# ', { use_statuscol_lnum = 3, highlights = true })
5218        )
5219      end)
5220
5221      it('no memory leak with click functions', function()
5222        api.nvim_eval_statusline('%@ClickFunc@StatusLineStringWithClickFunc%T', {})
5223        eq({
5224          str = 'StatusLineStringWithClickFunc',
5225          width = 29,
5226        }, api.nvim_eval_statusline('%@ClickFunc@StatusLineStringWithClickFunc%T', {}))
5227      end)
5228    end)
5229  end)
5230
5231  describe('nvim_parse_cmd', function()
5232    it('works', function()
5233      eq({
5234        cmd = 'echo',
5235        args = { 'foo' },
5236        bang = false,
5237        addr = 'none',
5238        magic = {
5239          file = false,
5240          bar = false,
5241        },
5242        nargs = '*',
5243        nextcmd = '',
5244        mods = {
5245          browse = false,
5246          confirm = false,
5247          emsg_silent = false,
5248          filter = {
5249            pattern = '',
5250            force = false,
5251          },
5252          hide = false,
5253          horizontal = false,
5254          keepalt = false,
5255          keepjumps = false,
5256          keepmarks = false,
5257          keeppatterns = false,
5258          lockmarks = false,
5259          noautocmd = false,
5260          noswapfile = false,
5261          sandbox = false,
5262          silent = false,
5263          split = '',
5264          tab = -1,
5265          unsilent = false,
5266          verbose = -1,
5267          vertical = false,
5268        },
5269      }, api.nvim_parse_cmd('echo foo', {}))
5270    end)
5271    it('works with ranges', function()
5272      eq({
5273        cmd = 'substitute',
5274        args = { '/math.random/math.max/' },
5275        bang = false,
5276        range = { 4, 6 },
5277        addr = 'line',
5278        magic = {
5279          file = false,
5280          bar = false,
5281        },
5282        nargs = '*',
5283        nextcmd = '',
5284        mods = {
5285          browse = false,
5286          confirm = false,
5287          emsg_silent = false,
5288          filter = {
5289            pattern = '',
5290            force = false,
5291          },
5292          hide = false,
5293          horizontal = false,
5294          keepalt = false,
5295          keepjumps = false,
5296          keepmarks = false,
5297          keeppatterns = false,
5298          lockmarks = false,
5299          noautocmd = false,
5300          noswapfile = false,
5301          sandbox = false,
5302          silent = false,
5303          split = '',
5304          tab = -1,
5305          unsilent = false,
5306          verbose = -1,
5307          vertical = false,
5308        },
5309      }, api.nvim_parse_cmd('4,6s/math.random/math.max/', {}))
5310    end)
5311    it('works with count', function()
5312      eq({
5313        cmd = 'buffer',
5314        args = {},
5315        bang = false,
5316        range = { 1 },
5317        count = 1,
5318        addr = 'buf',
5319        magic = {
5320          file = false,
5321          bar = true,
5322        },
5323        nargs = '*',
5324        nextcmd = '',
5325        mods = {
5326          browse = false,
5327          confirm = false,
5328          emsg_silent = false,
5329          filter = {
5330            pattern = '',
5331            force = false,
5332          },
5333          hide = false,
5334          horizontal = false,
5335          keepalt = false,
5336          keepjumps = false,
5337          keepmarks = false,
5338          keeppatterns = false,
5339          lockmarks = false,
5340          noautocmd = false,
5341          noswapfile = false,
5342          sandbox = false,
5343          silent = false,
5344          split = '',
5345          tab = -1,
5346          unsilent = false,
5347          verbose = -1,
5348          vertical = false,
5349        },
5350      }, api.nvim_parse_cmd('buffer 1', {}))
5351    end)
5352    it('works with register', function()
5353      eq({
5354        cmd = 'put',
5355        args = {},
5356        bang = false,
5357        reg = '+',
5358        addr = 'line',
5359        magic = {
5360          file = false,
5361          bar = true,
5362        },
5363        nargs = '0',
5364        nextcmd = '',
5365        mods = {
5366          browse = false,
5367          confirm = false,
5368          emsg_silent = false,
5369          filter = {
5370            pattern = '',
5371            force = false,
5372          },
5373          hide = false,
5374          horizontal = false,
5375          keepalt = false,
5376          keepjumps = false,
5377          keepmarks = false,
5378          keeppatterns = false,
5379          lockmarks = false,
5380          noautocmd = false,
5381          noswapfile = false,
5382          sandbox = false,
5383          silent = false,
5384          split = '',
5385          tab = -1,
5386          unsilent = false,
5387          verbose = -1,
5388          vertical = false,
5389        },
5390      }, api.nvim_parse_cmd('put +', {}))
5391      eq({
5392        cmd = 'put',
5393        args = {},
5394        bang = false,
5395        reg = '',
5396        addr = 'line',
5397        magic = {
5398          file = false,
5399          bar = true,
5400        },
5401        nargs = '0',
5402        nextcmd = '',
5403        mods = {
5404          browse = false,
5405          confirm = false,
5406          emsg_silent = false,
5407          filter = {
5408            pattern = '',
5409            force = false,
5410          },
5411          hide = false,
5412          horizontal = false,
5413          keepalt = false,
5414          keepjumps = false,
5415          keepmarks = false,
5416          keeppatterns = false,
5417          lockmarks = false,
5418          noautocmd = false,
5419          noswapfile = false,
5420          sandbox = false,
5421          silent = false,
5422          split = '',
5423          tab = -1,
5424          unsilent = false,
5425          verbose = -1,
5426          vertical = false,
5427        },
5428      }, api.nvim_parse_cmd('put', {}))
5429    end)
5430    it('works with range, count and register', function()
5431      eq({
5432        cmd = 'delete',
5433        args = {},
5434        bang = false,
5435        range = { 3, 7 },
5436        count = 7,
5437        reg = '*',
5438        addr = 'line',
5439        magic = {
5440          file = false,
5441          bar = true,
5442        },
5443        nargs = '0',
5444        nextcmd = '',
5445        mods = {
5446          browse = false,
5447          confirm = false,
5448          emsg_silent = false,
5449          filter = {
5450            pattern = '',
5451            force = false,
5452          },
5453          hide = false,
5454          horizontal = false,
5455          keepalt = false,
5456          keepjumps = false,
5457          keepmarks = false,
5458          keeppatterns = false,
5459          lockmarks = false,
5460          noautocmd = false,
5461          noswapfile = false,
5462          sandbox = false,
5463          silent = false,
5464          split = '',
5465          tab = -1,
5466          unsilent = false,
5467          verbose = -1,
5468          vertical = false,
5469        },
5470      }, api.nvim_parse_cmd('1,3delete * 5', {}))
5471    end)
5472    it('works with bang', function()
5473      eq({
5474        cmd = 'write',
5475        args = {},
5476        bang = true,
5477        addr = 'line',
5478        magic = {
5479          file = true,
5480          bar = true,
5481        },
5482        nargs = '?',
5483        nextcmd = '',
5484        mods = {
5485          browse = false,
5486          confirm = false,
5487          emsg_silent = false,
5488          filter = {
5489            pattern = '',
5490            force = false,
5491          },
5492          hide = false,
5493          horizontal = false,
5494          keepalt = false,
5495          keepjumps = false,
5496          keepmarks = false,
5497          keeppatterns = false,
5498          lockmarks = false,
5499          noautocmd = false,
5500          noswapfile = false,
5501          sandbox = false,
5502          silent = false,
5503          split = '',
5504          tab = -1,
5505          unsilent = false,
5506          verbose = -1,
5507          vertical = false,
5508        },
5509      }, api.nvim_parse_cmd('w!', {}))
5510    end)
5511    it('works with modifiers', function()
5512      eq(
5513        {
5514          cmd = 'split',
5515          args = { 'foo.txt' },
5516          bang = false,
5517          addr = '?',
5518          magic = {
5519            file = true,
5520            bar = true,
5521          },
5522          nargs = '?',
5523          nextcmd = '',
5524          mods = {
5525            browse = false,
5526            confirm = false,
5527            emsg_silent = true,
5528            filter = {
5529              pattern = 'foo',
5530              force = false,
5531            },
5532            hide = false,
5533            horizontal = true,
5534            keepalt = false,
5535            keepjumps = false,
5536            keepmarks = false,
5537            keeppatterns = false,
5538            lockmarks = false,
5539            noautocmd = false,
5540            noswapfile = false,
5541            sandbox = false,
5542            silent = true,
5543            split = 'topleft',
5544            tab = 1,
5545            unsilent = false,
5546            verbose = 15,
5547            vertical = false,
5548          },
5549        },
5550        api.nvim_parse_cmd(
5551          '15verbose silent! horizontal topleft tab filter /foo/ split foo.txt',
5552          {}
5553        )
5554      )
5555      eq(
5556        {
5557          cmd = 'split',
5558          args = { 'foo.txt' },
5559          bang = false,
5560          addr = '?',
5561          magic = {
5562            file = true,
5563            bar = true,
5564          },
5565          nargs = '?',
5566          nextcmd = '',
5567          mods = {
5568            browse = false,
5569            confirm = true,
5570            emsg_silent = false,
5571            filter = {
5572              pattern = 'foo',
5573              force = true,
5574            },
5575            hide = false,
5576            horizontal = false,
5577            keepalt = false,
5578            keepjumps = false,
5579            keepmarks = false,
5580            keeppatterns = false,
5581            lockmarks = false,
5582            noautocmd = false,
5583            noswapfile = false,
5584            sandbox = false,
5585            silent = false,
5586            split = 'botright',
5587            tab = 0,
5588            unsilent = true,
5589            verbose = 0,
5590            vertical = false,
5591          },
5592        },
5593        api.nvim_parse_cmd(
5594          '0verbose unsilent botright 0tab confirm filter! /foo/ split foo.txt',
5595          {}
5596        )
5597      )
5598    end)
5599    it('works with user commands', function()
5600      command('command -bang -nargs=+ -range -addr=lines MyCommand echo foo')
5601      eq({
5602        cmd = 'MyCommand',
5603        args = { 'test', 'it' },
5604        bang = true,
5605        range = { 4, 6 },
5606        addr = 'line',
5607        magic = {
5608          file = false,
5609          bar = false,
5610        },
5611        nargs = '+',
5612        nextcmd = '',
5613        mods = {
5614          browse = false,
5615          confirm = false,
5616          emsg_silent = false,
5617          filter = {
5618            pattern = '',
5619            force = false,
5620          },
5621          hide = false,
5622          horizontal = false,
5623          keepalt = false,
5624          keepjumps = false,
5625          keepmarks = false,
5626          keeppatterns = false,
5627          lockmarks = false,
5628          noautocmd = false,
5629          noswapfile = false,
5630          sandbox = false,
5631          silent = false,
5632          split = '',
5633          tab = -1,
5634          unsilent = false,
5635          verbose = -1,
5636          vertical = false,
5637        },
5638      }, api.nvim_parse_cmd('4,6MyCommand! test it', {}))
5639    end)
5640    it('sets nextcmd for bar-separated commands', function()
5641      eq({
5642        cmd = 'argadd',
5643        args = { 'a.txt' },
5644        bang = false,
5645        addr = 'arg',
5646        magic = {
5647          file = true,
5648          bar = true,
5649        },
5650        nargs = '*',
5651        nextcmd = 'argadd b.txt',
5652        mods = {
5653          browse = false,
5654          confirm = false,
5655          emsg_silent = false,
5656          filter = {
5657            pattern = '',
5658            force = false,
5659          },
5660          hide = false,
5661          horizontal = false,
5662          keepalt = false,
5663          keepjumps = false,
5664          keepmarks = false,
5665          keeppatterns = false,
5666          lockmarks = false,
5667          noautocmd = false,
5668          noswapfile = false,
5669          sandbox = false,
5670          silent = false,
5671          split = '',
5672          tab = -1,
5673          unsilent = false,
5674          verbose = -1,
5675          vertical = false,
5676        },
5677      }, api.nvim_parse_cmd('argadd a.txt | argadd b.txt', {}))
5678    end)
5679    it('sets nextcmd after expr-arg commands #36029', function()
5680      local result = api.nvim_parse_cmd('exe "ls"|edit foo', {})
5681      eq({ '"ls"' }, result.args)
5682      eq('execute', result.cmd)
5683      eq('edit foo', result.nextcmd)
5684    end)
5685    it('parses expr-arg commands with invalid expr #38689', function()
5686      for _, arg in ipairs({ '&', '[', '{', '"', "'" }) do
5687        local result = api.nvim_parse_cmd('echo ' .. arg, {})
5688        eq({ arg }, result.args)
5689        eq('echo', result.cmd)
5690        eq('', result.nextcmd)
5691      end
5692      -- v:errmsg shouldn't be set
5693      eq('', api.nvim_get_vvar('errmsg'))
5694    end)
5695    it('parses :map commands with space in RHS', function()
5696      eq({
5697        addr = 'none',
5698        args = { 'a', 'b  c' },
5699        bang = false,
5700        cmd = 'map',
5701        magic = {
5702          bar = true,
5703          file = false,
5704        },
5705        mods = {
5706          browse = false,
5707          confirm = false,
5708          emsg_silent = false,
5709          filter = {
5710            force = false,
5711            pattern = '',
5712          },
5713          hide = false,
5714          horizontal = false,
5715          keepalt = false,
5716          keepjumps = false,
5717          keepmarks = false,
5718          keeppatterns = false,
5719          lockmarks = false,
5720          noautocmd = false,
5721          noswapfile = false,
5722          sandbox = false,
5723          silent = false,
5724          split = '',
5725          tab = -1,
5726          unsilent = false,
5727          verbose = -1,
5728          vertical = false,
5729        },
5730        nargs = '*',
5731        nextcmd = '',
5732      }, api.nvim_parse_cmd('map a b  c', {}))
5733    end)
5734    it('works for nargs=1', function()
5735      command('command -nargs=1 MyCommand echo <q-args>')
5736      eq({
5737        cmd = 'MyCommand',
5738        args = { 'test it' },
5739        bang = false,
5740        addr = 'none',
5741        magic = {
5742          file = false,
5743          bar = false,
5744        },
5745        nargs = '1',
5746        nextcmd = '',
5747        mods = {
5748          browse = false,
5749          confirm = false,
5750          emsg_silent = false,
5751          filter = {
5752            pattern = '',
5753            force = false,
5754          },
5755          hide = false,
5756          horizontal = false,
5757          keepalt = false,
5758          keepjumps = false,
5759          keepmarks = false,
5760          keeppatterns = false,
5761          lockmarks = false,
5762          noautocmd = false,
5763          noswapfile = false,
5764          sandbox = false,
5765          silent = false,
5766          split = '',
5767          tab = -1,
5768          unsilent = false,
5769          verbose = -1,
5770          vertical = false,
5771        },
5772      }, api.nvim_parse_cmd('MyCommand test it', {}))
5773    end)
5774    it('validates command', function()
5775      eq('Parsing command-line', pcall_err(api.nvim_parse_cmd, '', {}))
5776      eq('Parsing command-line', pcall_err(api.nvim_parse_cmd, '" foo', {}))
5777      eq(
5778        'Parsing command-line: E492: Not an editor command: Fubar',
5779        pcall_err(api.nvim_parse_cmd, 'Fubar', {})
5780      )
5781      command('command! Fubar echo foo')
5782      eq('Parsing command-line: E477: No ! allowed', pcall_err(api.nvim_parse_cmd, 'Fubar!', {}))
5783      eq(
5784        'Parsing command-line: E481: No range allowed',
5785        pcall_err(api.nvim_parse_cmd, '4,6Fubar', {})
5786      )
5787      command('command! Foobar echo foo')
5788      eq(
5789        'Parsing command-line: E464: Ambiguous use of user-defined command',
5790        pcall_err(api.nvim_parse_cmd, 'F', {})
5791      )
5792    end)
5793    it('does not interfere with printing line in Ex mode #19400', function()
5794      local screen = Screen.new(60, 12)
5795      insert([[
5796        foo
5797        bar]])
5798      feed('1q:1')
5799      screen:expect({ any = vim.pesc('{1::}1^') })
5800      eq('Parsing command-line', pcall_err(api.nvim_parse_cmd, '', {}))
5801      -- Executing the line still auto-prints it.
5802      feed('<CR>')
5803      screen:expect({ any = vim.pesc('" foo') })
5804    end)
5805    it('does not move cursor or change search history/pattern #19878 #19890', function()
5806      api.nvim_buf_set_lines(0, 0, -1, true, { 'foo', 'bar', 'foo', 'bar' })
5807      eq({ 1, 0 }, api.nvim_win_get_cursor(0))
5808      eq('', fn.getreg('/'))
5809      eq('', fn.histget('search'))
5810      feed(':') -- call the API in cmdline mode to test whether it changes search history
5811      eq({
5812        cmd = 'normal',
5813        args = { 'x' },
5814        bang = true,
5815        range = { 3, 4 },
5816        addr = 'line',
5817        magic = {
5818          file = false,
5819          bar = false,
5820        },
5821        nargs = '+',
5822        nextcmd = '',
5823        mods = {
5824          browse = false,
5825          confirm = false,
5826          emsg_silent = false,
5827          filter = {
5828            pattern = '',
5829            force = false,
5830          },
5831          hide = false,
5832          horizontal = false,
5833          keepalt = false,
5834          keepjumps = false,
5835          keepmarks = false,
5836          keeppatterns = false,
5837          lockmarks = false,
5838          noautocmd = false,
5839          noswapfile = false,
5840          sandbox = false,
5841          silent = false,
5842          split = '',
5843          tab = -1,
5844          unsilent = false,
5845          verbose = -1,
5846          vertical = false,
5847        },
5848      }, api.nvim_parse_cmd('+2;/bar/normal! x', {}))
5849      eq({ 1, 0 }, api.nvim_win_get_cursor(0))
5850      eq('', fn.getreg('/'))
5851      eq('', fn.histget('search'))
5852    end)
5853    it('result can be used directly by nvim_cmd #20051', function()
5854      eq('foo', api.nvim_cmd(api.nvim_parse_cmd('echo "foo"', {}), { output = true }))
5855      api.nvim_cmd(api.nvim_parse_cmd('set cursorline', {}), {})
5856      eq(true, api.nvim_get_option_value('cursorline', {}))
5857      -- Roundtrip on :bdelete which does not accept "range". #33394
5858      api.nvim_cmd(api.nvim_parse_cmd('bdelete', {}), {})
5859    end)
5860    it('no side-effects (error messages) in pcall() #20339', function()
5861      eq(
5862        { false, 'Parsing command-line: E16: Invalid range' },
5863        exec_lua([=[return {pcall(vim.api.nvim_parse_cmd, "'<,'>n", {})}]=])
5864      )
5865      eq('', eval('v:errmsg'))
5866    end)
5867    it('does not include count field when no count provided for builtin commands', function()
5868      local result = api.nvim_parse_cmd('copen', {})
5869      eq(nil, result.count)
5870      api.nvim_cmd(result, {})
5871      eq(10, api.nvim_win_get_height(0))
5872      result = api.nvim_parse_cmd('copen 5', {})
5873      eq(5, result.count)
5874    end)
5875    it('parses range-only cmdline (:1)', function()
5876      insert [[
5877        line1
5878        line2
5879        line3
5880        line4
5881      ]]
5882      api.nvim_win_set_cursor(0, { 4, 4 })
5883      local res = api.nvim_parse_cmd('1', {})
5884      eq({
5885        addr = 'line',
5886        args = {},
5887        bang = false,
5888        cmd = '',
5889        magic = {
5890          bar = false,
5891          file = false,
5892        },
5893        mods = {
5894          browse = false,
5895          confirm = false,
5896          emsg_silent = false,
5897          filter = {
5898            force = false,
5899            pattern = '',
5900          },
5901          hide = false,
5902          horizontal = false,
5903          keepalt = false,
5904          keepjumps = false,
5905          keepmarks = false,
5906          keeppatterns = false,
5907          lockmarks = false,
5908          noautocmd = false,
5909          noswapfile = false,
5910          sandbox = false,
5911          silent = false,
5912          split = '',
5913          tab = -1,
5914          unsilent = false,
5915          verbose = -1,
5916          vertical = false,
5917        },
5918        nargs = '0',
5919        nextcmd = '',
5920        range = { 1 },
5921      }, res)
5922      api.nvim_cmd(res, {})
5923      eq(1, api.nvim_win_get_cursor(0)[1])
5924      feed('VG:')
5925      n.poke_eventloop()
5926      res = api.nvim_parse_cmd("'<,'>", {})
5927      eq({ 1, 5 }, res.range)
5928    end)
5929    it('parses modifier-only cmdline (:aboveleft)', function()
5930      local res = api.nvim_parse_cmd('aboveleft', {})
5931      eq('', res.cmd)
5932      eq('aboveleft', res.mods.split)
5933      eq('none', res.addr)
5934    end)
5935  end)
5936
5937  describe('nvim_cmd', function()
5938    it('works', function()
5939      api.nvim_cmd({ cmd = 'set', args = { 'cursorline' } }, {})
5940      eq(true, api.nvim_get_option_value('cursorline', {}))
5941    end)
5942
5943    it('validation', function()
5944      eq("Invalid 'cmd': expected non-empty String", pcall_err(api.nvim_cmd, { cmd = '' }, {}))
5945      eq("Invalid 'cmd': expected String, got Array", pcall_err(api.nvim_cmd, { cmd = {} }, {}))
5946      eq(
5947        "Invalid 'args': expected Array, got Boolean",
5948        pcall_err(api.nvim_cmd, { cmd = 'set', args = true }, {})
5949      )
5950      eq(
5951        'Invalid command arg: expected non-whitespace',
5952        pcall_err(api.nvim_cmd, { cmd = 'set', args = { '  ' } }, {})
5953      )
5954      eq(
5955        'Invalid command arg: expected valid type, got Array',
5956        pcall_err(api.nvim_cmd, { cmd = 'set', args = { {} } }, {})
5957      )
5958      eq('Wrong number of arguments', pcall_err(api.nvim_cmd, { cmd = 'aboveleft', args = {} }, {}))
5959      eq(
5960        'Command cannot accept bang: print',
5961        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, bang = true }, {})
5962      )
5963
5964      eq(
5965        'Command cannot accept range: set',
5966        pcall_err(api.nvim_cmd, { cmd = 'set', args = {}, range = { 1 } }, {})
5967      )
5968      eq(
5969        "Invalid 'range': expected Array, got Boolean",
5970        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, range = true }, {})
5971      )
5972      eq(
5973        "Invalid 'range': expected <=2 elements",
5974        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, range = { 1, 2, 3, 4 } }, {})
5975      )
5976      eq(
5977        'Invalid range element: expected non-negative Integer',
5978        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, range = { -1 } }, {})
5979      )
5980      eq(
5981        "Invalid 'range'",
5982        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, range = { 99 } }, {})
5983      )
5984      -- Not ":1x" (:xit).
5985      eq(
5986        'Wrong number of arguments',
5987        pcall_err(api.nvim_cmd, { cmd = '', range = { 1 }, args = { 'x' } }, {})
5988      )
5989
5990      eq(
5991        'Command cannot accept count: set',
5992        pcall_err(api.nvim_cmd, { cmd = 'set', args = {}, count = 1 }, {})
5993      )
5994      eq(
5995        "Invalid 'count': expected Integer, got Boolean",
5996        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, count = true }, {})
5997      )
5998      eq(
5999        "Invalid 'count': expected non-negative Integer",
6000        pcall_err(api.nvim_cmd, { cmd = 'print', args = {}, count = -1 }, {})
6001      )
6002
6003      eq(
6004        'Command cannot accept register: set',
6005        pcall_err(api.nvim_cmd, { cmd = 'set', args = {}, reg = 'x' }, {})
6006      )
6007      eq(
6008        'Cannot use register "=',
6009        pcall_err(api.nvim_cmd, { cmd = 'put', args = {}, reg = '=' }, {})
6010      )
6011      eq(
6012        "Invalid 'reg': expected single character, got xx",
6013        pcall_err(api.nvim_cmd, { cmd = 'put', args = {}, reg = 'xx' }, {})
6014      )
6015
6016      -- #20681
6017      eq('Invalid command: "win_getid"', pcall_err(api.nvim_cmd, { cmd = 'win_getid' }, {}))
6018      eq('Invalid command: "echo "hi""', pcall_err(api.nvim_cmd, { cmd = 'echo "hi"' }, {}))
6019      matches('Invalid command: "win_getid"$', pcall_err(exec_lua, [[return vim.cmd.win_getid{}]]))
6020
6021      -- Lua call allows empty {} for dict item.
6022      eq('', exec_lua([[return vim.cmd{ cmd = "set", args = {}, magic = {} }]]))
6023      eq('', exec_lua([[return vim.cmd{ cmd = "set", args = {}, mods = {} }]]))
6024      eq('', api.nvim_cmd({ cmd = 'set', args = {}, magic = {} }, {}))
6025
6026      -- Lua call does not allow non-empty list-like {} for dict item.
6027      matches(
6028        "Invalid 'magic': Expected Dict%-like Lua table$",
6029        pcall_err(exec_lua, [[return vim.cmd{ cmd = "set", args = {}, magic = { 'a' } }]])
6030      )
6031      matches(
6032        "Invalid key: 'bogus'$",
6033        pcall_err(exec_lua, [[return vim.cmd{ cmd = "set", args = {}, magic = { bogus = true } }]])
6034      )
6035      matches(
6036        "Invalid key: 'bogus'$",
6037        pcall_err(exec_lua, [[return vim.cmd{ cmd = "set", args = {}, mods = { bogus = true } }]])
6038      )
6039    end)
6040
6041    it('captures output', function()
6042      eq('foo', api.nvim_cmd({ cmd = 'echo', args = { '"foo"' } }, { output = true }))
6043      -- Returns output in cmdline mode #35321
6044      feed(':')
6045      eq('foo', api.nvim_cmd({ cmd = 'echo', args = { '"foo"' } }, { output = true }))
6046    end)
6047
6048    it('sets correct script context', function()
6049      api.nvim_cmd({ cmd = 'set', args = { 'cursorline' } }, {})
6050      local str = exec_capture([[verbose set cursorline?]])
6051      neq(nil, str:find('cursorline\n\tLast set from API client %(channel id %d+%)'))
6052    end)
6053
6054    it('works with range', function()
6055      insert [[
6056        line1
6057        line2
6058        line3
6059        line4
6060        you didn't expect this
6061        line5
6062        line6
6063      ]]
6064      api.nvim_cmd({ cmd = 'del', range = { 2, 4 } }, {})
6065      expect [[
6066        line1
6067        you didn't expect this
6068        line5
6069        line6
6070      ]]
6071    end)
6072
6073    it('uses the same default range as Ex', function()
6074      api.nvim_buf_set_lines(0, 0, -1, false, { 'a', 'b', 'c' })
6075      api.nvim_win_set_cursor(0, { 2, 0 })
6076      command('command -range -addr=other Other let g:r = [<line1>, <line2>]')
6077      command('command -range=% -addr=other OtherAll let g:r = [<line1>, <line2>]')
6078      for _, name in ipairs({ 'Other', 'OtherAll' }) do
6079        command(name)
6080        local ex = api.nvim_get_var('r')
6081        api.nvim_cmd({ cmd = name }, {})
6082        eq(ex, api.nvim_get_var('r'))
6083      end
6084    end)
6085
6086    it('works with count', function()
6087      insert [[
6088        line1
6089        line2
6090        line3
6091        line4
6092        you didn't expect this
6093        line5
6094        line6
6095      ]]
6096      api.nvim_cmd({ cmd = 'del', range = { 2 }, count = 4 }, {})
6097      expect [[
6098        line1
6099        line5
6100        line6
6101      ]]
6102    end)
6103
6104    it('works with register', function()
6105      insert [[
6106        line1
6107        line2
6108        line3
6109        line4
6110        you didn't expect this
6111        line5
6112        line6
6113      ]]
6114      api.nvim_cmd({ cmd = 'del', range = { 2, 4 }, reg = 'a' }, {})
6115      command('1put a')
6116      expect [[
6117        line1
6118        line2
6119        line3
6120        line4
6121        you didn't expect this
6122        line5
6123        line6
6124      ]]
6125    end)
6126
6127    it('works with bang', function()
6128      api.nvim_create_user_command('Foo', 'echo "<bang>"', { bang = true })
6129      eq('!', api.nvim_cmd({ cmd = 'Foo', bang = true }, { output = true }))
6130      eq('', api.nvim_cmd({ cmd = 'Foo', bang = false }, { output = true }))
6131    end)
6132
6133    it('works with modifiers', function()
6134      -- with silent = true output is still captured
6135      eq(
6136        '1',
6137        api.nvim_cmd(
6138          { cmd = 'echomsg', args = { '1' }, mods = { silent = true } },
6139          { output = true }
6140        )
6141      )
6142      -- but message isn't added to message history
6143      eq('', api.nvim_cmd({ cmd = 'messages' }, { output = true }))
6144
6145      api.nvim_create_user_command('Foo', 'set verbose', {})
6146      eq('  verbose=1', api.nvim_cmd({ cmd = 'Foo', mods = { verbose = 1 } }, { output = true }))
6147
6148      api.nvim_create_user_command('Mods', "echo '<mods>'", {})
6149      eq(
6150        'keepmarks keeppatterns silent 3verbose aboveleft horizontal',
6151        api.nvim_cmd({
6152          cmd = 'Mods',
6153          mods = {
6154            horizontal = true,
6155            keepmarks = true,
6156            keeppatterns = true,
6157            silent = true,
6158            split = 'aboveleft',
6159            verbose = 3,
6160          },
6161        }, { output = true })
6162      )
6163      eq(0, api.nvim_get_option_value('verbose', {}))
6164
6165      command('edit foo.txt | edit bar.txt')
6166      eq(
6167        '  1 #h   "foo.txt"                      line 1',
6168        api.nvim_cmd(
6169          { cmd = 'buffers', mods = { filter = { pattern = 'foo', force = false } } },
6170          { output = true }
6171        )
6172      )
6173      eq(
6174        '  2 %a   "bar.txt"                      line 1',
6175        api.nvim_cmd(
6176          { cmd = 'buffers', mods = { filter = { pattern = 'foo', force = true } } },
6177          { output = true }
6178        )
6179      )
6180
6181      -- with emsg_silent = true error is suppressed
6182      feed([[:lua vim.api.nvim_cmd({ cmd = 'call', mods = { emsg_silent = true } }, {})<CR>]])
6183      eq('', api.nvim_cmd({ cmd = 'messages' }, { output = true }))
6184      -- error from the next command typed is not suppressed #21420
6185      feed(':call<CR><CR>')
6186      eq('E471: Argument required', api.nvim_cmd({ cmd = 'messages' }, { output = true }))
6187
6188      -- "modifier-only" command (e.g. :noautocmd).
6189      eq('', api.nvim_cmd({ cmd = '', mods = { noautocmd = true } }, {}))
6190    end)
6191
6192    it('works with magic.file', function()
6193      exec_lua([[
6194        vim.api.nvim_create_user_command("Foo", function(opts)
6195          vim.api.nvim_echo({{ opts.fargs[1] }}, false, {})
6196        end, { nargs = 1 })
6197      ]])
6198      eq(
6199        t.fix_slashes(assert(uv.cwd())),
6200        api.nvim_cmd(
6201          { cmd = 'Foo', args = { '%:p:h' }, magic = { file = true } },
6202          { output = true }
6203        )
6204      )
6205    end)
6206
6207    it('splits arguments correctly', function()
6208      exec([[
6209        function! FooFunc(...)
6210          echo a:000
6211        endfunction
6212      ]])
6213      api.nvim_create_user_command('Foo', 'call FooFunc(<f-args>)', { nargs = '+' })
6214      eq(
6215        [=[['a quick', 'brown fox', 'jumps over the', 'lazy dog']]=],
6216        api.nvim_cmd(
6217          { cmd = 'Foo', args = { 'a quick', 'brown fox', 'jumps over the', 'lazy dog' } },
6218          { output = true }
6219        )
6220      )
6221      eq(
6222        [=[['test \ \\ \"""\', 'more\ tests\"  ']]=],
6223        api.nvim_cmd(
6224          { cmd = 'Foo', args = { [[test \ \\ \"""\]], [[more\ tests\"  ]] } },
6225          { output = true }
6226        )
6227      )
6228    end)
6229
6230    it('splits arguments correctly for Lua callback', function()
6231      api.nvim_exec_lua(
6232        [[
6233        local function FooFunc(opts)
6234          vim.print(opts.fargs)
6235        end
6236
6237        vim.api.nvim_create_user_command("Foo", FooFunc, { nargs = '+', bar = true })
6238      ]],
6239        {}
6240      )
6241      eq(
6242        [[{ "a quick", "brown fox", "jumps over the", "lazy dog" }]],
6243        api.nvim_cmd(
6244          { cmd = 'Foo', args = { 'a quick', 'brown fox', 'jumps over the', 'lazy dog' } },
6245          { output = true }
6246        )
6247      )
6248      eq(
6249        [[{ 'test \\ \\\\ \\"""\\', 'more\\ tests\\"  ' }]],
6250        api.nvim_cmd(
6251          { cmd = 'Foo', args = { [[test \ \\ \"""\]], [[more\ tests\"  ]] } },
6252          { output = true }
6253        )
6254      )
6255      eq([[{ " a|b" }]], api.nvim_cmd({ cmd = 'Foo', args = { ' a|b' } }, { output = true }))
6256    end)
6257
6258    it('keeps leading white space of the first argument', function()
6259      api.nvim_buf_set_lines(0, 0, -1, false, { 'ab' })
6260      api.nvim_cmd({ cmd = 'normal', args = { ' x' } }, {})
6261      eq({ 'a' }, api.nvim_buf_get_lines(0, 0, -1, false))
6262    end)
6263
6264    it('works with buffer names', function()
6265      command('edit foo.txt | edit bar.txt')
6266      api.nvim_cmd({ cmd = 'buffer', args = { 'foo.txt' } }, {})
6267      eq('foo.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6268      api.nvim_cmd({ cmd = 'buffer', args = { 'bar.txt' } }, {})
6269      eq('bar.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6270    end)
6271
6272    it('triggers CmdUndefined event if command is not found', function()
6273      api.nvim_exec_lua(
6274        [[
6275        vim.api.nvim_create_autocmd("CmdUndefined",
6276                                    { pattern = "Foo",
6277                                      callback = function()
6278                                        vim.api.nvim_create_user_command("Foo", "echo 'foo'", {})
6279                                      end
6280                                    })
6281      ]],
6282        {}
6283      )
6284      eq('foo', api.nvim_cmd({ cmd = 'Foo' }, { output = true }))
6285    end)
6286
6287    it('errors if command is not implemented', function()
6288      eq('Command not implemented: winpos', pcall_err(api.nvim_cmd, { cmd = 'winpos' }, {}))
6289    end)
6290
6291    it('works with empty arguments list', function()
6292      api.nvim_cmd({ cmd = 'update' }, {})
6293      api.nvim_cmd({ cmd = 'buffer', count = 0 }, {})
6294    end)
6295
6296    it("doesn't suppress errors when used in keymapping", function()
6297      api.nvim_exec_lua(
6298        [[
6299        vim.keymap.set("n", "[l",
6300                       function() vim.api.nvim_cmd({ cmd = "echo", args = {"foo"} }, {}) end)
6301      ]],
6302        {}
6303      )
6304      feed('[l')
6305      neq(nil, string.find(eval('v:errmsg'), 'E5108:'))
6306    end)
6307
6308    it('handles 0 range #19608', function()
6309      api.nvim_buf_set_lines(0, 0, -1, false, { 'aa' })
6310      api.nvim_cmd({ cmd = 'delete', range = { 0 } }, {})
6311      command('undo')
6312      eq({ 'aa' }, api.nvim_buf_get_lines(0, 0, 1, false))
6313      assert_alive()
6314    end)
6315
6316    it('supports filename expansion', function()
6317      api.nvim_cmd({ cmd = 'argadd', args = { '%:p:h:t', '%:p:h:t' } }, {})
6318      local arg = fn.expand('%:p:h:t')
6319      eq({ arg, arg }, fn.argv())
6320    end)
6321
6322    it(":make command works when argument count isn't 1 #19696", function()
6323      command('set makeprg=echo')
6324      command('set shellquote=')
6325      matches('^:!echo ', api.nvim_cmd({ cmd = 'make' }, { output = true }))
6326      assert_alive()
6327      matches(
6328        '^:!echo foo bar',
6329        api.nvim_cmd({ cmd = 'make', args = { 'foo', 'bar' } }, { output = true })
6330      )
6331      assert_alive()
6332      local arg_pesc = pesc(fn.expand('%:p:h:t'))
6333      matches(
6334        ('^:!echo %s %s'):format(arg_pesc, arg_pesc),
6335        api.nvim_cmd({ cmd = 'make', args = { '%:p:h:t', '%:p:h:t' } }, { output = true })
6336      )
6337      assert_alive()
6338    end)
6339
6340    it("doesn't display messages when output=true", function()
6341      local screen = Screen.new(40, 6)
6342      api.nvim_cmd({ cmd = 'echo', args = { [['hello']] } }, { output = true })
6343      screen:expect {
6344        grid = [[
6345        ^                                        |
6346        {1:~                                       }|*4
6347                                                |
6348      ]],
6349      }
6350      exec([[
6351        func Print()
6352          call nvim_cmd(#{cmd: 'echo', args: ['"hello"']}, #{output: v:true})
6353        endfunc
6354      ]])
6355      feed([[:echon 1 | call Print() | echon 5<CR>]])
6356      screen:expect {
6357        grid = [[
6358        ^                                        |
6359        {1:~                                       }|*4
6360        15                                      |
6361      ]],
6362      }
6363    end)
6364
6365    it('works with non-String args', function()
6366      eq('2', api.nvim_cmd({ cmd = 'echo', args = { 2 } }, { output = true }))
6367      eq('1', api.nvim_cmd({ cmd = 'echo', args = { true } }, { output = true }))
6368    end)
6369
6370    describe('first argument as count', function()
6371      it('works', function()
6372        command('vsplit | enew')
6373        api.nvim_cmd({ cmd = 'bdelete', args = { api.nvim_get_current_buf() } }, {})
6374        eq(1, api.nvim_get_current_buf())
6375      end)
6376
6377      it('works with :sleep using milliseconds', function()
6378        local start = uv.now()
6379        api.nvim_cmd({ cmd = 'sleep', args = { '100m' } }, {})
6380        ok(uv.now() - start <= 300)
6381      end)
6382    end)
6383
6384    it(':call with unknown function does not crash #26289', function()
6385      eq(
6386        'Vim:E117: Unknown function: UnknownFunc',
6387        pcall_err(api.nvim_cmd, { cmd = 'call', args = { 'UnknownFunc()' } }, {})
6388      )
6389    end)
6390
6391    it(':throw does not crash #24556', function()
6392      eq('42', pcall_err(api.nvim_cmd, { cmd = 'throw', args = { '42' } }, {}))
6393    end)
6394
6395    it('can use :return #24556', function()
6396      exec([[
6397        func Foo()
6398          let g:pos = 'before'
6399          call nvim_cmd({'cmd': 'return', 'args': ['[1, 2, 3]']}, {})
6400          let g:pos = 'after'
6401        endfunc
6402        let g:result = Foo()
6403      ]])
6404      eq('before', api.nvim_get_var('pos'))
6405      eq({ 1, 2, 3 }, api.nvim_get_var('result'))
6406    end)
6407
6408    it('errors properly when command too recursive #27210', function()
6409      exec_lua([[
6410        _G.success = false
6411        vim.api.nvim_create_user_command('Test', function()
6412          vim.api.nvim_cmd({ cmd = 'Test' }, {})
6413          _G.success = true
6414        end, {})
6415      ]])
6416      pcall_err(command, 'Test')
6417      assert_alive()
6418      eq(false, exec_lua('return _G.success'))
6419    end)
6420
6421    it('handles +flags correctly', function()
6422      -- Write a file for testing +flags
6423      t.write_file('testfile', 'Line 1\nLine 2\nLine 3', false, false)
6424
6425      -- Test + command (go to the last line)
6426      local result = exec_lua([[
6427        local parsed = vim.api.nvim_parse_cmd('edit + testfile', {})
6428        vim.cmd(parsed)
6429        return { vim.fn.line('.'), parsed.args, parsed.cmd }
6430      ]])
6431      eq({ 3, { '+ testfile' }, 'edit' }, result)
6432
6433      -- Test +{num} command (go to line number)
6434      result = exec_lua([[
6435        vim.cmd(vim.api.nvim_parse_cmd('edit +1 testfile', {}))
6436        return vim.fn.line('.')
6437      ]])
6438      eq(1, result)
6439
6440      -- Test +/{pattern} command (go to line with pattern)
6441      result = exec_lua([[
6442        local parsed = vim.api.nvim_parse_cmd('edit +/Line\\ 2 testfile', {})
6443        vim.cmd(parsed)
6444        return {vim.fn.line('.'), parsed.args}
6445      ]])
6446      eq({ 2, { '+/Line\\ 2 testfile' } }, result)
6447
6448      -- Test +{command} command (execute a command after opening the file)
6449      result = exec_lua([[
6450        vim.cmd(vim.api.nvim_parse_cmd('edit +set\\ nomodifiable testfile', {}))
6451        return vim.bo.modifiable
6452      ]])
6453      eq(false, result)
6454
6455      -- Test ++ flags structure in parsed command
6456      result = exec_lua([[
6457        local parsed = vim.api.nvim_parse_cmd('botright edit + testfile', {})
6458        vim.cmd(parsed)
6459        return { vim.fn.line('.'), parsed.cmd, parsed.args, parsed.mods.split }
6460      ]])
6461      eq({ 3, 'edit', { '+ testfile' }, 'botright' }, result)
6462
6463      -- Clean up
6464      os.remove('testfile')
6465    end)
6466
6467    it('handles various ++ flags correctly', function()
6468      -- Test ++ff flag
6469      local result = exec_lua [[
6470        local parsed = vim.api.nvim_parse_cmd('edit ++ff=mac test_ff_mac.txt', {})
6471        vim.cmd(parsed)
6472        return parsed.args
6473      ]]
6474      eq({ '++ff=mac test_ff_mac.txt' }, result)
6475      eq('mac', api.nvim_get_option_value('fileformat', {}))
6476      eq('test_ff_mac.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6477
6478      exec_lua [[
6479        vim.cmd(vim.api.nvim_parse_cmd('edit ++fileformat=unix test_ff_unix.txt', {}))
6480      ]]
6481      eq('unix', api.nvim_get_option_value('fileformat', {}))
6482      eq('test_ff_unix.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6483
6484      -- Test ++enc flag
6485      exec_lua [[
6486        vim.cmd(vim.api.nvim_parse_cmd('edit ++enc=utf-32 test_enc.txt', {}))
6487      ]]
6488      eq('ucs-4', api.nvim_get_option_value('fileencoding', {}))
6489      eq('test_enc.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6490
6491      -- Test ++bin and ++nobin flags
6492      exec_lua [[
6493        vim.cmd(vim.api.nvim_parse_cmd('edit ++bin test_bin.txt', {}))
6494      ]]
6495      eq(true, api.nvim_get_option_value('binary', {}))
6496      eq('test_bin.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6497
6498      exec_lua [[
6499        vim.cmd(vim.api.nvim_parse_cmd('edit ++nobin test_nobin.txt', {}))
6500      ]]
6501      eq(false, api.nvim_get_option_value('binary', {}))
6502      eq('test_nobin.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6503
6504      -- Test multiple flags together
6505      exec_lua [[
6506        vim.cmd(vim.api.nvim_parse_cmd('edit ++ff=mac ++enc=utf-32 ++bin test_multi.txt', {}))
6507      ]]
6508      eq(true, api.nvim_get_option_value('binary', {}))
6509      eq('mac', api.nvim_get_option_value('fileformat', {}))
6510      eq('ucs-4', api.nvim_get_option_value('fileencoding', {}))
6511      eq('test_multi.txt', fn.fnamemodify(api.nvim_buf_get_name(0), ':t'))
6512    end)
6513
6514    it('handles invalid and incorrect ++ flags gracefully', function()
6515      -- Test invalid ++ff flag
6516      local result = exec_lua [[
6517        local cmd = vim.api.nvim_parse_cmd('edit ++ff=invalid test_invalid_ff.txt', {})
6518        local _, err = pcall(vim.cmd, cmd)
6519        return err
6520      ]]
6521      matches("Invalid argument : '%+%+ff=invalid'$", result)
6522
6523      -- Test incorrect ++ syntax
6524      result = exec_lua [[
6525        local cmd = vim.api.nvim_parse_cmd('edit ++unknown=test_unknown.txt', {})
6526        local _, err = pcall(vim.cmd, cmd)
6527        return err
6528      ]]
6529      matches("Invalid argument : '%+%+unknown=test_unknown.txt'$", result)
6530
6531      -- Test invalid ++bin flag
6532      result = exec_lua [[
6533        local cmd = vim.api.nvim_parse_cmd('edit ++binabc test_invalid_bin.txt', {})
6534        local _, err = pcall(vim.cmd, cmd)
6535        return err
6536      ]]
6537      matches("Invalid argument : '%+%+binabc test_invalid_bin.txt'$", result)
6538    end)
6539
6540    it('handles ++p for creating parent directory', function()
6541      exec_lua [[
6542        vim.cmd('edit flags_dir/test_create.txt')
6543        vim.cmd(vim.api.nvim_parse_cmd('write! ++p', {}))
6544      ]]
6545      eq(true, fn.isdirectory('flags_dir') == 1)
6546      fn.delete('flags_dir', 'rf')
6547    end)
6548
6549    it('tests editing files with bad utf8 sequences', function()
6550      -- Write a file with bad utf8 sequences
6551      local file = io.open('Xfile', 'wb')
6552      file:write('[\255][\192][\226\137\240][\194\194]')
6553      file:close()
6554
6555      exec_lua([[
6556        vim.cmd(vim.api.nvim_parse_cmd('edit! ++enc=utf8 Xfile', {}))
6557      ]])
6558      eq('[?][?][???][??]', api.nvim_get_current_line())
6559
6560      exec_lua([[
6561        vim.cmd(vim.api.nvim_parse_cmd('edit! ++enc=utf8 ++bad=_ Xfile', {}))
6562      ]])
6563      eq('[_][_][___][__]', api.nvim_get_current_line())
6564
6565      exec_lua([[
6566        vim.cmd(vim.api.nvim_parse_cmd('edit! ++enc=utf8 ++bad=drop Xfile', {}))
6567      ]])
6568      eq('[][][][]', api.nvim_get_current_line())
6569
6570      exec_lua([[
6571        vim.cmd(vim.api.nvim_parse_cmd('edit! ++enc=utf8 ++bad=keep Xfile', {}))
6572      ]])
6573      eq('[\255][\192][\226\137\240][\194\194]', api.nvim_get_current_line())
6574
6575      local result = exec_lua([[
6576        local _, err = pcall(vim.cmd, vim.api.nvim_parse_cmd('edit ++enc=utf8 ++bad=foo Xfile', {}))
6577        return err
6578      ]])
6579      matches("Invalid argument : '%+%+bad=foo'$", result)
6580      -- Clean up
6581      os.remove('Xfile')
6582    end)
6583    it('interprets numeric args as count for count-only commands', function()
6584      api.nvim_cmd({ cmd = 'copen', args = { 8 } }, {})
6585      local height1 = api.nvim_win_get_height(0)
6586      command('cclose')
6587      api.nvim_cmd({ cmd = 'copen', count = 8 }, {})
6588      local height2 = api.nvim_win_get_height(0)
6589      command('cclose')
6590      eq(height1, height2)
6591
6592      exec_lua 'vim.cmd.copen(5)'
6593      height2 = api.nvim_win_get_height(0)
6594      command('cclose')
6595      eq(5, height2)
6596
6597      -- should reject both count and numeric arg
6598      eq(
6599        "Cannot specify both 'count' and numeric argument",
6600        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { 5 }, count = 10 }, {})
6601      )
6602    end)
6603    it('handles string numeric arguments correctly', function()
6604      -- Valid string numbers should work
6605      api.nvim_cmd({ cmd = 'copen', args = { '6' } }, {})
6606      eq(6, api.nvim_win_get_height(0))
6607      command('cclose')
6608      -- Invalid strings should be rejected
6609      eq(
6610        'Wrong number of arguments',
6611        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { 'abc' } }, {})
6612      )
6613      -- Partial numbers should be rejected
6614      eq(
6615        'Wrong number of arguments',
6616        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { '8abc' } }, {})
6617      )
6618      -- Empty string should be rejected
6619      eq(
6620        'Invalid command arg: expected non-whitespace',
6621        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { '' } }, {})
6622      )
6623      -- Negative string numbers should be rejected
6624      eq(
6625        'Wrong number of arguments',
6626        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { '-5' } }, {})
6627      )
6628      -- Leading/trailing spaces should be rejected
6629      eq(
6630        'Wrong number of arguments',
6631        pcall_err(api.nvim_cmd, { cmd = 'copen', args = { ' 5 ' } }, {})
6632      )
6633    end)
6634  end)
6635
6636  it('nvim__redraw', function()
6637    local screen = Screen.new(60, 5)
6638    eq('at least one action required', pcall_err(api.nvim__redraw, {}))
6639    eq('at least one action required', pcall_err(api.nvim__redraw, { buf = 0 }))
6640    eq('at least one action required', pcall_err(api.nvim__redraw, { win = 0 }))
6641    eq("cannot use both 'buf' and 'win'", pcall_err(api.nvim__redraw, { buf = 0, win = 0 }))
6642    local win = api.nvim_get_current_win()
6643    -- Can move cursor to recently opened window and window is flushed #28868
6644    feed(':echo getchar()<CR>')
6645    local newwin = api.nvim_open_win(0, false, {
6646      relative = 'editor',
6647      width = 1,
6648      height = 1,
6649      row = 1,
6650      col = 10,
6651    })
6652    api.nvim__redraw({ win = newwin, cursor = true })
6653    screen:expect({
6654      grid = [[
6655                                                                    |
6656        {1:~         }{4:^ }{1:                                                 }|
6657        {1:~                                                           }|*2
6658        :echo getchar()                                             |
6659      ]],
6660    })
6661    fn.setline(1, 'foobar')
6662    command('vnew')
6663    fn.setline(1, 'foobaz')
6664    -- Can flush pending screen updates
6665    api.nvim__redraw({ flush = true })
6666    screen:expect({
6667      grid = [[
6668        foobaz                        │foobar                       |
6669        {1:~         }{4:^f}{1:                   }│{1:~                            }|
6670        {1:~                             }│{1:~                            }|
6671        {3:[No Name] [+]                  }{2:[No Name] [+]                }|
6672        :echo getchar()                                             |
6673      ]],
6674    })
6675    api.nvim_win_close(newwin, true)
6676    -- Can update the grid cursor position #20793
6677    api.nvim__redraw({ cursor = true })
6678    screen:expect({
6679      grid = [[
6680        ^foobaz                        │foobar                       |
6681        {1:~                             }│{1:~                            }|*2
6682        {3:[No Name] [+]                  }{2:[No Name] [+]                }|
6683        :echo getchar()                                             |
6684      ]],
6685    })
6686    -- Also in non-current window
6687    api.nvim__redraw({ cursor = true, win = win })
6688    screen:expect({
6689      grid = [[
6690        foobaz                        │^foobar                       |
6691        {1:~                             }│{1:~                            }|*2
6692        {3:[No Name] [+]                  }{2:[No Name] [+]                }|
6693        :echo getchar()                                             |
6694      ]],
6695    })
6696    -- Can update the 'statusline' in a single window
6697    api.nvim_set_option_value('statusline', 'statusline1', { win = 0 })
6698    api.nvim_set_option_value('statusline', 'statusline2', { win = win })
6699    api.nvim__redraw({ cursor = true, win = 0, statusline = true })
6700    screen:expect({
6701      grid = [[
6702        ^foobaz                        │foobar                       |
6703        {1:~                             }│{1:~                            }|*2
6704        {3:statusline1                    }{2:[No Name] [+]                }|
6705        :echo getchar()                                             |
6706      ]],
6707    })
6708    api.nvim__redraw({ win = win, statusline = true })
6709    screen:expect({
6710      grid = [[
6711        ^foobaz                        │foobar                       |
6712        {1:~                             }│{1:~                            }|*2
6713        {3:statusline1                    }{2:statusline2                  }|
6714        :echo getchar()                                             |
6715      ]],
6716    })
6717    -- Can update the 'statusline' in all windows
6718    api.nvim_set_option_value('statusline', '', { win = win })
6719    api.nvim_set_option_value('statusline', 'statusline3', {})
6720    api.nvim__redraw({ statusline = true })
6721    screen:expect({
6722      grid = [[
6723        ^foobaz                        │foobar                       |
6724        {1:~                             }│{1:~                            }|*2
6725        {3:statusline3                    }{2:statusline3                  }|
6726        :echo getchar()                                             |
6727      ]],
6728    })
6729    -- Can update the 'statuscolumn'
6730    api.nvim_set_option_value('statuscolumn', 'statuscolumn', { win = win })
6731    api.nvim__redraw({ statuscolumn = true })
6732    screen:expect({
6733      grid = [[
6734        ^foobaz                        │{8:statuscolumn}foobar           |
6735        {1:~                             }│{1:~                            }|*2
6736        {3:statusline3                    }{2:statusline3                  }|
6737        :echo getchar()                                             |
6738      ]],
6739    })
6740    -- Can update the 'winbar'
6741    api.nvim_set_option_value('winbar', 'winbar', { win = 0 })
6742    api.nvim__redraw({ win = 0, winbar = true })
6743    screen:expect({
6744      grid = [[
6745        {5:^winbar                        }│{8:statuscolumn}foobar           |
6746        foobaz                        │{1:~                            }|
6747        {1:~                             }│{1:~                            }|
6748        {3:statusline3                    }{2:statusline3                  }|
6749        :echo getchar()                                             |
6750      ]],
6751    })
6752    -- Can update the 'tabline'
6753    api.nvim_set_option_value('showtabline', 2, {})
6754    api.nvim_set_option_value('tabline', 'tabline', {})
6755    api.nvim__redraw({ tabline = true })
6756    screen:expect({
6757      grid = [[
6758        {2:^tabline                                                     }|
6759        {5:winbar                        }│{8:statuscolumn}foobar           |
6760        foobaz                        │{1:~                            }|
6761        {3:statusline3                    }{2:statusline3                  }|
6762        :echo getchar()                                             |
6763      ]],
6764    })
6765    -- Can update multiple status widgets
6766    api.nvim_set_option_value('tabline', 'tabline2', {})
6767    api.nvim_set_option_value('statusline', 'statusline4', {})
6768    api.nvim__redraw({ statusline = true, tabline = true })
6769    screen:expect({
6770      grid = [[
6771        {2:^tabline2                                                    }|
6772        {5:winbar                        }│{8:statuscolumn}foobar           |
6773        foobaz                        │{1:~                            }|
6774        {3:statusline4                    }{2:statusline4                  }|
6775        :echo getchar()                                             |
6776      ]],
6777    })
6778    -- Can update all status widgets
6779    api.nvim_set_option_value('tabline', 'tabline3', {})
6780    api.nvim_set_option_value('statusline', 'statusline5', {})
6781    api.nvim_set_option_value('statuscolumn', 'statuscolumn2', {})
6782    api.nvim_set_option_value('winbar', 'winbar2', {})
6783    api.nvim__redraw({ statuscolumn = true, statusline = true, tabline = true, winbar = true })
6784    screen:expect({
6785      grid = [[
6786        {2:^tabline3                                                    }|
6787        {5:winbar2                       }│{5:winbar2                      }|
6788        {8:statuscolumn2}foobaz           │{8:statuscolumn}foobar           |
6789        {3:statusline5                    }{2:statusline5                  }|
6790        :echo getchar()                                             |
6791      ]],
6792    })
6793    -- Can update status widget for a specific window
6794    feed('<CR><CR>')
6795    command('let g:status=0')
6796    api.nvim_set_option_value('statusline', '%{%g:status%}', { win = 0 })
6797    command('vsplit')
6798    screen:expect({
6799      grid = [[
6800        {2:tabline3                                                    }|
6801        {5:winbar2             }│{5:winbar2            }│{5:winbar2            }|
6802        {8:statuscolumn2}^foobaz │{8:statuscolumn2}foobaz│{8:statuscolumn}foobar |
6803        {3:0                    }{2:0                   statusline5        }|
6804        13                                                          |
6805      ]],
6806    })
6807    command('let g:status=1')
6808    api.nvim__redraw({ win = 0, statusline = true })
6809    screen:expect({
6810      grid = [[
6811        {2:tabline3                                                    }|
6812        {5:winbar2             }│{5:winbar2            }│{5:winbar2            }|
6813        {8:statuscolumn2}^foobaz │{8:statuscolumn2}foobaz│{8:statuscolumn}foobar |
6814        {3:1                    }{2:0                   statusline5        }|
6815        13                                                          |
6816      ]],
6817    })
6818    -- Can update status widget for a specific buffer
6819    command('let g:status=2')
6820    api.nvim__redraw({ buf = 0, statusline = true })
6821    screen:expect({
6822      grid = [[
6823        {2:tabline3                                                    }|
6824        {5:winbar2             }│{5:winbar2            }│{5:winbar2            }|
6825        {8:statuscolumn2}^foobaz │{8:statuscolumn2}foobaz│{8:statuscolumn}foobar |
6826        {3:2                    }{2:2                   statusline5        }|
6827        13                                                          |
6828      ]],
6829    })
6830    -- valid = true does not draw any lines on its own
6831    exec_lua([[
6832      _G.lines = 0
6833      ns = vim.api.nvim_create_namespace('')
6834      vim.api.nvim_set_decoration_provider(ns, {
6835        on_win = function()
6836          if _G.do_win then
6837            vim.api.nvim_buf_set_extmark(0, ns, 0, 0, { hl_group = 'IncSearch', end_col = 6 })
6838          end
6839        end,
6840        on_line = function()
6841          _G.lines = _G.lines + 1
6842        end,
6843      })
6844    ]])
6845    local lines = exec_lua('return lines')
6846    api.nvim__redraw({ buf = 0, valid = true, flush = true })
6847    eq(lines, exec_lua('return _G.lines'))
6848    -- valid = false does
6849    api.nvim__redraw({ buf = 0, valid = false, flush = true })
6850    neq(lines, exec_lua('return _G.lines'))
6851    -- valid = true does redraw lines if affected by on_win callback
6852    exec_lua('_G.do_win = true')
6853    api.nvim__redraw({ buf = 0, valid = true, flush = true })
6854    screen:expect({
6855      grid = [[
6856        {2:tabline3                                                    }|
6857        {5:winbar2             }│{5:winbar2            }│{5:winbar2            }|
6858        {8:statuscolumn2}{2:^foobaz} │{8:statuscolumn2}{2:foobaz}│{8:statuscolumn}foobar |
6859        {3:2                    }{2:2                   statusline5        }|
6860        13                                                          |
6861      ]],
6862    })
6863  end)
6864
6865  it('nvim__redraw range parameter', function()
6866    Screen.new(10, 5)
6867    fn.setline(1, fn.range(4))
6868
6869    exec_lua([[
6870      _G.lines_list = {}
6871      ns = vim.api.nvim_create_namespace('')
6872      vim.api.nvim_set_decoration_provider(ns, {
6873        on_win = function()
6874        end,
6875        on_line = function(_, _, _, line)
6876          table.insert(_G.lines_list, line)
6877        end,
6878      })
6879      function _G.get_lines()
6880        local lines = _G.lines_list
6881        _G.lines_list = {}
6882        return lines
6883      end
6884    ]])
6885
6886    api.nvim__redraw({ flush = true, valid = false })
6887    exec_lua('_G.get_lines()')
6888
6889    local actual_lines = {}
6890    local function test(range)
6891      api.nvim__redraw({ win = 0, range = range })
6892      table.insert(actual_lines, exec_lua('return _G.get_lines()'))
6893    end
6894
6895    test({ 0, -1 })
6896    test({ 2, 2 ^ 31 })
6897    test({ 2, 2 ^ 32 })
6898    test({ 2 ^ 31 - 1, 2 })
6899    test({ 2 ^ 32 - 1, 2 })
6900
6901    local expected_lines = {
6902      { 0, 1, 2, 3 },
6903      { 2, 3 },
6904      { 2, 3 },
6905      {},
6906      {},
6907    }
6908    eq(expected_lines, actual_lines)
6909
6910    n.assert_alive()
6911  end)
6912
6913  it('nvim__redraw updates topline', function()
6914    local screen = Screen.new(40, 8)
6915    fn.setline(1, fn.range(100))
6916    feed(':call getchar()<CR>')
6917    fn.cursor(50, 1)
6918    screen:expect([[
6919      0                                       |
6920      1                                       |
6921      2                                       |
6922      3                                       |
6923      4                                       |
6924      5                                       |
6925      6                                       |
6926      ^:call getchar()                         |
6927    ]])
6928    api.nvim__redraw({ flush = true })
6929    screen:expect([[
6930      46                                      |
6931      47                                      |
6932      48                                      |
6933      49                                      |
6934      50                                      |
6935      51                                      |
6936      52                                      |
6937      ^:call getchar()                         |
6938    ]])
6939  end)
6940end)