robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
194.2 KiB5193 linesraw
1-- TUI acceptance tests.
2-- Uses :terminal as a way to send keys and assert screen state.
3--
4-- "bracketed paste" terminal feature:
5-- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Bracketed-Paste-Mode
6
7local t = require('test.testutil')
8local n = require('test.functional.testnvim')()
9local Screen = require('test.functional.ui.screen')
10local tt = require('test.functional.testterm')
11
12local describe, it, before_each, after_each, pending, finally =
13  t.describe, t.it, t.before_each, t.after_each, t.pending, t.finally
14local eq = t.eq
15local feed_data = tt.feed_data
16local clear = n.clear
17local command = n.command
18local exec = n.exec
19local exec_lua = n.exec_lua
20local testprg = n.testprg
21local retry = t.retry
22local nvim_prog = n.nvim_prog
23local nvim_set = n.nvim_set
24local ok = t.ok
25local read_file = t.read_file
26local fn = n.fn
27local api = n.api
28local is_os = t.is_os
29local new_pipename = n.new_pipename
30local set_session = n.set_session
31local write_file = t.write_file
32local eval = n.eval
33local assert_log = t.assert_log
34
35local testlog = 'Xtest-tui-log'
36
37-- Using this to have 'notermguicolors' in Nvim instances without starting a timer
38-- that causes delay on exit with ASAN/TSAN.
39local env_notermguicolors = { COLORTERM = 'xterm-256color' }
40
41describe('TUI', function()
42  it('exit status 1 and error message with server --listen error #34365', function()
43    clear()
44    local addr_in_use = api.nvim_get_vvar('servername')
45    local screen = tt.setup_child_nvim(
46      { '--listen', addr_in_use, '-u', 'NONE', '-i', 'NONE' },
47      { extra_rows = 10, cols = 60, env = { NVIM_LOG_FILE = testlog } }
48    )
49    finally(function()
50      os.remove(testlog)
51    end)
52
53    screen:expect({ any = vim.pesc('[Process exited 1]') })
54
55    -- When the address is very long, the error message may be only partly visible.
56    if #addr_in_use <= 600 then
57      screen:expect({
58        any = vim.pesc(
59          ('%s: Failed to --listen: address already in use:'):format(
60            fn.fnamemodify(nvim_prog, ':t')
61          )
62        ),
63        unchanged = true,
64      })
65    end
66
67    -- Always assert the log for the error message.
68    assert_log(
69      vim.pesc('Failed to start server: address already in use: ' .. addr_in_use),
70      testlog,
71      100
72    )
73  end)
74
75  it('suspending does not crash or hang', function()
76    clear()
77    local screen = tt.setup_child_nvim({ '--clean' }, { env = env_notermguicolors })
78    local s0 = [[
79      ^                                                  |
80      ~                                                 |*3
81      {2:[No Name]                       0,0-1          All}|
82                                                        |
83      {5:-- TERMINAL --}                                    |
84    ]]
85    screen:expect(s0)
86    feed_data(':')
87    local s1 = [[
88                                                        |
89      ~                                                 |*3
90      {2:[No Name]                       0,0-1          All}|
91      :^                                                 |
92      {5:-- TERMINAL --}                                    |
93    ]]
94    screen:expect(s1)
95    feed_data('suspend\r')
96    if is_os('win') then -- no-op on Windows
97      screen:expect([[
98        ^                                                  |
99        ~                                                 |*3
100        {2:[No Name]                       0,0-1          All}|
101        :suspend                                          |
102        {5:-- TERMINAL --}                                    |
103      ]])
104    else -- resuming works on other platforms
105      screen:expect([[
106                                                          |*5
107        ^[Process suspended]                               |
108        {5:-- TERMINAL --}                                    |
109      ]])
110      n.feed('<Space>')
111      screen:expect(s0)
112    end
113    feed_data(':')
114    screen:expect(s1)
115  end)
116
117  it('jobstart child writing to CON does not leak to screen', function()
118    -- A child job that writes to CON must not leak onto the TUI screen. The
119    -- embedded server AttachConsole()'s the parent terminal (so server io.stdout
120    -- e.g. SIXEL works), but jobs must get their own (windowless) console so
121    -- writes to CON go nowhere visible.
122    t.skip(not is_os('win'), 'N/A Windows only')
123    n.clear()
124    finally(function()
125      n.check_close()
126    end)
127
128    local screen = tt.setup_child_nvim({
129      '--clean',
130      '--cmd',
131      'colorscheme vim',
132      '--cmd',
133      nvim_set .. ' laststatus=2 background=dark',
134    }, { env = env_notermguicolors })
135    tt.override_screen_expect_for_conpty(screen)
136
137    feed_data('iZZZSENTINEL')
138
139    -- Leave insert mode and run a job that writes directly to CON, blocking
140    -- until it finishes. The CON output must not appear anywhere on screen.
141    feed_data("\027\027:call jobwait([jobstart(['cmd', '/c', 'echo LEAKEDXYZ > CON'])])\013")
142
143    screen:expect([[
144      ZZZSENTINE^L                                       |
145      {100:~                                                 }|*3
146      {3:[No Name] [+]                                     }|
147                                                        |
148      {5:-- TERMINAL --}                                    |
149    ]])
150  end)
151end)
152
153describe('TUI :detach', function()
154  local child_server, screen
155
156  local function setup_detach_child(opts)
157    opts = opts or {}
158    n.clear()
159    finally(function()
160      n.check_close()
161    end)
162
163    child_server = new_pipename()
164    screen = tt.setup_child_nvim({
165      '--listen',
166      child_server,
167      '-u',
168      'NONE',
169      '-i',
170      'NONE',
171      '--cmd',
172      'colorscheme vim',
173      '--cmd',
174      nvim_set .. ' laststatus=2 background=dark',
175    }, { env = env_notermguicolors, cols = opts.cols })
176    tt.override_screen_expect_for_conpty(screen)
177    -- The child's `--listen` socket is created asynchronously wrt its PTY output.
178    t.retry(nil, 2000, function()
179      assert(vim.uv.fs_stat(child_server))
180    end)
181  end
182
183  it('does not stop server', function()
184    setup_detach_child()
185
186    tt.feed_data('iHello, World')
187    screen:expect([[
188      Hello, World^                                      |
189      {100:~                                                 }|*3
190      {3:[No Name] [+]                                     }|
191      {5:-- INSERT --}                                      |
192      {5:-- TERMINAL --}                                    |
193    ]])
194
195    local child_session = n.connect(child_server)
196    finally(function()
197      -- Avoid a dangling process after :detach.
198      child_session:request('nvim_command', 'qall!')
199    end)
200    local status, child_uis = child_session:request('nvim_list_uis')
201    assert(status)
202    eq(1, #child_uis)
203
204    eq(
205      { false, { 0, 'Vim(detach):E16: Invalid range' } },
206      { child_session:request('nvim_command', '2detach') }
207    )
208    eq(
209      { false, { 0, 'Vim(detach):E488: Trailing characters: foo: detach foo' } },
210      { child_session:request('nvim_command', 'detach foo') }
211    )
212
213    tt.feed_data('\027\027:detach\013')
214    -- Note: "Process exited" message is misleading; tt.setup_child_nvim() sees the foreground
215    -- process (client) exited, and doesn't know the server is still running?
216    screen:expect {
217      any = [[Process exited 0]],
218    }
219
220    child_uis --[[@type any[] ]] = ({ child_session:request('nvim_list_uis') })[2]
221    eq(0, #child_uis)
222
223    -- NOTE: The tt.setup_child_nvim() screen just wraps :terminal, it's not connected to the child.
224    -- To use it again, we need to detach the old one.
225    screen:detach()
226
227    -- Edit some text on the headless server.
228    status = (child_session:request('nvim_input', 'ddiWe did it, pooky.<Esc><Esc>'))
229    assert(status)
230
231    -- Test reattach by connecting a new TUI.
232    local screen_reattached = tt.setup_child_nvim({
233      '--remote-ui',
234      '--server',
235      child_server,
236    }, { env = env_notermguicolors })
237
238    screen_reattached:expect([[
239      We did it, pooky^.                                 |
240      {100:~                                                 }|*3
241      {3:[No Name] [+]                                     }|
242                                                        |
243      {5:-- TERMINAL --}                                    |
244    ]])
245  end)
246
247  it('detach! keeps the UI attached but survives client disconnect', function()
248    -- Wide enough that the confirmation message doesn't trigger a |hit-enter| prompt.
249    setup_detach_child({ cols = 80 })
250    -- Capture the client (foreground TUI) job so we can kill it below.
251    local term_job = n.api.nvim_buf_get_var(0, 'terminal_job_id')
252
253    -- Wait for the child server to come up (its socket to exist), then connect.
254    local child_session ---@type test.Session
255    retry(nil, nil, function()
256      child_session = n.connect(child_server)
257    end)
258    finally(function()
259      -- Stop the (surviving) server so it doesn't dangle.
260      pcall(function()
261        n.connect(child_server):request('nvim_command', 'qall!')
262      end)
263    end)
264
265    feed_data('\027\027:detach!\013')
266    screen:expect({ any = vim.pesc('Nvim will continue running') })
267
268    -- Unlike ":detach", the UI is still attached.
269    eq(1, #({ child_session:request('nvim_list_uis') })[2])
270
271    -- Simulate the host terminal disconnecting: SIGKILL the client so it can't shut down cleanly.
272    -- On Windows this also exercises the console hand-off in rpc_close_event().
273    n.exec_lua(function(pid)
274      vim.uv.kill(pid, 'sigkill')
275    end, n.fn.jobpid(term_job))
276
277    retry(nil, 4000, function()
278      eq(2, ({ child_session:request('nvim_eval', '1+1') })[2])
279    end)
280  end)
281
282  it('% detaches other UIs', function()
283    setup_detach_child()
284    finally(function()
285      pcall(function()
286        local s = n.connect(child_server)
287        s:request('nvim_command', 'qall!')
288      end)
289    end)
290
291    tt.feed_data('iHello from detach!')
292    screen:expect({ any = vim.pesc('Hello from detach!^') })
293    tt.feed_data('\027')
294
295    local child_session = n.connect(child_server)
296    local _, uis_before = child_session:request('nvim_list_uis')
297    eq(1, #uis_before)
298    local tui_chan_id = uis_before[1].chan
299
300    -- :%detach with only 1 UI is a no-op.
301    tt.feed_data(':%detach\013')
302    screen:expect({ any = vim.pesc('No other UIs are attached') })
303    local _, uis_noop = child_session:request('nvim_list_uis')
304    eq(1, #uis_noop)
305
306    child_session:request('nvim_ui_attach', 50, 7, {})
307    local _, uis_attached = child_session:request('nvim_list_uis')
308    eq(2, #uis_attached)
309
310    -- Send the command in two steps, to avoid "Screen test succeeded immediately" warning.
311    tt.feed_data(':%detach')
312    screen:expect({ any = vim.pesc(':%detach^') })
313    tt.feed_data('\013')
314    screen:expect([[
315      Hello from detach^!                                |
316      {100:~                                                 }|*3
317      {3:[No Name] [+]                                     }|
318                                                        |
319      {5:-- TERMINAL --}                                    |
320    ]])
321
322    local verify_session = n.connect(child_server)
323    local _, uis_after = verify_session:request('nvim_list_uis')
324    eq(1, #uis_after)
325    eq(tui_chan_id, uis_after[1].chan)
326  end)
327
328  it('% detaches the original UI when invoked from a later UI', function()
329    setup_detach_child()
330    finally(function()
331      pcall(function()
332        local s = n.connect(child_server)
333        s:request('nvim_command', 'qall!')
334      end)
335    end)
336
337    screen:expect({ any = vim.pesc('[No Name]') })
338    local child_session = n.connect(child_server)
339    child_session:request('nvim_ui_attach', 50, 7, {})
340    local _, uis_before = child_session:request('nvim_list_uis')
341    eq(2, #uis_before)
342
343    eq({ true, vim.NIL }, { child_session:request('nvim_command', '%detach') })
344    screen:expect({ any = [[Process exited 0]] })
345
346    local status, uis_after = child_session:request('nvim_list_uis')
347    ok(status)
348    eq(1, #uis_after)
349  end)
350end)
351
352describe('TUI :restart', function()
353  before_each(n.clear)
354  after_each(n.check_close)
355
356  --- Asserts that the server at `addr` has (or has not) restarted since `starttime`.
357  ---@param starttime integer v:starttime of the server before restart
358  ---@param sess table Session
359  ---@param addr string
360  ---@return integer starttime
361  ---@return table session
362  local function assert_restarted(starttime, sess, addr)
363    sess:close()
364    local new_starttime
365    -- Retry: old server may still be alive (connect succeeds but yields stale starttime),
366    -- or on Windows the --listen address is restored async.
367    retry(nil, 5000, function()
368      local candidate = n.connect(addr)
369      local status, t = candidate:request('nvim_eval', 'v:starttime')
370      if not status then
371        candidate:close()
372        error(type(t) == 'table' and t[2] or t)
373      end
374      if t <= starttime then
375        candidate:close()
376      end
377      ok(t > starttime, ('v:starttime (%d) > old starttime (%d)'):format(t, starttime), t)
378      sess = candidate
379      new_starttime = t
380    end)
381    return new_starttime, sess
382  end
383
384  it('validation', function()
385    eq('Vim(restart):E481: No range allowed: :1restart!', t.pcall_err(n.command, ':1restart!'))
386  end)
387
388  it(':restart (no bang) restores session, window layout', function()
389    local file = 'Xtest-restart-file'
390    write_file(file, 'foobar')
391    finally(function()
392      os.remove(file)
393    end)
394
395    local server_pipe = new_pipename()
396    local server_session
397    finally(function()
398      if server_session then
399        server_session:close()
400      end
401    end)
402    local screen = tt.setup_child_nvim({
403      '--clean',
404      '--listen',
405      server_pipe,
406      '--cmd',
407      'set notermguicolors laststatus=0 noruler noshowcmd',
408    }, {
409      env = vim.tbl_extend('force', env_notermguicolors, {
410        -- Ignore logs, because assert_restarted may log "connection refused" while it retries.
411        NVIM_LOG_FILE = testlog,
412      }),
413    })
414    finally(function()
415      os.remove(testlog)
416    end)
417
418    feed_data(':edit ' .. file .. '\r')
419    feed_data(':wincmd v\r')
420    screen:expect([[
421      ^foobar                   │foobar                  |
422      ~                        │~                       |
423      ~                        │~                       |
424      ~                        │~                       |
425      ~                        │~                       |
426      :wincmd v                                         |
427      {5:-- TERMINAL --}                                    |
428    ]])
429    server_session = n.connect(server_pipe)
430    local _, starttime = server_session:request('nvim_eval', 'v:starttime')
431    eq({ true, '' }, { server_session:request('nvim_get_vvar', 'this_session') })
432
433    -- :restart
434    feed_data(':restart\r')
435    screen:expect([[
436      ^foobar                   │foobar                  |
437      ~                        │~                       |
438      ~                        │~                       |
439      ~                        │~                       |
440      ~                        │~                       |
441                                                        |
442      {5:-- TERMINAL --}                                    |
443    ]])
444    starttime, server_session = assert_restarted(starttime, server_session, server_pipe)
445    eq({ true, 'restart' }, { server_session:request('nvim_get_vvar', 'startreason') })
446    eq({ true, '' }, { server_session:request('nvim_get_vvar', 'this_session') })
447
448    -- :restart!
449    feed_data(':restart!\r')
450    screen:expect([[
451      ^                                                  |
452      ~                                                 |*4
453                                                        |
454      {5:-- TERMINAL --}                                    |
455    ]])
456    starttime, server_session = assert_restarted(starttime, server_session, server_pipe)
457    eq({ true, 'restart!' }, { server_session:request('nvim_get_vvar', 'startreason') })
458
459    feed_data(':qall!\r')
460    screen:expect({ any = vim.pesc('[Process exited 0]') })
461  end)
462
463  it('ZR', function()
464    -- Just exercise ZR, don't need to test all :restart functionality here.
465    local file = 'Xtest-restart-file'
466    write_file(file, 'foo')
467    finally(function()
468      os.remove(file)
469    end)
470    local server_pipe = new_pipename()
471    local server_session
472    finally(function()
473      if server_session then
474        server_session:close()
475      end
476    end)
477    local screen = tt.setup_child_nvim({
478      '--clean',
479      '--listen',
480      server_pipe,
481      '--cmd',
482      'set notermguicolors',
483    }, {
484      env = vim.tbl_extend('force', env_notermguicolors, {
485        -- Ignore logs, because assert_restarted may log "connection refused" while it retries.
486        NVIM_LOG_FILE = testlog,
487      }),
488    })
489    finally(function()
490      os.remove(testlog)
491    end)
492    feed_data(':edit ' .. file .. '\r')
493    screen:expect({ any = 'foo' })
494
495    server_session = n.connect(server_pipe)
496    local _, starttime = server_session:request('nvim_eval', 'v:starttime')
497
498    -- ZR preserves screen state
499    tt.feed_data('ZR')
500    starttime, server_session = assert_restarted(starttime, server_session, server_pipe)
501    -- Match the full restored screen, to avoid "Screen test succeeded immediately" warning.
502    screen:expect([[
503      ^foo                                               |
504      ~                                                 |*3
505      {2:Xtest-restart-file              1,1            All}|
506                                                        |
507      {5:-- TERMINAL --}                                    |
508    ]])
509
510    -- [1-8]ZR does not preserve screen state
511    tt.feed_data('1ZR')
512    screen:expect({ any = vim.pesc('[No Name]'), none = 'foo' })
513
514    -- ZR on modified buffer fails with E37.
515    tt.feed_data('ifoo\027')
516    tt.feed_data('ZR')
517    screen:expect({ any = 'E37:' })
518    -- Overwrite the message so the next "E37" is a real transition, not a stale immediate match.
519    tt.feed_data(':echo "cleared"\r')
520    screen:expect({ any = 'cleared', none = 'E37:' })
521    tt.feed_data('1ZR')
522    screen:expect({ any = 'E37:' })
523
524    -- [9]ZR discards unsaved changes.
525    tt.feed_data('9ZR')
526    screen:expect({ any = vim.pesc('[No Name]') })
527    starttime, server_session = assert_restarted(starttime, server_session, server_pipe)
528
529    -- The server is now detached and needs to be quit explicitly.
530    tt.feed_data(':qall!\r')
531  end)
532
533  it('works', function()
534    -- Log exit events + v:exitreason.
535    local eventlog = t.tmpname()
536    local initfile = t.tmpname() .. '.lua'
537    local init = [[
538      local f = %q
539      vim.api.nvim_create_autocmd({ 'QuitPre', 'ExitPre', 'VimLeavePre', 'VimLeave' }, {
540        callback = function(ev)
541          vim.fn.writefile({ ('%%s:%%s'):format(ev.event, vim.v.exitreason) }, f, 'a')
542        end,
543      })
544    ]]
545    write_file(initfile, init:format(eventlog))
546    finally(function()
547      os.remove(eventlog)
548      os.remove(initfile)
549    end)
550
551    local function assert_exitreason(expected)
552      local default =
553        'QuitPre:restart!\nExitPre:restart!\nVimLeavePre:restart!\nVimLeave:restart!\n'
554      eq(expected or default, t.read_file(eventlog))
555      os.remove(eventlog)
556    end
557
558    local server_pipe = new_pipename()
559    local screen = tt.setup_child_nvim({
560      '--clean',
561      '-u',
562      initfile,
563      '--listen',
564      server_pipe,
565      '--cmd',
566      'colorscheme vim',
567      '--cmd',
568      'set laststatus=2 background=dark noruler noshowcmd',
569    }, { env = { COLORTERM = 'truecolor' } })
570    screen:set_option('rgb', true)
571    screen:add_extra_attr_ids({
572      [101] = { bold = true, foreground = Screen.colors.WebGreen },
573    })
574
575    -- 'termguicolors' support should be detected properly after :restart!
576    -- The value of has("gui_running") should be 0 before and after :restart!
577    local function assert_termguicolors_and_no_gui_running()
578      tt.feed_data(':echo "&termguicolors: " .. &termguicolors\013')
579      screen:expect({ any = '&termguicolors: 1' })
580      tt.feed_data(':echo "GUI Running: " .. has("gui_running")\013')
581      screen:expect({ any = 'GUI Running: 0' })
582    end
583
584    local s0 = [[
585      ^                                                  |
586      {1:~}{18:                                                 }|*3
587      {3:[No Name]                                         }|
588                                                        |
589      {5:-- TERMINAL --}                                    |
590    ]]
591    screen:expect(s0)
592    assert_termguicolors_and_no_gui_running()
593
594    local server_session = n.connect(server_pipe)
595    local _, server_pid = server_session:request('nvim_call_function', 'getpid', {})
596    local function assert_new_pid()
597      server_session:close()
598      -- On Windows, --listen address is restored async (after old server exits).
599      if is_os('win') then
600        retry(nil, 5000, function()
601          server_session = n.connect(server_pipe)
602        end)
603      else
604        server_session = n.connect(server_pipe)
605      end
606      local _, new_pid = server_session:request('nvim_call_function', 'getpid', {})
607      t.neq(server_pid, new_pid)
608      server_pid = new_pid
609    end
610
611    local s1 = [[
612                                                        |
613      ^Hello1                                            |
614      {1:~}{18:                                                 }|*2
615      {3:[No Name] [+]                                     }|
616                                                        |
617      {5:-- TERMINAL --}                                    |
618    ]]
619
620    tt.feed_data(':set nomodified\013')
621    tt.feed_data(':restart\013')
622    screen:expect(s0)
623    assert_new_pid()
624    assert_exitreason('QuitPre:restart\nExitPre:restart\nVimLeavePre:restart\nVimLeave:restart\n')
625    assert_termguicolors_and_no_gui_running()
626
627    tt.feed_data(':set nomodified\013')
628    -- Command is run on new server.
629    tt.feed_data(":restart! put ='Hello1'\013")
630    screen:expect(s1)
631    assert_new_pid()
632    assert_exitreason()
633    assert_termguicolors_and_no_gui_running()
634
635    -- Complex command following +cmd.
636    tt.feed_data(":restart! +qall! put ='Hello2' | put ='World2'\013")
637    screen:expect([[
638                                                        |
639      Hello2                                            |
640      ^World2                                            |
641      {1:~}{18:                                                 }|
642      {3:[No Name] [+]                                     }|
643                                                        |
644      {5:-- TERMINAL --}                                    |
645    ]])
646    assert_new_pid()
647    assert_exitreason()
648    assert_termguicolors_and_no_gui_running()
649
650    -- Check ":restart!" on an unmodified buffer.
651    tt.feed_data(':set nomodified\013')
652    tt.feed_data(':restart!\013')
653    screen:expect(s0)
654    assert_new_pid()
655    assert_exitreason()
656    assert_termguicolors_and_no_gui_running()
657
658    -- Check ":restart! +qall!" on an unmodified buffer.
659    tt.feed_data(':restart! +qall!\013')
660    screen:expect(s0)
661    assert_new_pid()
662    assert_exitreason()
663    assert_termguicolors_and_no_gui_running()
664
665    -- Check ":restart[!] +echo" cannot restart server.
666    -- Check the full screen state to ensure this doesn't pollute the current UI.
667    for _, cmd in ipairs({ ':restart', ':restart!' }) do
668      tt.feed_data(cmd .. ' +echo\013')
669      screen:expect([[
670                                                          |
671        {1:~}{18:                                                 }|
672        {3:                                                  }|
673        {9:E5201: Restart failed: +cmd did not quit server: e}|
674        {9:cho}                                               |
675        {101:Press ENTER or type command to continue}^           |
676        {5:-- TERMINAL --}                                    |
677      ]])
678      tt.feed_data('\013')
679      -- Return to a distinct state so the next screen:expect() doesn't "succeed immediately".
680      screen:expect({ any = vim.pesc('[No Name]') })
681    end
682
683    tt.feed_data('ithis will be removed\027')
684    screen:expect({ any = vim.pesc('this will be remove^d') })
685
686    -- Check ":confirm restart!" on a modified buffer.
687    tt.feed_data(':confirm restart!\013')
688    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })
689
690    -- Cancel the operation (abandons restart).
691    tt.feed_data('C\013')
692    screen:expect({ any = vim.pesc('[No Name]') })
693    -- Failed/cancelled restarts still fire QuitPre/ExitPre (but not VimLeave[Pre]).
694    assert_exitreason('QuitPre:restart!\nExitPre:restart!\n')
695
696    -- Check :restart! respects 'confirm' option.
697    tt.feed_data(':set confirm\013')
698    tt.feed_data(':restart!\013')
699    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })
700    tt.feed_data('C\013')
701    screen:expect({ any = vim.pesc('[No Name]') })
702    tt.feed_data(':set noconfirm\013')
703    -- Failed/cancelled restarts still fire QuitPre/ExitPre (but not VimLeave[Pre]).
704    assert_exitreason('QuitPre:restart!\nExitPre:restart!\n')
705
706    -- Check ":confirm restart! <cmd>" on a modified buffer.
707    tt.feed_data(":confirm restart! put ='Hello3'\013")
708    screen:expect({ any = vim.pesc('Save changes to "Untitled"?') })
709    tt.feed_data('N\013')
710    screen:expect({ any = '%^Hello3' })
711    assert_new_pid()
712    assert_exitreason()
713    assert_termguicolors_and_no_gui_running()
714
715    -- Check ":confirm restart! +echo" correctly ignores ":confirm"
716    tt.feed_data(':confirm restart! +echo\013')
717    screen:expect({ any = vim.pesc('E5201: Restart failed: +cmd did not quit server') })
718
719    -- Check ":restart[!]" on a modified buffer.
720    tt.feed_data('ithis will be removed\027')
721    for cmd, exitreason in pairs({
722      [':restart'] = 'restart',
723      [':restart!'] = 'restart!',
724    }) do
725      tt.feed_data(cmd)
726      -- Assert the command-line echo so the E37 assertion below doesn't "succeed immediately".
727      screen:expect({ any = vim.pesc(cmd) })
728      tt.feed_data('\013')
729      screen:expect({ any = vim.pesc('E37: No write since last change') })
730      assert_exitreason(('QuitPre:%s\nExitPre:%s\n'):format(exitreason, exitreason))
731    end
732
733    -- Check ":restart! +qall!" on a modified buffer.
734    tt.feed_data('ithis will be removed\027')
735    tt.feed_data(':restart! +qall!\013')
736    screen:expect(s0)
737    assert_new_pid()
738    assert_exitreason()
739    assert_termguicolors_and_no_gui_running()
740
741    if not is_os('win') then
742      -- No --listen conflict when server exit is delayed.
743      feed_data(':lua vim.schedule(function() vim.wait(100) end); vim.cmd("restart!")\n')
744      screen:expect(s0)
745      assert_new_pid()
746      assert_exitreason()
747      assert_termguicolors_and_no_gui_running()
748    end
749
750    screen:try_resize(60, 6)
751    screen:expect([[
752      ^                                                            |
753      {1:~}{18:                                                           }|*2
754      {3:[No Name]                                                   }|
755                                                                  |
756      {5:-- TERMINAL --}                                              |
757    ]])
758
759    --- Check that ":restart!" uses the updated size after terminal resize.
760    tt.feed_data(':restart! echo "restarted"\013')
761    screen:expect([[
762      ^                                                            |
763      {1:~}{18:                                                           }|*2
764      {3:[No Name]                                                   }|
765      restarted                                                   |
766      {5:-- TERMINAL --}                                              |
767    ]])
768    assert_new_pid()
769    assert_exitreason()
770    assert_termguicolors_and_no_gui_running()
771
772    -- The server is now detached and needs to be quit explicitly.
773    feed_data(':qall!\r')
774    screen:expect({ any = vim.pesc('[Process exited 0]') })
775  end)
776
777  it('drops "-" and "-- [files…]" from v:argv #34417', function()
778    t.skip(is_os('win'), 'stdin behavior differs on Windows')
779    local file = 'file.lua'
780    write_file(file, "print('-S works')\n")
781    finally(function()
782      os.remove(file)
783    end)
784    local server_session
785    finally(function()
786      if server_session then
787        server_session:close()
788      end
789    end)
790    local server_pipe = new_pipename()
791    local screen = tt.setup_child_nvim({
792      '-u',
793      'NONE',
794      '-i',
795      'NONE',
796      '--listen',
797      server_pipe,
798      '--cmd',
799      'set notermguicolors',
800      '-S',
801      file,
802      '-s',
803      '-',
804      '-',
805      '--',
806      'Xtest-file1',
807      'Xtest-file2',
808    }, { env = env_notermguicolors })
809    screen:expect([[
810      ^                                                  |
811      ~                                                 |*3
812      {2:Xtest-file1                     0,0-1          All}|
813      -S works                                          |
814      {5:-- TERMINAL --}                                    |
815    ]])
816    server_session = n.connect(server_pipe)
817    local expr = 'index(v:argv, "-") >= 0 || index(v:argv, "--") >= 0 ? v:true : v:false'
818    local has_s = 'index(v:argv, "-s") >= 0 ? v:true : v:false'
819    local has_S = 'index(v:argv, "-S") >= 0 ? v:true : v:false'
820    eq({ true, true }, { server_session:request('nvim_eval', expr) })
821    eq({ true, true }, { server_session:request('nvim_eval', has_s) })
822    eq({ true, true }, { server_session:request('nvim_eval', has_S) })
823
824    tt.feed_data(":restart! put='foo'\013")
825    screen:expect([[
826                                                        |
827      ^foo                                               |
828      ~                                                 |*2
829      {2:[No Name] [+]                   2,1            All}|
830                                                        |
831      {5:-- TERMINAL --}                                    |
832    ]])
833    server_session:close()
834    server_session = n.connect(server_pipe)
835
836    eq({ true, false }, { server_session:request('nvim_eval', expr) })
837    eq({ true, false }, { server_session:request('nvim_eval', has_s) })
838    eq({ true, false }, { server_session:request('nvim_eval', has_S) })
839
840    -- local argv = ({ server_session:request('nvim_eval', 'v:argv') })[2] --[[@type table]]
841    -- eq(13, #argv)
842    -- eq("-c put='foo'", table.concat(argv, ' ', #argv - 1, #argv))
843
844    -- The server is now detached and needs to be quit explicitly.
845    feed_data(':qall!\r')
846    screen:expect({ any = vim.pesc('[Process exited 0]') })
847  end)
848
849  it('[command] triggers autocommands properly #38549', function()
850    local screen = tt.setup_child_nvim({
851      '--clean',
852      '--cmd',
853      'autocmd FileType text echomsg "TRIGGERED: " .. bufnr()',
854      '--cmd',
855      'set notermguicolors noswapfile laststatus=0',
856    }, { env = env_notermguicolors })
857    screen:expect([[
858      ^                                                  |
859      ~                                                 |*4
860                                      0,0-1          All|
861      {5:-- TERMINAL --}                                    |
862    ]])
863
864    -- 'laststatus' should be 0 in the new Nvim and FileType event should be triggered.
865    feed_data(':restart! set nowrap | edit test/functional/fixtures/bigfile.txt\r')
866    screen:expect([[
867      ^0000;<control>;Cc;0;BN;;;;;N;NULL;;;;             |
868      0001;<control>;Cc;0;BN;;;;;N;START OF HEADING;;;; |
869      0002;<control>;Cc;0;BN;;;;;N;START OF TEXT;;;;    |
870      0003;<control>;Cc;0;BN;;;;;N;END OF TEXT;;;;      |
871      0004;<control>;Cc;0;BN;;;;;N;END OF TRANSMISSION;;|
872      TRIGGERED: 1                    1,1            Top|
873      {5:-- TERMINAL --}                                    |
874    ]])
875
876    -- The server is now detached and needs to be quit explicitly.
877    feed_data(':qall!\r')
878    screen:expect({ any = vim.pesc('[Process exited 0]') })
879  end)
880
881  it('new server loads user config after old server exits #38569', function()
882    local config_file = 'Xrestart_session_config.lua'
883    local session_file = 'Xrestart_session.vim'
884    write_file(
885      config_file,
886      ([[
887        vim.api.nvim_create_autocmd("VimLeavePre", {
888          callback = function()
889            vim.cmd('mksession! %s')
890          end,
891        })
892
893        if vim.v.vim_did_enter and vim.uv.fs_stat('%s') then
894          vim.cmd('source %s')
895        end
896      ]]):format(session_file, session_file, session_file)
897    )
898    finally(function()
899      os.remove(config_file)
900      os.remove(session_file)
901    end)
902
903    local screen = tt.setup_child_nvim({
904      '--clean',
905      '-u',
906      config_file,
907      '--cmd',
908      'set notermguicolors noswapfile laststatus=0 nowrap noruler noshowcmd',
909    }, { env = env_notermguicolors })
910    screen:expect([[
911      ^                                                  |
912      ~                                                 |*4
913                                                        |
914      {5:-- TERMINAL --}                                    |
915    ]])
916
917    feed_data(':rightbelow 28vsplit test/functional/fixtures/bigfile.txt\r')
918    screen:expect([[
919                           │^0000;<control>;Cc;0;BN;;;;;N|
920      ~                    │0001;<control>;Cc;0;BN;;;;;N|
921      ~                    │0002;<control>;Cc;0;BN;;;;;N|
922      ~                    │0003;<control>;Cc;0;BN;;;;;N|
923      ~                    │0004;<control>;Cc;0;BN;;;;;N|
924                                                        |
925      {5:-- TERMINAL --}                                    |
926    ]])
927
928    feed_data(':restart! echo "restarted"\r')
929    screen:expect([[
930                           │^0000;<control>;Cc;0;BN;;;;;N|
931      ~                    │0001;<control>;Cc;0;BN;;;;;N|
932      ~                    │0002;<control>;Cc;0;BN;;;;;N|
933      ~                    │0003;<control>;Cc;0;BN;;;;;N|
934      ~                    │0004;<control>;Cc;0;BN;;;;;N|
935      restarted                                         |
936      {5:-- TERMINAL --}                                    |
937    ]])
938
939    feed_data(':set sessionoptions-=winsize | restart!\r')
940    screen:expect([[
941                              │^0000;<control>;Cc;0;BN;;;|
942      ~                       │0001;<control>;Cc;0;BN;;;|
943      ~                       │0002;<control>;Cc;0;BN;;;|
944      ~                       │0003;<control>;Cc;0;BN;;;|
945      ~                       │0004;<control>;Cc;0;BN;;;|
946                                                        |
947      {5:-- TERMINAL --}                                    |
948    ]])
949
950    -- The server is now detached and needs to be quit explicitly.
951    feed_data(':qall!\r')
952    screen:expect({ any = vim.pesc('[Process exited 0]') })
953  end)
954end)
955
956describe('TUI :connect', function()
957  before_each(n.clear)
958  after_each(n.check_close)
959
960  local screen_empty = [[
961    ^                                                  |
962    {100:~                                                 }|*5
963                                                      |
964  ]]
965
966  it('leaves the current server running', function()
967    local server1 = new_pipename()
968    local screen1 = tt.setup_child_nvim({ '--listen', server1, '--clean' })
969    screen1:expect({ any = vim.pesc('[No Name]') })
970
971    tt.feed_data(':connect\013')
972    screen1:expect({ any = 'E471: Argument required' })
973
974    tt.feed_data('iThis is server 1.\027')
975    screen1:expect({ any = vim.pesc('This is server 1^.') })
976
977    -- Prevent screen2 from receiving the old terminal state.
978    command('enew')
979    screen1:expect(screen_empty)
980    screen1:detach()
981
982    local server2 = new_pipename()
983    local screen2 = tt.setup_child_nvim({ '--listen', server2, '--clean' })
984    screen2:expect({ any = vim.pesc('[No Name]') })
985
986    tt.feed_data('iThis is server 2.\027')
987    screen2:expect({ any = vim.pesc('This is server 2^.') })
988
989    if is_os('win') then
990      -- still supports backslashes
991      server1 = server1:gsub('/', '\\')
992    end
993    tt.feed_data(':connect ' .. server1 .. '\013')
994    screen2:expect({ any = vim.pesc('This is server 1^.') })
995
996    local server1_session = n.connect(server1)
997    server1_session:request('nvim_command', 'qall!')
998    screen2:expect({ any = vim.pesc('[Process exited 0]') })
999
1000    screen2:detach()
1001
1002    local server2_session = n.connect(server2)
1003
1004    local screen3 = tt.setup_child_nvim({ '--remote-ui', '--server', server2 })
1005    screen3:expect({ any = vim.pesc('This is server 2^.') })
1006
1007    screen3:detach()
1008    server2_session:request('nvim_command', 'qall!')
1009  end)
1010
1011  it('! stops the current server', function()
1012    local server1 = new_pipename()
1013    local screen1 = tt.setup_child_nvim({ '--listen', server1, '--clean' })
1014    screen1:expect({ any = vim.pesc('[No Name]') })
1015
1016    tt.feed_data('iThis is server 1.\027')
1017    screen1:expect({ any = vim.pesc('This is server 1^.') })
1018
1019    -- Prevent screen2 from receiving the old terminal state.
1020    command('enew')
1021    screen1:expect(screen_empty)
1022    screen1:detach()
1023
1024    local server2 = new_pipename()
1025    local screen2 = tt.setup_child_nvim({ '--listen', server2, '--clean' })
1026    screen2:expect({ any = vim.pesc('[No Name]') })
1027
1028    tt.feed_data(':connect! ' .. server1 .. '\013')
1029    screen2:expect({ any = vim.pesc('This is server 1^.') })
1030
1031    retry(nil, nil, function()
1032      eq(nil, vim.uv.fs_stat(server2))
1033    end)
1034
1035    local server1_session = n.connect(server1)
1036    server1_session:request('nvim_command', 'qall!')
1037    screen2:expect({ any = vim.pesc('[Process exited 0]') })
1038
1039    screen2:detach()
1040  end)
1041end)
1042
1043describe('TUI', function()
1044  local screen --[[@type test.functional.ui.screen]]
1045  local child_session --[[@type test.Session]]
1046  local child_exec_lua --[[@type fun(code: string, ...):any]]
1047
1048  before_each(function()
1049    clear()
1050    local child_server = new_pipename()
1051    screen = tt.setup_child_nvim({
1052      '--listen',
1053      child_server,
1054      '--clean',
1055      '--cmd',
1056      nvim_set .. ' laststatus=2 background=dark',
1057      '--cmd',
1058      'colorscheme vim',
1059    }, { env = env_notermguicolors })
1060    screen:expect([[
1061      ^                                                  |
1062      {100:~                                                 }|*3
1063      {3:[No Name]                                         }|
1064                                                        |
1065      {5:-- TERMINAL --}                                    |
1066    ]])
1067    child_session = n.connect(child_server)
1068    child_exec_lua = tt.make_lua_executor(child_session)
1069  end)
1070
1071  -- Wait for mode in the child Nvim (avoid "typeahead race" #10826).
1072  local function wait_for_mode(mode)
1073    retry(nil, nil, function()
1074      local _, m = child_session:request('nvim_get_mode')
1075      eq(mode, m.mode)
1076    end)
1077  end
1078
1079  -- Assert buffer contents in the child Nvim.
1080  local function expect_child_buf_lines(expected)
1081    assert(type({}) == type(expected))
1082    retry(nil, nil, function()
1083      local _, buflines = child_session:request('nvim_buf_get_lines', 0, 0, -1, false)
1084      eq(expected, buflines)
1085    end)
1086  end
1087
1088  -- Ensure both child client and child server have processed pending events.
1089  local function poke_both_eventloop()
1090    child_exec_lua([[
1091      _G.termresponse = nil
1092      vim.api.nvim_create_autocmd('TermResponse', {
1093        once = true,
1094        callback = function(ev) _G.termresponse = ev.data.sequence end,
1095      })
1096    ]])
1097    feed_data('\027P0$r\027\\')
1098    retry(nil, nil, function()
1099      eq('\027P0$r', child_exec_lua('return _G.termresponse'))
1100    end)
1101  end
1102
1103  it('rapid resize #7572 #7628', function()
1104    -- Need buffer rows to provoke the behavior.
1105    feed_data(':edit test/functional/fixtures/bigfile.txt\n')
1106    screen:expect([[
1107      ^0000;<control>;Cc;0;BN;;;;;N;NULL;;;;             |
1108      0001;<control>;Cc;0;BN;;;;;N;START OF HEADING;;;; |
1109      0002;<control>;Cc;0;BN;;;;;N;START OF TEXT;;;;    |
1110      0003;<control>;Cc;0;BN;;;;;N;END OF TEXT;;;;      |
1111      {3:test/functional/fixtures/bigfile.txt              }|
1112      :edit test/functional/fixtures/bigfile.txt        |
1113      {5:-- TERMINAL --}                                    |
1114    ]])
1115    command('call jobresize(b:terminal_job_id, 58, 9)')
1116    command('call jobresize(b:terminal_job_id, 62, 13)')
1117    command('call jobresize(b:terminal_job_id, 100, 42)')
1118    command('call jobresize(b:terminal_job_id, 37, 1000)')
1119    -- Resize to <5 columns.
1120    screen:try_resize(4, 44)
1121    command('call jobresize(b:terminal_job_id, 4, 1000)')
1122    -- Resize to 1 row, then to 1 column, then increase rows to 4.
1123    screen:try_resize(44, 1)
1124    command('call jobresize(b:terminal_job_id, 44, 1)')
1125    screen:try_resize(1, 1)
1126    command('call jobresize(b:terminal_job_id, 1, 1)')
1127    screen:try_resize(1, 4)
1128    command('call jobresize(b:terminal_job_id, 1, 4)')
1129    screen:try_resize(57, 17)
1130    command('call jobresize(b:terminal_job_id, 57, 17)')
1131    retry(nil, nil, function()
1132      eq({ true, 57 }, { child_session:request('nvim_win_get_width', 0) })
1133    end)
1134  end)
1135
1136  it('accepts resize while pager is active', function()
1137    tt.override_screen_expect_for_conpty(screen)
1138    child_session:request(
1139      'nvim_exec2',
1140      [[
1141      set more
1142      func! ManyErr()
1143        for i in range(20)
1144          echoerr "FAIL ".i
1145        endfor
1146      endfunc
1147    ]],
1148      {}
1149    )
1150    feed_data(':call ManyErr()\r')
1151    screen:expect([[
1152      {101:Error in function ManyErr:}                        |
1153      {103:line    2:}                                        |
1154      {101:FAIL 0}                                            |
1155      {101:FAIL 1}                                            |
1156      {101:FAIL 2}                                            |
1157      {102:-- More --}^                                        |
1158      {5:-- TERMINAL --}                                    |
1159    ]])
1160
1161    screen:try_resize(50, 10)
1162    screen:expect([[
1163      :call ManyErr()                                   |
1164      {101:Error in function ManyErr:}                        |
1165      {103:line    2:}                                        |
1166      {101:FAIL 0}                                            |
1167      {101:FAIL 1}                                            |
1168      {101:FAIL 2}                                            |
1169                                                        |*2
1170      {102:-- More --}^                                        |
1171      {5:-- TERMINAL --}                                    |
1172    ]])
1173
1174    feed_data('j')
1175    screen:expect([[
1176      {101:Error in function ManyErr:}                        |
1177      {103:line    2:}                                        |
1178      {101:FAIL 0}                                            |
1179      {101:FAIL 1}                                            |
1180      {101:FAIL 2}                                            |
1181      {101:FAIL 3}                                            |
1182      {101:FAIL 4}                                            |
1183      {101:FAIL 5}                                            |
1184      {102:-- More --}^                                        |
1185      {5:-- TERMINAL --}                                    |
1186    ]])
1187
1188    screen:try_resize(50, 7)
1189    screen:expect([[
1190      {101:FAIL 1}                                            |
1191      {101:FAIL 2}                                            |
1192      {101:FAIL 3}                                            |
1193      {101:FAIL 4}                                            |
1194      {101:FAIL 5}                                            |
1195      {102:-- More --}^                                        |
1196      {5:-- TERMINAL --}                                    |
1197    ]])
1198
1199    screen:try_resize(50, 5)
1200    screen:expect([[
1201      {101:FAIL 3}                                            |
1202      {101:FAIL 4}                                            |
1203      {101:FAIL 5}                                            |
1204      {102:-- More --}^                                        |
1205      {5:-- TERMINAL --}                                    |
1206    ]])
1207
1208    feed_data('g')
1209    screen:expect([[
1210      :call ManyErr()                                   |
1211      {101:Error in function ManyErr:}                        |
1212      {103:line    2:}                                        |
1213      {102:-- More --}^                                        |
1214      {5:-- TERMINAL --}                                    |
1215    ]])
1216
1217    screen:try_resize(50, 10)
1218    screen:expect([[
1219      :call ManyErr()                                   |
1220      {101:Error in function ManyErr:}                        |
1221      {103:line    2:}                                        |
1222      {101:FAIL 0}                                            |
1223      {101:FAIL 1}                                            |
1224      {101:FAIL 2}                                            |
1225      {101:FAIL 3}                                            |
1226      {101:FAIL 4}                                            |
1227      {102:-- More --}^                                        |
1228      {5:-- TERMINAL --}                                    |
1229    ]])
1230
1231    feed_data('\003')
1232    screen:expect([[
1233      ^                                                  |
1234      {100:~                                                 }|*6
1235      {3:[No Name]                                         }|
1236                                                        |
1237      {5:-- TERMINAL --}                                    |
1238    ]])
1239  end)
1240
1241  it('accepts basic utf-8 input', function()
1242    feed_data('iabc\ntest1\ntest2')
1243    screen:expect([[
1244      abc                                               |
1245      test1                                             |
1246      test2^                                             |
1247      {100:~                                                 }|
1248      {3:[No Name] [+]                                     }|
1249      {5:-- INSERT --}                                      |
1250      {5:-- TERMINAL --}                                    |
1251    ]])
1252    feed_data('\027')
1253    screen:expect([[
1254      abc                                               |
1255      test1                                             |
1256      test^2                                             |
1257      {100:~                                                 }|
1258      {3:[No Name] [+]                                     }|
1259                                                        |
1260      {5:-- TERMINAL --}                                    |
1261    ]])
1262  end)
1263
1264  it('interprets leading ESC byte as ALT modifier in normal-mode', function()
1265    local keys = 'dfghjkl'
1266    for c in keys:gmatch('.') do
1267      feed_data(':nnoremap <a-' .. c .. '> ialt-' .. c .. '<cr><esc>\r')
1268      feed_data('\027' .. c)
1269    end
1270    feed_data(':nnoremap <a-esc> ialt-esc<esc>\r')
1271    feed_data('\027\027')
1272    screen:expect([[
1273      alt-j                                             |
1274      alt-k                                             |
1275      alt-l                                             |
1276      alt-es^c                                           |
1277      {3:[No Name] [+]                                     }|
1278                                                        |
1279      {5:-- TERMINAL --}                                    |
1280    ]])
1281    feed_data('gg')
1282    screen:expect([[
1283      ^alt-d                                             |
1284      alt-f                                             |
1285      alt-g                                             |
1286      alt-h                                             |
1287      {3:[No Name] [+]                                     }|
1288                                                        |
1289      {5:-- TERMINAL --}                                    |
1290    ]])
1291  end)
1292
1293  it('interprets ESC+key as ALT chord in i_CTRL-V', function()
1294    -- Vim represents ALT/META by setting the "high bit" of the modified key:
1295    -- ALT+j inserts "ê". Nvim does not (#3982).
1296    feed_data('i\022\027j')
1297    screen:expect([[
1298      <M-j>^                                             |
1299      {100:~                                                 }|*3
1300      {3:[No Name] [+]                                     }|
1301      {5:-- INSERT --}                                      |
1302      {5:-- TERMINAL --}                                    |
1303    ]])
1304  end)
1305
1306  it('interprets ESC encoded with kitty keyboard protocol', function()
1307    child_session:request(
1308      'nvim_exec2',
1309      [[
1310      nnoremap <M-;> <Nop>
1311      nnoremap <Esc> AESC<Esc>
1312      nnoremap <C-Esc> ACtrlEsc<Esc>
1313      nnoremap <D-Esc> ASuperEsc<Esc>
1314      nnoremap ; Asemicolon<Esc>
1315    ]],
1316      {}
1317    )
1318    -- Works with no modifier
1319    feed_data('\027[27u;')
1320    expect_child_buf_lines({ 'ESCsemicolon' })
1321    -- Works with Ctrl modifier
1322    feed_data('\027[27;5u')
1323    expect_child_buf_lines({ 'ESCsemicolonCtrlEsc' })
1324    -- Works with Super modifier
1325    feed_data('\027[27;9u')
1326    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEsc' })
1327    -- Works with NumLock modifier (which should be the same as no modifier) #33799
1328    feed_data('\027[27;129u')
1329    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEscESC' })
1330    screen:expect([[
1331      ESCsemicolonCtrlEscSuperEscES^C                    |
1332      {100:~                                                 }|*3
1333      {3:[No Name] [+]                                     }|
1334                                                        |
1335      {5:-- TERMINAL --}                                    |
1336    ]])
1337    -- ESC+; should be recognized as <M-;> when <M-;> is mapped
1338    feed_data('\027;')
1339    screen:expect_unchanged()
1340    expect_child_buf_lines({ 'ESCsemicolonCtrlEscSuperEscESC' })
1341  end)
1342
1343  it('interprets ESC NUL as <M-C-Space> #17198', function()
1344    t.skip(is_os('win'), 'FIXME: does not work on Windows')
1345    feed_data('i\022\027\000')
1346    screen:expect([[
1347      <M-C-Space>^                                       |
1348      {100:~                                                 }|*3
1349      {3:[No Name] [+]                                     }|
1350      {5:-- INSERT --}                                      |
1351      {5:-- TERMINAL --}                                    |
1352    ]])
1353  end)
1354
1355  it('does not interpret ESC preceding repeat/release event as ALT #41763', function()
1356    child_session:request('nvim_command', 'noremap <M-Esc> <Nop>')
1357    child_session:request('nvim_command', 'noremap! <M-Esc> <Nop>')
1358    feed_data('i\015')
1359    wait_for_mode('niI')
1360    feed_data('\027\027[27;1:3u') -- ESC, ESC release
1361    wait_for_mode('i')
1362    feed_data('\015')
1363    wait_for_mode('niI')
1364    feed_data('\027\027[27;1:2u\027[27;1:3u') -- ESC, ESC repeat, ESC release
1365    wait_for_mode('n')
1366  end)
1367
1368  it("split sequences work within 'ttimeoutlen' time", function()
1369    poke_both_eventloop() -- Make sure startup requests have finished.
1370    -- The split sequences below are always completed, so this timeout never actually fires; it only
1371    -- needs to exceed the inter-byte gap, which balloons on slow CI.
1372    child_session:request('nvim_set_option_value', 'ttimeoutlen', n.load_adjust(1000), {})
1373    feed_data('i')
1374    screen:expect([[
1375      ^                                                  |
1376      {100:~                                                 }|*3
1377      {3:[No Name]                                         }|
1378      {5:-- INSERT --}                                      |
1379      {5:-- TERMINAL --}                                    |
1380    ]])
1381    -- Split UTF-8 '⌂' character
1382    feed_data('\226')
1383    screen:expect_unchanged(false, 25)
1384    feed_data('\140')
1385    screen:expect_unchanged(false, 25)
1386    feed_data('\130')
1387    screen:expect([[
1388      ⌂^                                                 |
1389      {100:~                                                 }|*3
1390      {3:[No Name] [+]                                     }|
1391      {5:-- INSERT --}                                      |
1392      {5:-- TERMINAL --}                                    |
1393    ]])
1394    -- Split CSI u escape sequence for Ctrl-X
1395    feed_data('\027')
1396    screen:expect_unchanged(false, 25)
1397    feed_data('[')
1398    screen:expect_unchanged(false, 25)
1399    feed_data('120;')
1400    screen:expect_unchanged(false, 25)
1401    feed_data('5u')
1402    screen:expect([[
1403      ⌂^                                                 |
1404      {100:~                                                 }|*3
1405      {3:[No Name] [+]                                     }|
1406      {5:-- ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)}        |
1407      {5:-- TERMINAL --}                                    |
1408    ]])
1409
1410    -- <Esc> is sent after 'ttimeoutlen' exceeds. Use a small value so the sleep below reliably exceeds it.
1411    child_session:request('nvim_set_option_value', 'ttimeoutlen', 250, {})
1412    poke_both_eventloop()
1413
1414    feed_data('\027')
1415    screen:expect_unchanged(false, 25)
1416    vim.uv.sleep(225)
1417    screen:expect([[
1418      ^⌂                                                 |
1419      {100:~                                                 }|*3
1420      {3:[No Name] [+]                                     }|
1421                                                        |
1422      {5:-- TERMINAL --}                                    |
1423    ]])
1424  end)
1425
1426  it('accepts ASCII control sequences', function()
1427    feed_data('i')
1428    feed_data('\022\007') -- ctrl+g
1429    feed_data('\022\022') -- ctrl+v
1430    feed_data('\022\013') -- ctrl+m
1431    screen:expect([[
1432      {104:^G^V^M}^                                            |
1433      {100:~                                                 }|*3
1434      {3:[No Name] [+]                                     }|
1435      {5:-- INSERT --}                                      |
1436      {5:-- TERMINAL --}                                    |
1437    ]])
1438    child_session:request('nvim_set_keymap', 'i', '\031', '!!!', {})
1439    feed_data('\031')
1440    screen:expect([[
1441      {104:^G^V^M}!!!^                                         |
1442      {100:~                                                 }|*3
1443      {3:[No Name] [+]                                     }|
1444      {5:-- INSERT --}                                      |
1445      {5:-- TERMINAL --}                                    |
1446    ]])
1447    child_session:request('nvim_buf_delete', 0, { force = true })
1448    child_session:request('nvim_set_option_value', 'laststatus', 0, {})
1449    child_session:request(
1450      'nvim_call_function',
1451      'jobstart',
1452      { { testprg('shell-test'), 'INTERACT' }, { term = true } }
1453    )
1454    screen:expect([[
1455      interact $ ^                                       |
1456                                                        |*4
1457      {5:-- TERMINAL --}                                    |*2
1458    ]])
1459    -- mappings for C0 control codes should work in Terminal mode #33750
1460    child_session:request('nvim_set_keymap', 't', '\031', '<Cmd>new<CR>', {})
1461    feed_data('\031')
1462    screen:expect([[
1463      ^                                                  |
1464      {100:~                                                 }|
1465      {3:[No Name]                                         }|
1466      interact $                                        |
1467                                                        |*2
1468      {5:-- TERMINAL --}                                    |
1469    ]])
1470  end)
1471
1472  local function test_mouse_wheel(esc)
1473    t.skip(is_os('win'), 'FIXME: some spaces have wrong attrs on Windows')
1474    child_session:request(
1475      'nvim_exec2',
1476      [[
1477      set number nostartofline nowrap mousescroll=hor:1,ver:1
1478      call setline(1, repeat([join(range(10), '----')], 10))
1479      vsplit
1480    ]],
1481      {}
1482    )
1483    screen:expect([[
1484      {103:  1 }^0----1----2----3----4│{103:  1 }0----1----2----3----|
1485      {103:  2 }0----1----2----3----4│{103:  2 }0----1----2----3----|
1486      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
1487      {103:  4 }0----1----2----3----4│{103:  4 }0----1----2----3----|
1488      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1489                                                        |
1490      {5:-- TERMINAL --}                                    |
1491    ]])
1492    -- <ScrollWheelDown> in active window
1493    if esc then
1494      feed_data('\027[<65;8;1M')
1495    else
1496      api.nvim_input_mouse('wheel', 'down', '', 0, 0, 7)
1497    end
1498    screen:expect([[
1499      {103:  2 }^0----1----2----3----4│{103:  1 }0----1----2----3----|
1500      {103:  3 }0----1----2----3----4│{103:  2 }0----1----2----3----|
1501      {103:  4 }0----1----2----3----4│{103:  3 }0----1----2----3----|
1502      {103:  5 }0----1----2----3----4│{103:  4 }0----1----2----3----|
1503      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1504                                                        |
1505      {5:-- TERMINAL --}                                    |
1506    ]])
1507    -- <ScrollWheelDown> in inactive window
1508    if esc then
1509      feed_data('\027[<65;48;1M')
1510    else
1511      api.nvim_input_mouse('wheel', 'down', '', 0, 0, 47)
1512    end
1513    screen:expect([[
1514      {103:  2 }^0----1----2----3----4│{103:  2 }0----1----2----3----|
1515      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
1516      {103:  4 }0----1----2----3----4│{103:  4 }0----1----2----3----|
1517      {103:  5 }0----1----2----3----4│{103:  5 }0----1----2----3----|
1518      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1519                                                        |
1520      {5:-- TERMINAL --}                                    |
1521    ]])
1522    -- <ScrollWheelRight> in active window
1523    if esc then
1524      feed_data('\027[<67;8;1M')
1525    else
1526      api.nvim_input_mouse('wheel', 'right', '', 0, 0, 7)
1527    end
1528    screen:expect([[
1529      {103:  2 }^----1----2----3----4-│{103:  2 }0----1----2----3----|
1530      {103:  3 }----1----2----3----4-│{103:  3 }0----1----2----3----|
1531      {103:  4 }----1----2----3----4-│{103:  4 }0----1----2----3----|
1532      {103:  5 }----1----2----3----4-│{103:  5 }0----1----2----3----|
1533      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1534                                                        |
1535      {5:-- TERMINAL --}                                    |
1536    ]])
1537    -- <ScrollWheelRight> in inactive window
1538    if esc then
1539      feed_data('\027[<67;48;1M')
1540    else
1541      api.nvim_input_mouse('wheel', 'right', '', 0, 0, 47)
1542    end
1543    screen:expect([[
1544      {103:  2 }^----1----2----3----4-│{103:  2 }----1----2----3----4|
1545      {103:  3 }----1----2----3----4-│{103:  3 }----1----2----3----4|
1546      {103:  4 }----1----2----3----4-│{103:  4 }----1----2----3----4|
1547      {103:  5 }----1----2----3----4-│{103:  5 }----1----2----3----4|
1548      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1549                                                        |
1550      {5:-- TERMINAL --}                                    |
1551    ]])
1552    -- <S-ScrollWheelDown> in active window
1553    if esc then
1554      feed_data('\027[<69;8;1M')
1555    else
1556      api.nvim_input_mouse('wheel', 'down', 'S', 0, 0, 7)
1557    end
1558    screen:expect([[
1559      {103:  5 }^----1----2----3----4-│{103:  2 }----1----2----3----4|
1560      {103:  6 }----1----2----3----4-│{103:  3 }----1----2----3----4|
1561      {103:  7 }----1----2----3----4-│{103:  4 }----1----2----3----4|
1562      {103:  8 }----1----2----3----4-│{103:  5 }----1----2----3----4|
1563      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1564                                                        |
1565      {5:-- TERMINAL --}                                    |
1566    ]])
1567    -- <S-ScrollWheelDown> in inactive window
1568    if esc then
1569      feed_data('\027[<69;48;1M')
1570    else
1571      api.nvim_input_mouse('wheel', 'down', 'S', 0, 0, 47)
1572    end
1573    screen:expect([[
1574      {103:  5 }^----1----2----3----4-│{103:  5 }----1----2----3----4|
1575      {103:  6 }----1----2----3----4-│{103:  6 }----1----2----3----4|
1576      {103:  7 }----1----2----3----4-│{103:  7 }----1----2----3----4|
1577      {103:  8 }----1----2----3----4-│{103:  8 }----1----2----3----4|
1578      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1579                                                        |
1580      {5:-- TERMINAL --}                                    |
1581    ]])
1582    -- <S-ScrollWheelRight> in active window
1583    if esc then
1584      feed_data('\027[<71;8;1M')
1585    else
1586      api.nvim_input_mouse('wheel', 'right', 'S', 0, 0, 7)
1587    end
1588    screen:expect([[
1589      {103:  5 }^----6----7----8----9 │{103:  5 }----1----2----3----4|
1590      {103:  6 }----6----7----8----9 │{103:  6 }----1----2----3----4|
1591      {103:  7 }----6----7----8----9 │{103:  7 }----1----2----3----4|
1592      {103:  8 }----6----7----8----9 │{103:  8 }----1----2----3----4|
1593      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1594                                                        |
1595      {5:-- TERMINAL --}                                    |
1596    ]])
1597    -- <S-ScrollWheelRight> in inactive window
1598    if esc then
1599      feed_data('\027[<71;48;1M')
1600    else
1601      api.nvim_input_mouse('wheel', 'right', 'S', 0, 0, 47)
1602    end
1603    screen:expect([[
1604      {103:  5 }^----6----7----8----9 │{103:  5 }5----6----7----8----|
1605      {103:  6 }----6----7----8----9 │{103:  6 }5----6----7----8----|
1606      {103:  7 }----6----7----8----9 │{103:  7 }5----6----7----8----|
1607      {103:  8 }----6----7----8----9 │{103:  8 }5----6----7----8----|
1608      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1609                                                        |
1610      {5:-- TERMINAL --}                                    |
1611    ]])
1612    -- <ScrollWheelUp> in active window
1613    if esc then
1614      feed_data('\027[<64;8;1M')
1615    else
1616      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 7)
1617    end
1618    screen:expect([[
1619      {103:  4 }----6----7----8----9 │{103:  5 }5----6----7----8----|
1620      {103:  5 }^----6----7----8----9 │{103:  6 }5----6----7----8----|
1621      {103:  6 }----6----7----8----9 │{103:  7 }5----6----7----8----|
1622      {103:  7 }----6----7----8----9 │{103:  8 }5----6----7----8----|
1623      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1624                                                        |
1625      {5:-- TERMINAL --}                                    |
1626    ]])
1627    -- <ScrollWheelUp> in inactive window
1628    if esc then
1629      feed_data('\027[<64;48;1M')
1630    else
1631      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 47)
1632    end
1633    screen:expect([[
1634      {103:  4 }----6----7----8----9 │{103:  4 }5----6----7----8----|
1635      {103:  5 }^----6----7----8----9 │{103:  5 }5----6----7----8----|
1636      {103:  6 }----6----7----8----9 │{103:  6 }5----6----7----8----|
1637      {103:  7 }----6----7----8----9 │{103:  7 }5----6----7----8----|
1638      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1639                                                        |
1640      {5:-- TERMINAL --}                                    |
1641    ]])
1642    -- <ScrollWheelLeft> in active window
1643    if esc then
1644      feed_data('\027[<66;8;1M')
1645    else
1646      api.nvim_input_mouse('wheel', 'left', '', 0, 0, 7)
1647    end
1648    screen:expect([[
1649      {103:  4 }5----6----7----8----9│{103:  4 }5----6----7----8----|
1650      {103:  5 }5^----6----7----8----9│{103:  5 }5----6----7----8----|
1651      {103:  6 }5----6----7----8----9│{103:  6 }5----6----7----8----|
1652      {103:  7 }5----6----7----8----9│{103:  7 }5----6----7----8----|
1653      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1654                                                        |
1655      {5:-- TERMINAL --}                                    |
1656    ]])
1657    -- <ScrollWheelLeft> in inactive window
1658    if esc then
1659      feed_data('\027[<66;48;1M')
1660    else
1661      api.nvim_input_mouse('wheel', 'left', '', 0, 0, 47)
1662    end
1663    screen:expect([[
1664      {103:  4 }5----6----7----8----9│{103:  4 }-5----6----7----8---|
1665      {103:  5 }5^----6----7----8----9│{103:  5 }-5----6----7----8---|
1666      {103:  6 }5----6----7----8----9│{103:  6 }-5----6----7----8---|
1667      {103:  7 }5----6----7----8----9│{103:  7 }-5----6----7----8---|
1668      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1669                                                        |
1670      {5:-- TERMINAL --}                                    |
1671    ]])
1672    -- <S-ScrollWheelUp> in active window
1673    if esc then
1674      feed_data('\027[<68;8;1M')
1675    else
1676      api.nvim_input_mouse('wheel', 'up', 'S', 0, 0, 7)
1677    end
1678    screen:expect([[
1679      {103:  1 }5----6----7----8----9│{103:  4 }-5----6----7----8---|
1680      {103:  2 }5----6----7----8----9│{103:  5 }-5----6----7----8---|
1681      {103:  3 }5----6----7----8----9│{103:  6 }-5----6----7----8---|
1682      {103:  4 }5^----6----7----8----9│{103:  7 }-5----6----7----8---|
1683      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1684                                                        |
1685      {5:-- TERMINAL --}                                    |
1686    ]])
1687    -- <S-ScrollWheelUp> in inactive window
1688    if esc then
1689      feed_data('\027[<68;48;1M')
1690    else
1691      api.nvim_input_mouse('wheel', 'up', 'S', 0, 0, 47)
1692    end
1693    screen:expect([[
1694      {103:  1 }5----6----7----8----9│{103:  1 }-5----6----7----8---|
1695      {103:  2 }5----6----7----8----9│{103:  2 }-5----6----7----8---|
1696      {103:  3 }5----6----7----8----9│{103:  3 }-5----6----7----8---|
1697      {103:  4 }5^----6----7----8----9│{103:  4 }-5----6----7----8---|
1698      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1699                                                        |
1700      {5:-- TERMINAL --}                                    |
1701    ]])
1702    -- <S-ScrollWheelLeft> in active window
1703    if esc then
1704      feed_data('\027[<70;8;1M')
1705    else
1706      api.nvim_input_mouse('wheel', 'left', 'S', 0, 0, 7)
1707    end
1708    screen:expect([[
1709      {103:  1 }0----1----2----3----4│{103:  1 }-5----6----7----8---|
1710      {103:  2 }0----1----2----3----4│{103:  2 }-5----6----7----8---|
1711      {103:  3 }0----1----2----3----4│{103:  3 }-5----6----7----8---|
1712      {103:  4 }0----1----2----3----^4│{103:  4 }-5----6----7----8---|
1713      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1714                                                        |
1715      {5:-- TERMINAL --}                                    |
1716    ]])
1717    -- <S-ScrollWheelLeft> in inactive window
1718    if esc then
1719      feed_data('\027[<70;48;1M')
1720    else
1721      api.nvim_input_mouse('wheel', 'left', 'S', 0, 0, 47)
1722    end
1723    screen:expect([[
1724      {103:  1 }0----1----2----3----4│{103:  1 }0----1----2----3----|
1725      {103:  2 }0----1----2----3----4│{103:  2 }0----1----2----3----|
1726      {103:  3 }0----1----2----3----4│{103:  3 }0----1----2----3----|
1727      {103:  4 }0----1----2----3----^4│{103:  4 }0----1----2----3----|
1728      {3:[No Name] [+]             }{2:[No Name] [+]           }|
1729                                                        |
1730      {5:-- TERMINAL --}                                    |
1731    ]])
1732  end
1733
1734  describe('accepts mouse wheel events', function()
1735    it('(mouse events sent to host)', function()
1736      test_mouse_wheel(false)
1737    end)
1738
1739    it('(escape sequences sent to child)', function()
1740      test_mouse_wheel(true)
1741    end)
1742  end)
1743
1744  local function test_mouse_popup(esc)
1745    child_session:request(
1746      'nvim_exec2',
1747      [[
1748      call setline(1, 'popup menu test')
1749      set mouse=a mousemodel=popup
1750
1751      aunmenu PopUp
1752      " Delete the default MenuPopup event handler.
1753      autocmd! nvim.popupmenu
1754      menu PopUp.foo :let g:menustr = 'foo'<CR>
1755      menu PopUp.bar :let g:menustr = 'bar'<CR>
1756      menu PopUp.baz :let g:menustr = 'baz'<CR>
1757      highlight Pmenu ctermbg=NONE ctermfg=NONE cterm=underline,reverse
1758      highlight PmenuSel ctermbg=NONE ctermfg=NONE cterm=underline,reverse,bold
1759    ]],
1760      {}
1761    )
1762    if esc then
1763      feed_data('\027[<2;5;1M')
1764    else
1765      api.nvim_input_mouse('right', 'press', '', 0, 0, 4)
1766    end
1767    screen:expect([[
1768      ^popup menu test                                   |
1769      {100:~  }{105: foo }{100:                                          }|
1770      {100:~  }{105: bar }{100:                                          }|
1771      {100:~  }{105: baz }{100:                                          }|
1772      {3:[No Name] [+]                                     }|
1773                                                        |
1774      {5:-- TERMINAL --}                                    |
1775    ]])
1776    if esc then
1777      feed_data('\027[<2;5;1m')
1778    else
1779      api.nvim_input_mouse('right', 'release', '', 0, 0, 4)
1780    end
1781    screen:expect_unchanged()
1782    if esc then
1783      feed_data('\027[<64;5;1M')
1784    else
1785      api.nvim_input_mouse('wheel', 'up', '', 0, 0, 4)
1786    end
1787    screen:expect([[
1788      ^popup menu test                                   |
1789      {100:~  }{106: foo }{100:                                          }|
1790      {100:~  }{105: bar }{100:                                          }|
1791      {100:~  }{105: baz }{100:                                          }|
1792      {3:[No Name] [+]                                     }|
1793                                                        |
1794      {5:-- TERMINAL --}                                    |
1795    ]])
1796    if esc then
1797      feed_data('\027[<35;7;4M')
1798    else
1799      api.nvim_input_mouse('move', '', '', 0, 3, 6)
1800    end
1801    screen:expect([[
1802      ^popup menu test                                   |
1803      {100:~  }{105: foo }{100:                                          }|
1804      {100:~  }{105: bar }{100:                                          }|
1805      {100:~  }{106: baz }{100:                                          }|
1806      {3:[No Name] [+]                                     }|
1807                                                        |
1808      {5:-- TERMINAL --}                                    |
1809    ]])
1810    if esc then
1811      feed_data('\027[<65;7;4M')
1812    else
1813      api.nvim_input_mouse('wheel', 'down', '', 0, 3, 6)
1814    end
1815    screen:expect([[
1816      ^popup menu test                                   |
1817      {100:~  }{105: foo }{100:                                          }|
1818      {100:~  }{106: bar }{100:                                          }|
1819      {100:~  }{105: baz }{100:                                          }|
1820      {3:[No Name] [+]                                     }|
1821                                                        |
1822      {5:-- TERMINAL --}                                    |
1823    ]])
1824    if esc then
1825      feed_data('\027[<0;7;3M')
1826    else
1827      api.nvim_input_mouse('left', 'press', '', 0, 2, 6)
1828    end
1829    screen:expect([[
1830      ^popup menu test                                   |
1831      {100:~                                                 }|*3
1832      {3:[No Name] [+]                                     }|
1833      :let g:menustr = 'bar'                            |
1834      {5:-- TERMINAL --}                                    |
1835    ]])
1836    if esc then
1837      feed_data('\027[<0;7;3m')
1838    else
1839      api.nvim_input_mouse('left', 'release', '', 0, 2, 6)
1840    end
1841    screen:expect_unchanged()
1842    if esc then
1843      feed_data('\027[<2;45;3M')
1844    else
1845      api.nvim_input_mouse('right', 'press', '', 0, 2, 44)
1846    end
1847    screen:expect([[
1848      ^popup menu test                                   |
1849      {100:~                                                 }|*2
1850      {100:~                                          }{105: foo }{100:  }|
1851      {3:[No Name] [+]                              }{105: bar }{3:  }|
1852      :let g:menustr = 'bar'                     {105: baz }  |
1853      {5:-- TERMINAL --}                                    |
1854    ]])
1855    if esc then
1856      feed_data('\027[<34;48;6M')
1857    else
1858      api.nvim_input_mouse('right', 'drag', '', 0, 5, 47)
1859    end
1860    screen:expect([[
1861      ^popup menu test                                   |
1862      {100:~                                                 }|*2
1863      {100:~                                          }{105: foo }{100:  }|
1864      {3:[No Name] [+]                              }{105: bar }{3:  }|
1865      :let g:menustr = 'bar'                     {106: baz }  |
1866      {5:-- TERMINAL --}                                    |
1867    ]])
1868    if esc then
1869      feed_data('\027[<2;48;6m')
1870    else
1871      api.nvim_input_mouse('right', 'release', '', 0, 5, 47)
1872    end
1873    screen:expect([[
1874      ^popup menu test                                   |
1875      {100:~                                                 }|*3
1876      {3:[No Name] [+]                                     }|
1877      :let g:menustr = 'baz'                            |
1878      {5:-- TERMINAL --}                                    |
1879    ]])
1880  end
1881
1882  describe('mouse events work with right-click menu', function()
1883    it('(mouse events sent to host)', function()
1884      test_mouse_popup(false)
1885    end)
1886
1887    it('(escape sequences sent to child)', function()
1888      test_mouse_popup(true)
1889    end)
1890  end)
1891
1892  it('accepts keypad keys from kitty keyboard protocol #19180', function()
1893    feed_data('i')
1894    feed_data(fn.nr2char(57399)) -- KP_0
1895    feed_data(fn.nr2char(57400)) -- KP_1
1896    feed_data(fn.nr2char(57401)) -- KP_2
1897    feed_data(fn.nr2char(57402)) -- KP_3
1898    feed_data(fn.nr2char(57403)) -- KP_4
1899    feed_data(fn.nr2char(57404)) -- KP_5
1900    feed_data(fn.nr2char(57405)) -- KP_6
1901    feed_data(fn.nr2char(57406)) -- KP_7
1902    feed_data(fn.nr2char(57407)) -- KP_8
1903    feed_data(fn.nr2char(57408)) -- KP_9
1904    feed_data(fn.nr2char(57409)) -- KP_DECIMAL
1905    feed_data(fn.nr2char(57410)) -- KP_DIVIDE
1906    feed_data(fn.nr2char(57411)) -- KP_MULTIPLY
1907    feed_data(fn.nr2char(57412)) -- KP_SUBTRACT
1908    feed_data(fn.nr2char(57413)) -- KP_ADD
1909    feed_data(fn.nr2char(57414)) -- KP_ENTER
1910    feed_data(fn.nr2char(57415)) -- KP_EQUAL
1911    screen:expect([[
1912      0123456789./*-+                                   |
1913      =^                                                 |
1914      {100:~                                                 }|*2
1915      {3:[No Name] [+]                                     }|
1916      {5:-- INSERT --}                                      |
1917      {5:-- TERMINAL --}                                    |
1918    ]])
1919    feed_data(fn.nr2char(57417)) -- KP_LEFT
1920    screen:expect([[
1921      0123456789./*-+                                   |
1922      ^=                                                 |
1923      {100:~                                                 }|*2
1924      {3:[No Name] [+]                                     }|
1925      {5:-- INSERT --}                                      |
1926      {5:-- TERMINAL --}                                    |
1927    ]])
1928    feed_data(fn.nr2char(57418)) -- KP_RIGHT
1929    screen:expect([[
1930      0123456789./*-+                                   |
1931      =^                                                 |
1932      {100:~                                                 }|*2
1933      {3:[No Name] [+]                                     }|
1934      {5:-- INSERT --}                                      |
1935      {5:-- TERMINAL --}                                    |
1936    ]])
1937    feed_data(fn.nr2char(57419)) -- KP_UP
1938    screen:expect([[
1939      0^123456789./*-+                                   |
1940      =                                                 |
1941      {100:~                                                 }|*2
1942      {3:[No Name] [+]                                     }|
1943      {5:-- INSERT --}                                      |
1944      {5:-- TERMINAL --}                                    |
1945    ]])
1946    feed_data(fn.nr2char(57420)) -- KP_DOWN
1947    screen:expect([[
1948      0123456789./*-+                                   |
1949      =^                                                 |
1950      {100:~                                                 }|*2
1951      {3:[No Name] [+]                                     }|
1952      {5:-- INSERT --}                                      |
1953      {5:-- TERMINAL --}                                    |
1954    ]])
1955    feed_data(fn.nr2char(57425)) -- KP_INSERT
1956    screen:expect([[
1957      0123456789./*-+                                   |
1958      =^                                                 |
1959      {100:~                                                 }|*2
1960      {3:[No Name] [+]                                     }|
1961      {5:-- REPLACE --}                                     |
1962      {5:-- TERMINAL --}                                    |
1963    ]])
1964    feed_data('\027[27u') -- ESC
1965    screen:expect([[
1966      0123456789./*-+                                   |
1967      ^=                                                 |
1968      {100:~                                                 }|*2
1969      {3:[No Name] [+]                                     }|
1970                                                        |
1971      {5:-- TERMINAL --}                                    |
1972    ]])
1973    feed_data('\027[57417;5u') -- CTRL + KP_LEFT
1974    screen:expect([[
1975      ^0123456789./*-+                                   |
1976      =                                                 |
1977      {100:~                                                 }|*2
1978      {3:[No Name] [+]                                     }|
1979                                                        |
1980      {5:-- TERMINAL --}                                    |
1981    ]])
1982    feed_data('\027[57418;2u') -- SHIFT + KP_RIGHT
1983    screen:expect([[
1984      0123456789^./*-+                                   |
1985      =                                                 |
1986      {100:~                                                 }|*2
1987      {3:[No Name] [+]                                     }|
1988                                                        |
1989      {5:-- TERMINAL --}                                    |
1990    ]])
1991    feed_data(fn.nr2char(57426)) -- KP_DELETE
1992    screen:expect([[
1993      0123456789^/*-+                                    |
1994      =                                                 |
1995      {100:~                                                 }|*2
1996      {3:[No Name] [+]                                     }|
1997                                                        |
1998      {5:-- TERMINAL --}                                    |
1999    ]])
2000    feed_data(fn.nr2char(57423)) -- KP_HOME
2001    screen:expect([[
2002      ^0123456789/*-+                                    |
2003      =                                                 |
2004      {100:~                                                 }|*2
2005      {3:[No Name] [+]                                     }|
2006                                                        |
2007      {5:-- TERMINAL --}                                    |
2008    ]])
2009    feed_data(fn.nr2char(57424)) -- KP_END
2010    screen:expect([[
2011      0123456789/*-^+                                    |
2012      =                                                 |
2013      {100:~                                                 }|*2
2014      {3:[No Name] [+]                                     }|
2015                                                        |
2016      {5:-- TERMINAL --}                                    |
2017    ]])
2018    child_session:request(
2019      'nvim_exec2',
2020      [[
2021      tab split
2022      tabnew
2023      highlight Tabline ctermbg=NONE ctermfg=NONE cterm=underline
2024    ]],
2025      {}
2026    )
2027    screen:expect([[
2028      {107: + [No Name]  + [No Name] }{5: [No Name] }{2:            }{107:X}|
2029      ^                                                  |
2030      {100:~                                                 }|*2
2031      {3:[No Name]                                         }|
2032                                                        |
2033      {5:-- TERMINAL --}                                    |
2034    ]])
2035    feed_data('\027[57421;5u') -- CTRL + KP_PAGE_UP
2036    screen:expect([[
2037      {107: + [No Name] }{5: + [No Name] }{107: [No Name] }{2:            }{107:X}|
2038      0123456789/*-^+                                    |
2039      =                                                 |
2040      {100:~                                                 }|
2041      {3:[No Name] [+]                                     }|
2042                                                        |
2043      {5:-- TERMINAL --}                                    |
2044    ]])
2045    feed_data('\027[57422;5u') -- CTRL + KP_PAGE_DOWN
2046    screen:expect([[
2047      {107: + [No Name]  + [No Name] }{5: [No Name] }{2:            }{107:X}|
2048      ^                                                  |
2049      {100:~                                                 }|*2
2050      {3:[No Name]                                         }|
2051                                                        |
2052      {5:-- TERMINAL --}                                    |
2053    ]])
2054  end)
2055
2056  it('supports Super and Meta modifiers', function()
2057    feed_data('i')
2058    feed_data('\022\027[106;9u') -- Super + j
2059    feed_data('\022\027[107;33u') -- Meta + k
2060    feed_data('\022\027[13;41u') -- Super + Meta + Enter
2061    feed_data('\022\027[127;48u') -- Shift + Alt + Ctrl + Super + Meta + Backspace
2062    feed_data('\n')
2063    feed_data('\022\027[57376;9u') -- Super + F13
2064    feed_data('\022\027[57377;33u') -- Meta + F14
2065    feed_data('\022\027[57378;41u') -- Super + Meta + F15
2066    feed_data('\022\027[57379;48u') -- Shift + Alt + Ctrl + Super + Meta + F16
2067    screen:expect([[
2068      <D-j><T-k><T-D-CR><M-T-C-S-D-BS>                  |
2069      <D-F13><T-F14><T-D-F15><M-T-C-S-D-F16>^            |
2070      {100:~                                                 }|*2
2071      {3:[No Name] [+]                                     }|
2072      {5:-- INSERT --}                                      |
2073      {5:-- TERMINAL --}                                    |
2074    ]])
2075  end)
2076
2077  it('paste: Insert mode', function()
2078    -- "bracketed paste"
2079    feed_data('i""\027i\027[200~')
2080    screen:expect([[
2081      "^"                                                |
2082      {100:~                                                 }|*3
2083      {3:[No Name] [+]                                     }|
2084      {5:-- INSERT --}                                      |
2085      {5:-- TERMINAL --}                                    |
2086    ]])
2087    feed_data('pasted from terminal')
2088    expect_child_buf_lines({ '"pasted from terminal"' })
2089    screen:expect([[
2090      "pasted from terminal^"                            |
2091      {100:~                                                 }|*3
2092      {3:[No Name] [+]                                     }|
2093      {5:-- INSERT --}                                      |
2094      {5:-- TERMINAL --}                                    |
2095    ]])
2096    feed_data('\027[201~') -- End paste.
2097    poke_both_eventloop()
2098    screen:expect_unchanged()
2099    feed_data('\027[27u') -- ESC: go to Normal mode.
2100    wait_for_mode('n')
2101    screen:expect([[
2102      "pasted from termina^l"                            |
2103      {100:~                                                 }|*3
2104      {3:[No Name] [+]                                     }|
2105                                                        |
2106      {5:-- TERMINAL --}                                    |
2107    ]])
2108    -- Dot-repeat/redo.
2109    feed_data('2.')
2110    expect_child_buf_lines({ '"pasted from terminapasted from terminalpasted from terminall"' })
2111    screen:expect([[
2112      "pasted from terminapasted from terminalpasted fro|
2113      m termina^ll"                                      |
2114      {100:~                                                 }|*2
2115      {3:[No Name] [+]                                     }|
2116                                                        |
2117      {5:-- TERMINAL --}                                    |
2118    ]])
2119    -- Undo.
2120    feed_data('u')
2121    expect_child_buf_lines({ '"pasted from terminal"' })
2122    feed_data('u')
2123    expect_child_buf_lines({ '""' })
2124    feed_data('u')
2125    expect_child_buf_lines({ '' })
2126  end)
2127
2128  it('paste: select-mode', function()
2129    feed_data('ithis is line 1\nthis is line 2\nline 3 is here\n\027')
2130    wait_for_mode('n')
2131    screen:expect([[
2132      this is line 1                                    |
2133      this is line 2                                    |
2134      line 3 is here                                    |
2135      ^                                                  |
2136      {3:[No Name] [+]                                     }|
2137                                                        |
2138      {5:-- TERMINAL --}                                    |
2139    ]])
2140    -- Select-mode. Use <C-n> to move down.
2141    feed_data('gg04lgh\14\14')
2142    screen:expect([[
2143      this{108: is line 1}                                    |
2144      {108:this is line 2}                                    |
2145      {108:line^ }3 is here                                    |
2146                                                        |
2147      {3:[No Name] [+]                                     }|
2148      {5:-- SELECT --}                                      |
2149      {5:-- TERMINAL --}                                    |
2150    ]])
2151    feed_data('\027[200~')
2152    feed_data('just paste it™')
2153    feed_data('\027[201~')
2154    screen:expect([[
2155      thisjust paste it^™3 is here                       |
2156                                                        |
2157      {100:~                                                 }|*2
2158      {3:[No Name] [+]                                     }|
2159                                                        |
2160      {5:-- TERMINAL --}                                    |
2161    ]])
2162    -- Undo.
2163    feed_data('u')
2164    expect_child_buf_lines {
2165      'this is line 1',
2166      'this is line 2',
2167      'line 3 is here',
2168      '',
2169    }
2170    -- Redo.
2171    feed_data('\18') -- <C-r>
2172    expect_child_buf_lines {
2173      'thisjust paste it™3 is here',
2174      '',
2175    }
2176  end)
2177
2178  it('paste: terminal mode', function()
2179    child_exec_lua('vim.o.statusline="^^^^^^^"')
2180    child_exec_lua('vim.fn.jobstart({ ... }, { term = true })', testprg('tty-test'))
2181    feed_data('i')
2182    screen:expect([[
2183      tty ready                                         |
2184      ^                                                  |
2185                                                        |*2
2186      {109:^^^^^^^                                           }|
2187      {5:-- TERMINAL --}                                    |*2
2188    ]])
2189    feed_data('\027[200~')
2190    feed_data('hallo')
2191    feed_data('\027[201~')
2192    screen:expect([[
2193      tty ready                                         |
2194      hallo^                                             |
2195                                                        |*2
2196      {109:^^^^^^^                                           }|
2197      {5:-- TERMINAL --}                                    |*2
2198    ]])
2199  end)
2200
2201  it('paste: normal-mode (+CRLF #10872)', function()
2202    t.skip(is_os('win'), 'FIXME: some spaces have wrong attrs on Windows')
2203    feed_data(':set ruler | echo')
2204    wait_for_mode('c')
2205    feed_data('\n')
2206    wait_for_mode('n')
2207    local expected_lf = { 'line 1', 'ESC:\027 / CR: \rx' }
2208    local expected_crlf = { 'line 1', 'ESC:\027 / CR: ', 'x' }
2209    local expected_grid1 = [[
2210      line 1                                            |
2211      ESC:{104:^[} / CR:                                      |
2212      ^x                                                 |
2213      {100:~                                                 }|
2214      {3:[No Name] [+]                   3,1            All}|
2215                                                        |
2216      {5:-- TERMINAL --}                                    |
2217    ]]
2218    -- "bracketed paste"
2219    feed_data('\027[200~' .. table.concat(expected_lf, '\n') .. '\027[201~')
2220    screen:expect(expected_grid1)
2221    -- Dot-repeat/redo.
2222    feed_data('.')
2223    local expected_grid2 = [[
2224      ESC:{104:^[} / CR:                                      |
2225      xline 1                                           |
2226      ESC:{104:^[} / CR:                                      |
2227      ^x                                                 |
2228      {3:[No Name] [+]                   5,1            Bot}|
2229                                                        |
2230      {5:-- TERMINAL --}                                    |
2231    ]]
2232    screen:expect(expected_grid2)
2233    -- Undo.
2234    feed_data('u')
2235    expect_child_buf_lines(expected_crlf)
2236    feed_data('u')
2237    expect_child_buf_lines({ '' })
2238    feed_data(':echo')
2239    wait_for_mode('c')
2240    feed_data('\n')
2241    wait_for_mode('n')
2242    -- CRLF input
2243    feed_data('\027[200~' .. table.concat(expected_lf, '\r\n') .. '\027[201~')
2244    screen:expect(expected_grid1)
2245    expect_child_buf_lines(expected_crlf)
2246    -- Dot-repeat/redo.
2247    feed_data('.')
2248    screen:expect(expected_grid2)
2249    -- Undo.
2250    feed_data('u')
2251    expect_child_buf_lines(expected_crlf)
2252    feed_data('u')
2253    expect_child_buf_lines({ '' })
2254  end)
2255
2256  it('paste: cmdline-mode inserts 1 line', function()
2257    feed_data('ifoo\n') -- Insert some text (for dot-repeat later).
2258    feed_data('\027:""') -- Enter Cmdline-mode.
2259    feed_data('\027[D') -- <Left> to place cursor between quotes.
2260    wait_for_mode('c')
2261    screen:expect([[
2262      foo                                               |
2263                                                        |
2264      {100:~                                                 }|*2
2265      {3:[No Name] [+]                                     }|
2266      :"^"                                               |
2267      {5:-- TERMINAL --}                                    |
2268    ]])
2269    -- "bracketed paste"
2270    feed_data('\027[200~line 1\nline 2\n')
2271    wait_for_mode('c')
2272    feed_data('line 3\nline 4\n\027[201~')
2273    poke_both_eventloop()
2274    wait_for_mode('c')
2275    screen:expect([[
2276      foo                                               |
2277                                                        |
2278      {100:~                                                 }|*2
2279      {3:[No Name] [+]                                     }|
2280      :"line 1^"                                         |
2281      {5:-- TERMINAL --}                                    |
2282    ]])
2283    -- Dot-repeat/redo.
2284    feed_data('\027[27u')
2285    wait_for_mode('n')
2286    feed_data('.')
2287    screen:expect([[
2288      foo                                               |*2
2289      ^                                                  |
2290      {100:~                                                 }|
2291      {3:[No Name] [+]                                     }|
2292                                                        |
2293      {5:-- TERMINAL --}                                    |
2294    ]])
2295  end)
2296
2297  it('paste: cmdline-mode collects chunks of unfinished line', function()
2298    local function expect_cmdline(expected)
2299      retry(nil, nil, function()
2300        local _, cmdline = child_session:request('nvim_call_function', 'getcmdline', {})
2301        eq(expected, cmdline)
2302        local _, pos = child_session:request('nvim_call_function', 'getcmdpos', {})
2303        eq(#expected, pos) -- Cursor is just before the last char.
2304      end)
2305    end
2306    feed_data('\027:""') -- Enter Cmdline-mode.
2307    feed_data('\027[D') -- <Left> to place cursor between quotes.
2308    expect_cmdline('""')
2309    feed_data('\027[200~stuff 1 ')
2310    expect_cmdline('"stuff 1 "')
2311    -- Discards everything after the first line.
2312    feed_data('more\nstuff 2\nstuff 3\n')
2313    expect_cmdline('"stuff 1 more"')
2314    feed_data('stuff 3')
2315    expect_cmdline('"stuff 1 more"')
2316    -- End the paste sequence.
2317    feed_data('\027[201~')
2318    poke_both_eventloop()
2319    expect_cmdline('"stuff 1 more"')
2320    feed_data(' typed')
2321    expect_cmdline('"stuff 1 more typed"')
2322  end)
2323
2324  it('paste: recovers from vim.paste() failure', function()
2325    child_exec_lua([[
2326      _G.save_paste_fn = vim.paste
2327      -- Stack traces for this test are non-deterministic, so disable them
2328      _G.debug.traceback = function(msg) return msg end
2329      vim.paste = function(lines, phase) error("fake fail") end
2330    ]])
2331    -- Prepare something for dot-repeat/redo.
2332    feed_data('ifoo\n\027[27u')
2333    wait_for_mode('n')
2334    screen:expect([[
2335      foo                                               |
2336      ^                                                  |
2337      {100:~                                                 }|*2
2338      {3:[No Name] [+]                                     }|
2339                                                        |
2340      {5:-- TERMINAL --}                                    |
2341    ]])
2342    -- Start pasting...
2343    feed_data('\027[200~line 1\nline 2\n')
2344    screen:expect([[
2345      foo                                               |
2346      ^                                                  |
2347      {100:~                                                 }|*2
2348      {3:[No Name] [+]                                     }|
2349      {101:paste: Lua: [string "<nvim>"]:4: fake fail}        |
2350      {5:-- TERMINAL --}                                    |
2351    ]])
2352    -- Remaining chunks are discarded after vim.paste() failure.
2353    feed_data('line 3\nline 4\n')
2354    feed_data('line 5\nline 6\n')
2355    feed_data('line 7\nline 8\n')
2356    -- Stop paste.
2357    feed_data('\027[201~')
2358    screen:expect_unchanged()
2359    feed_data('\n') -- <CR> to dismiss hit-enter prompt
2360    expect_child_buf_lines({ 'foo', '' })
2361    -- Dot-repeat/redo is not modified by failed paste.
2362    feed_data('.')
2363    screen:expect([[
2364      foo                                               |*2
2365      ^                                                  |
2366      {100:~                                                 }|
2367      {3:[No Name] [+]                                     }|
2368                                                        |
2369      {5:-- TERMINAL --}                                    |
2370    ]])
2371    -- Editor should still work after failed/drained paste.
2372    feed_data('ityped input...\027[27u')
2373    screen:expect([[
2374      foo                                               |*2
2375      typed input..^.                                    |
2376      {100:~                                                 }|
2377      {3:[No Name] [+]                                     }|
2378                                                        |
2379      {5:-- TERMINAL --}                                    |
2380    ]])
2381    -- Paste works if vim.paste() succeeds.
2382    child_exec_lua([[vim.paste = _G.save_paste_fn]])
2383    feed_data('\027[200~line A\nline B\n\027[201~')
2384    screen:expect([[
2385      foo                                               |
2386      typed input...line A                              |
2387      line B                                            |
2388      ^                                                  |
2389      {3:[No Name] [+]                                     }|
2390                                                        |
2391      {5:-- TERMINAL --}                                    |
2392    ]])
2393  end)
2394
2395  it('paste: vim.paste() cancel (retval=false) #10865', function()
2396    -- This test only exercises the "cancel" case.  Use-case would be "dangling
2397    -- paste", but that is not implemented yet. #10865
2398    child_exec_lua([[
2399      vim.paste = function(lines, phase) return false end
2400    ]])
2401    feed_data('\027[200~line A\nline B\n\027[201~')
2402    expect_child_buf_lines({ '' })
2403    feed_data('ifoo\n\027[27u')
2404    expect_child_buf_lines({ 'foo', '' })
2405  end)
2406
2407  it('paste: vim.paste() cancel (retval=false) with streaming #30462', function()
2408    child_exec_lua([[
2409      vim.paste = (function(overridden)
2410        return function(lines, phase)
2411          for i, line in ipairs(lines) do
2412            if line:find('!') then
2413              return false
2414            end
2415          end
2416          return overridden(lines, phase)
2417        end
2418      end)(vim.paste)
2419    ]])
2420    feed_data('A')
2421    wait_for_mode('i')
2422    feed_data('\027[200~aaa')
2423    expect_child_buf_lines({ 'aaa' })
2424    feed_data('bbb')
2425    expect_child_buf_lines({ 'aaabbb' })
2426    feed_data('ccc!') -- This chunk is cancelled.
2427    expect_child_buf_lines({ 'aaabbb' })
2428    feed_data('ddd\027[201~') -- This chunk is ignored.
2429    poke_both_eventloop()
2430    expect_child_buf_lines({ 'aaabbb' })
2431    feed_data('\027[27u')
2432    wait_for_mode('n')
2433    feed_data('.') -- Dot-repeat only includes chunks actually pasted.
2434    expect_child_buf_lines({ 'aaabbbaaabbb' })
2435    feed_data('$\027[200~eee\027[201~') -- A following paste works normally.
2436    expect_child_buf_lines({ 'aaabbbaaabbbeee' })
2437  end)
2438
2439  it("paste: 'nomodifiable' buffer", function()
2440    tt.override_screen_expect_for_conpty(screen)
2441    child_exec_lua([[
2442      vim.bo.modifiable = false
2443      -- Truncate the error message to hide the line number
2444      _G.debug.traceback = function(msg) return msg:sub(-49) end
2445    ]])
2446    feed_data('\027[200~fail 1\nfail 2\n\027[201~')
2447    screen:expect([[
2448                                                        |
2449      {100:~                                                 }|
2450      {3:                                                  }|
2451      {101:paste: Lua: Vim:E21: Cannot make changes, 'modifia}|
2452      {101:ble' is off}                                       |
2453      {102:Press ENTER or type command to continue}^           |
2454      {5:-- TERMINAL --}                                    |
2455    ]])
2456    feed_data('\n') -- <Enter> to dismiss hit-enter prompt
2457    child_exec_lua('vim.bo.modifiable = true')
2458    feed_data('\027[200~success 1\nsuccess 2\n\027[201~')
2459    screen:expect([[
2460      success 1                                         |
2461      success 2                                         |
2462      ^                                                  |
2463      {100:~                                                 }|
2464      {3:[No Name] [+]                                     }|
2465                                                        |
2466      {5:-- TERMINAL --}                                    |
2467    ]])
2468  end)
2469
2470  it('paste: exactly 64 bytes #10311', function()
2471    local expected = string.rep('z', 64)
2472    feed_data('i')
2473    wait_for_mode('i')
2474    -- "bracketed paste"
2475    feed_data('\027[200~' .. expected .. '\027[201~')
2476    expect_child_buf_lines({ expected })
2477    feed_data(' end')
2478    expected = expected .. ' end'
2479    screen:expect([[
2480      zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz|
2481      zzzzzzzzzzzzzz end^                                |
2482      {100:~                                                 }|*2
2483      {3:[No Name] [+]                                     }|
2484      {5:-- INSERT --}                                      |
2485      {5:-- TERMINAL --}                                    |
2486    ]])
2487    expect_child_buf_lines({ expected })
2488  end)
2489
2490  it('paste: less-than sign in cmdline #11088', function()
2491    local expected = '<'
2492    feed_data(':')
2493    wait_for_mode('c')
2494    -- "bracketed paste"
2495    feed_data('\027[200~' .. expected .. '\027[201~')
2496    screen:expect([[
2497                                                        |
2498      {100:~                                                 }|*3
2499      {3:[No Name]                                         }|
2500      :<^                                                |
2501      {5:-- TERMINAL --}                                    |
2502    ]])
2503  end)
2504
2505  it('paste: big burst of input', function()
2506    feed_data(':set ruler\n')
2507    local q = {}
2508    for i = 1, 3000 do
2509      q[i] = 'item ' .. tostring(i)
2510    end
2511    feed_data('i')
2512    wait_for_mode('i')
2513    -- "bracketed paste"
2514    feed_data('\027[200~' .. table.concat(q, '\n') .. '\027[201~')
2515    expect_child_buf_lines(q)
2516    feed_data(' end')
2517    screen:expect([[
2518      item 2997                                         |
2519      item 2998                                         |
2520      item 2999                                         |
2521      item 3000 end^                                     |
2522      {3:[No Name] [+]                   3000,14        Bot}|
2523      {5:-- INSERT --}                                      |
2524      {5:-- TERMINAL --}                                    |
2525    ]])
2526    feed_data('\027[27u') -- ESC: go to Normal mode.
2527    wait_for_mode('n')
2528    -- Dot-repeat/redo.
2529    feed_data('.')
2530    screen:expect([[
2531      item 2997                                         |
2532      item 2998                                         |
2533      item 2999                                         |
2534      item 3000 en^dd                                    |
2535      {3:[No Name] [+]                   5999,13        Bot}|
2536                                                        |
2537      {5:-- TERMINAL --}                                    |
2538    ]])
2539  end)
2540
2541  it('paste: forwards spurious "start paste" code', function()
2542    -- If multiple "start paste" sequences are sent without a corresponding
2543    -- "stop paste" sequence, only the first occurrence should be consumed.
2544    feed_data('i')
2545    wait_for_mode('i')
2546    -- Send the "start paste" sequence.
2547    feed_data('\027[200~')
2548    feed_data('\npasted from terminal (1)\n')
2549    -- Send spurious "start paste" sequence.
2550    feed_data('\027[200~')
2551    feed_data('\n')
2552    -- Send the "stop paste" sequence.
2553    feed_data('\027[201~')
2554    screen:expect([[
2555                                                        |
2556      pasted from terminal (1)                          |
2557      {104:^[}[200~                                           |
2558      ^                                                  |
2559      {3:[No Name] [+]                                     }|
2560      {5:-- INSERT --}                                      |
2561      {5:-- TERMINAL --}                                    |
2562    ]])
2563  end)
2564
2565  it('paste: ignores spurious "stop paste" code', function()
2566    -- If "stop paste" sequence is received without a preceding "start paste"
2567    -- sequence, it should be ignored.
2568    feed_data('i')
2569    wait_for_mode('i')
2570    -- Send "stop paste" sequence.
2571    feed_data('\027[201~')
2572    screen:expect([[
2573      ^                                                  |
2574      {100:~                                                 }|*3
2575      {3:[No Name]                                         }|
2576      {5:-- INSERT --}                                      |
2577      {5:-- TERMINAL --}                                    |
2578    ]])
2579  end)
2580
2581  it('paste: split "start paste" code', function()
2582    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
2583    feed_data('i')
2584    wait_for_mode('i')
2585    -- Send split "start paste" sequence.
2586    feed_data('\027[2')
2587    feed_data('00~pasted from terminal\027[201~')
2588    screen:expect([[
2589      pasted from terminal^                              |
2590      {100:~                                                 }|*3
2591      {3:[No Name] [+]                                     }|
2592      {5:-- INSERT --}                                      |
2593      {5:-- TERMINAL --}                                    |
2594    ]])
2595  end)
2596
2597  it('paste: split "stop paste" code', function()
2598    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
2599    feed_data('i')
2600    wait_for_mode('i')
2601    -- Send split "stop paste" sequence.
2602    feed_data('\027[200~pasted from terminal\027[20')
2603    feed_data('1~')
2604    screen:expect([[
2605      pasted from terminal^                              |
2606      {100:~                                                 }|*3
2607      {3:[No Name] [+]                                     }|
2608      {5:-- INSERT --}                                      |
2609      {5:-- TERMINAL --}                                    |
2610    ]])
2611  end)
2612
2613  it('paste: streamed paste with isolated "stop paste" code', function()
2614    child_exec_lua([[
2615      _G.paste_phases = {}
2616      vim.paste = (function(overridden)
2617        return function(lines, phase)
2618          table.insert(_G.paste_phases, phase)
2619          overridden(lines, phase)
2620        end
2621      end)(vim.paste)
2622    ]])
2623    feed_data('i')
2624    wait_for_mode('i')
2625    feed_data('\027[200~pasted') -- phase 1
2626    screen:expect([[
2627      pasted^                                            |
2628      {100:~                                                 }|*3
2629      {3:[No Name] [+]                                     }|
2630      {5:-- INSERT --}                                      |
2631      {5:-- TERMINAL --}                                    |
2632    ]])
2633    feed_data(' from terminal') -- phase 2
2634    screen:expect([[
2635      pasted from terminal^                              |
2636      {100:~                                                 }|*3
2637      {3:[No Name] [+]                                     }|
2638      {5:-- INSERT --}                                      |
2639      {5:-- TERMINAL --}                                    |
2640    ]])
2641    -- Send isolated "stop paste" sequence.
2642    feed_data('\027[201~') -- phase 3
2643    poke_both_eventloop()
2644    screen:expect_unchanged()
2645    local rv = child_exec_lua('return _G.paste_phases')
2646    -- In rare cases there may be multiple chunks of phase 2 because of timing.
2647    eq({ 1, 2, 3 }, { rv[1], rv[2], rv[#rv] })
2648  end)
2649
2650  it('allows termguicolors to be set at runtime', function()
2651    tt.override_screen_expect_for_conpty(screen)
2652    screen:set_option('rgb', true)
2653    feed_data(':hi SpecialKey ctermfg=3 guifg=SeaGreen\n')
2654    feed_data('i')
2655    feed_data('\022\007') -- ctrl+g
2656    feed_data('\028\014') -- crtl+\ ctrl+N
2657    feed_data(':set termguicolors?\n')
2658    screen:expect([[
2659      {110:^^G}                                                |
2660      {111:~                                                 }|*3
2661      {3:[No Name] [+]                                     }|
2662      notermguicolors                                   |
2663      {5:-- TERMINAL --}                                    |
2664    ]])
2665
2666    feed_data(':set termguicolors\n')
2667    screen:expect([[
2668      {113:^^G}                                                |
2669      {1:~}{18:                                                 }|*3
2670      {3:[No Name] [+]                                     }|
2671      :set termguicolors                                |
2672      {5:-- TERMINAL --}                                    |
2673    ]])
2674
2675    feed_data(':set notermguicolors\n')
2676    screen:expect([[
2677      {110:^^G}                                                |
2678      {111:~                                                 }|*3
2679      {3:[No Name] [+]                                     }|
2680      :set notermguicolors                              |
2681      {5:-- TERMINAL --}                                    |
2682    ]])
2683  end)
2684
2685  it('forwards :term palette colors with termguicolors', function()
2686    t.skip(is_os('win'), 'FIXME: wrong behavior on Windows')
2687    screen:set_rgb_cterm(true)
2688    screen:set_default_attr_ids({
2689      [1] = { { reverse = true }, { reverse = true } },
2690      [2] = {
2691        { bold = true, background = Screen.colors.LightGreen, foreground = Screen.colors.Black },
2692        { bold = true },
2693      },
2694      [3] = { { bold = true }, { bold = true } },
2695      [4] = { { fg_indexed = true, foreground = tonumber('0xe0e000') }, { foreground = 3 } },
2696      [5] = { { foreground = tonumber('0xff8000') }, {} },
2697      [6] = {
2698        {
2699          fg_indexed = true,
2700          bg_indexed = true,
2701          bold = true,
2702          background = tonumber('0x66ff99'),
2703          foreground = Screen.colors.Black,
2704        },
2705        { bold = true, background = 121, foreground = 0 },
2706      },
2707      [7] = {
2708        {
2709          fg_indexed = true,
2710          bg_indexed = true,
2711          background = tonumber('0x66ff99'),
2712          foreground = Screen.colors.Black,
2713        },
2714        { background = 121, foreground = 0 },
2715      },
2716    })
2717
2718    child_exec_lua('vim.o.statusline="^^^^^^^"')
2719    child_exec_lua('vim.o.termguicolors=true')
2720    child_exec_lua('vim.fn.jobstart({ ... }, { term = true })', testprg('tty-test'))
2721    screen:expect([[
2722      ^tty ready                                         |
2723                                                        |*3
2724      {2:^^^^^^^                                           }|
2725                                                        |
2726      {3:-- TERMINAL --}                                    |
2727    ]])
2728    feed_data(
2729      ':call chansend(&channel, "\\033[38;5;3mtext\\033[38:2:255:128:0mcolor\\033[0;10mtext")\n'
2730    )
2731    screen:expect([[
2732      ^tty ready                                         |
2733      {4:text}{5:color}text                                     |
2734                                                        |*2
2735      {2:^^^^^^^                                           }|
2736                                                        |
2737      {3:-- TERMINAL --}                                    |
2738    ]])
2739
2740    feed_data(':set notermguicolors\n')
2741    screen:expect([[
2742      ^tty ready                                         |
2743      {4:text}colortext                                     |
2744                                                        |*2
2745      {6:^^^^^^^}{7:                                           }|
2746      :set notermguicolors                              |
2747      {3:-- TERMINAL --}                                    |
2748    ]])
2749  end)
2750
2751  -- Note: libvterm doesn't support colored underline or undercurl.
2752  it('supports undercurl and underdouble when run in :terminal', function()
2753    child_session:request('nvim_set_hl', 0, 'Visual', { undercurl = true })
2754    feed_data('ifoobar\027V')
2755    screen:expect([[
2756      {114:fooba^r}                                            |
2757      {100:~                                                 }|*3
2758      {3:[No Name] [+]                                     }|
2759      {5:-- VISUAL LINE --}                                 |
2760      {5:-- TERMINAL --}                                    |
2761    ]])
2762    child_session:request('nvim_set_hl', 0, 'Visual', { underdouble = true })
2763    screen:expect([[
2764      {115:fooba^r}                                            |
2765      {100:~                                                 }|*3
2766      {3:[No Name] [+]                                     }|
2767      {5:-- VISUAL LINE --}                                 |
2768      {5:-- TERMINAL --}                                    |
2769    ]])
2770  end)
2771
2772  it('in nvim_list_uis(), sets nvim_set_client_info()', function()
2773    -- $TERM in :terminal.
2774    local exp_term = (is_os('bsd') or is_os('win') or fn.has('terminfo') == 0) and 'xterm'
2775      or 'xterm-256color'
2776    local ui_chan = 1
2777    local expected = {
2778      {
2779        chan = ui_chan,
2780        ext_cmdline = false,
2781        ext_hlstate = false,
2782        ext_linegrid = true,
2783        ext_messages = false,
2784        ext_multigrid = false,
2785        ext_popupmenu = false,
2786        ext_tabline = false,
2787        ext_termcolors = true,
2788        ext_wildmenu = false,
2789        height = 6,
2790        override = false,
2791        rgb = false,
2792        stdin_tty = true,
2793        stdout_tty = true,
2794        term_background = '',
2795        term_colors = 256,
2796        term_name = exp_term,
2797        width = 50,
2798      },
2799    }
2800    local _, rv = child_session:request('nvim_list_uis')
2801    eq(expected, rv)
2802
2803    ---@type table
2804    local expected_version = child_exec_lua('return vim.version()')
2805    -- vim.version() returns `prerelease` string. Coerce it to boolean.
2806    expected_version.prerelease = not not expected_version.prerelease
2807
2808    local expected_chan_info = {
2809      client = {
2810        attributes = {
2811          license = 'Apache 2',
2812          -- pid = 5371,
2813          website = 'https://neovim.io',
2814        },
2815        methods = {},
2816        name = 'nvim-tui',
2817        type = 'ui',
2818        version = expected_version,
2819      },
2820      id = ui_chan,
2821      mode = 'rpc',
2822      stream = 'stdio',
2823    }
2824
2825    local status, chan_info = child_session:request('nvim_get_chan_info', ui_chan)
2826    ok(status)
2827    local info = chan_info.client
2828    ok(info.attributes.pid and info.attributes.pid > 0, 'PID', info.attributes.pid or 'nil')
2829    ok(info.version.major >= 0)
2830    ok(info.version.minor >= 0)
2831    ok(info.version.patch >= 0)
2832
2833    -- Delete variable fields so we can deep-compare.
2834    info.attributes.pid = nil
2835
2836    eq(expected_chan_info, chan_info)
2837  end)
2838
2839  it('allows grid to assume wider ambiwidth chars than host terminal', function()
2840    tt.override_screen_expect_for_conpty(screen)
2841    child_session:request(
2842      'nvim_buf_set_lines',
2843      0,
2844      0,
2845      -1,
2846      true,
2847      { ('℃'):rep(60), ('℃'):rep(60) }
2848    )
2849    child_session:request('nvim_set_option_value', 'cursorline', true, {})
2850    child_session:request('nvim_set_option_value', 'list', true, {})
2851    child_session:request('nvim_set_option_value', 'listchars', 'eol:$', { win = 0 })
2852    feed_data('gg')
2853    local singlewidth_screen = [[
2854      {107:^℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃}|
2855      {107:℃℃℃℃℃℃℃℃℃℃}{116:$}{107:                                       }|
2856      ℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃℃|
2857      ℃℃℃℃℃℃℃℃℃℃{100:$}                                       |
2858      {3:[No Name] [+]                                     }|
2859                                                        |
2860      {5:-- TERMINAL --}                                    |
2861    ]]
2862    -- When grid assumes "℃" to be double-width but host terminal assumes it to be single-width,
2863    -- the second cell of "℃" is a space and the attributes of the "℃" are applied to it.
2864    local doublewidth_screen = [[
2865      {107:^℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }|
2866      {107:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }|
2867      {107:℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ }{116:$}{107:                             }|
2868      ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ ℃ {100:@@@@}|
2869      {3:[No Name] [+]                                     }|
2870                                                        |
2871      {5:-- TERMINAL --}                                    |
2872    ]]
2873    screen:expect(singlewidth_screen)
2874    child_session:request('nvim_set_option_value', 'ambiwidth', 'double', {})
2875    screen:expect(doublewidth_screen)
2876    child_session:request('nvim_set_option_value', 'ambiwidth', 'single', {})
2877    screen:expect(singlewidth_screen)
2878    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2103, 0x2103, 2 } } })
2879    screen:expect(doublewidth_screen)
2880    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2103, 0x2103, 1 } } })
2881    screen:expect(singlewidth_screen)
2882  end)
2883
2884  it('allows grid to assume wider non-ambiwidth chars than host terminal', function()
2885    tt.override_screen_expect_for_conpty(screen)
2886    child_session:request(
2887      'nvim_buf_set_lines',
2888      0,
2889      0,
2890      -1,
2891      true,
2892      { ('✓'):rep(60), ('✓'):rep(60) }
2893    )
2894    child_session:request('nvim_set_option_value', 'cursorline', true, {})
2895    child_session:request('nvim_set_option_value', 'list', true, {})
2896    child_session:request('nvim_set_option_value', 'listchars', 'eol:$', { win = 0 })
2897    feed_data('gg')
2898    local singlewidth_screen = [[
2899      {107:^✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓}|
2900      {107:✓✓✓✓✓✓✓✓✓✓}{116:$}{107:                                       }|
2901      ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓|
2902      ✓✓✓✓✓✓✓✓✓✓{100:$}                                       |
2903      {3:[No Name] [+]                                     }|
2904                                                        |
2905      {5:-- TERMINAL --}                                    |
2906    ]]
2907    -- When grid assumes "✓" to be double-width but host terminal assumes it to be single-width,
2908    -- the second cell of "✓" is a space and the attributes of the "✓" are applied to it.
2909    local doublewidth_screen = [[
2910      {107:^✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }|
2911      {107:✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }|
2912      {107:✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ }{116:$}{107:                             }|
2913      ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ {100:@@@@}|
2914      {3:[No Name] [+]                                     }|
2915                                                        |
2916      {5:-- TERMINAL --}                                    |
2917    ]]
2918    screen:expect(singlewidth_screen)
2919    child_session:request('nvim_set_option_value', 'ambiwidth', 'double', {})
2920    screen:expect_unchanged()
2921    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2713, 0x2713, 2 } } })
2922    screen:expect(doublewidth_screen)
2923    child_session:request('nvim_set_option_value', 'ambiwidth', 'single', {})
2924    screen:expect_unchanged()
2925    child_session:request('nvim_call_function', 'setcellwidths', { { { 0x2713, 0x2713, 1 } } })
2926    screen:expect(singlewidth_screen)
2927  end)
2928
2929  it('draws correctly when cursor_address overflows #21643', function()
2930    screen:try_resize(70, 333)
2931    retry(nil, nil, function()
2932      eq({ true, 330 }, { child_session:request('nvim_win_get_height', 0) })
2933    end)
2934    child_session:request('nvim_set_option_value', 'cursorline', true, {})
2935    -- Use full screen message so that redrawing afterwards is more deterministic.
2936    child_session:notify('nvim_command', 'intro')
2937    screen:expect({ any = 'Nvim is open source and freely distributable' })
2938    -- Going to top-left corner needs 3 bytes.
2939    -- Setting underline attribute needs 9 bytes.
2940    -- A Ꝩ character takes 3 bytes.
2941    -- The whole line needs 3 + 9 + 3 * 21838 + 3 = 65529 bytes.
2942    -- The cursor_address that comes after will overflow the 65535-byte buffer.
2943    local line = ('Ꝩ'):rep(21838) .. '℃'
2944    child_session:notify('nvim_buf_set_lines', 0, 0, -1, true, { line, 'b' })
2945    -- Close the :intro message and redraw the lines.
2946    feed_data('\n')
2947    screen:expect([[
2948      {107:^ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ}|
2949      {107:ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ}|*310
2950      {107:ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ℃ }|
2951      b                                                                     |
2952      {100:~                                                                     }|*17
2953      {3:[No Name] [+]                                                         }|
2954                                                                            |
2955      {5:-- TERMINAL --}                                                        |
2956    ]])
2957  end)
2958
2959  it('does not split large synchronized TUI output', function()
2960    screen:try_resize(70, 333)
2961    retry(nil, 1000, function()
2962      eq({ true, 330 }, { child_session:request('nvim_win_get_height', 0) })
2963    end)
2964
2965    local dump = t.tmpname()
2966    finally(function()
2967      os.remove(dump)
2968    end)
2969
2970    -- Inform the TUI that synchronized output is supported.
2971    feed_data('\027[?2026;2$y')
2972    poke_both_eventloop()
2973    child_session:request('nvim_set_option_value', 'termsync', true, {})
2974    child_session:request('nvim_buf_set_lines', 0, 0, -1, true, { ('Ꝩ'):rep(21844), 'b' })
2975
2976    child_session:request('nvim__screenshot', dump)
2977    poke_both_eventloop()
2978    local raw = assert(read_file(dump))
2979
2980    local _, starts = raw:gsub('\027%[%?2026h', '')
2981    local _, ends = raw:gsub('\027%[%?2026l', '')
2982    eq({ 1, 1 }, { starts, ends })
2983  end)
2984
2985  it('draws correctly when setting title overflows #30793', function()
2986    screen:try_resize(67, 327)
2987    retry(nil, nil, function()
2988      eq({ true, 324 }, { child_session:request('nvim_win_get_height', 0) })
2989    end)
2990    child_exec_lua([[
2991      vim.o.cmdheight = 0
2992      vim.o.laststatus = 0
2993      vim.o.ruler = false
2994      vim.o.showcmd = false
2995      vim.o.termsync = false
2996      vim.o.titlestring = '%t%( %M%) - Nvim'
2997      vim.o.title = true
2998    ]])
2999    retry(nil, nil, function()
3000      eq('[No Name] - Nvim', api.nvim_buf_get_var(0, 'term_title'))
3001      eq({ true, 326 }, { child_session:request('nvim_win_get_height', 0) })
3002    end)
3003    -- Use full screen message so that redrawing afterwards is more deterministic.
3004    child_session:notify('nvim_command', 'intro')
3005    screen:expect({ any = 'Nvim is open source and freely distributable' })
3006    -- Going to top-left corner needs 3 bytes.
3007    -- A Ꝩ character takes 3 bytes.
3008    -- The whole line needs 3 + 3 * 21842 = 65529 bytes.
3009    -- The title will be updated because the buffer is now modified.
3010    -- The start of the OSC 0 sequence to set title can fit in the 65535-byte buffer,
3011    -- but the title string cannot.
3012    local line = ('Ꝩ'):rep(21842)
3013    child_session:notify('nvim_buf_set_lines', 0, 0, -1, true, { line })
3014    -- Close the :intro message and redraw the lines.
3015    feed_data('\n')
3016    screen:expect([[
3017      ^ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ|
3018      ꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨꝨ|*325
3019      {5:-- TERMINAL --}                                                     |
3020    ]])
3021    retry(nil, nil, function()
3022      eq('[No Name] + - Nvim', api.nvim_buf_get_var(0, 'term_title'))
3023    end)
3024  end)
3025
3026  it('visual bell (padding) does not crash #21610', function()
3027    feed_data ':set visualbell\n'
3028    screen:expect([[
3029      ^                                                  |
3030      {100:~                                                 }|*3
3031      {3:[No Name]                                         }|
3032      :set visualbell                                   |
3033      {5:-- TERMINAL --}                                    |
3034    ]])
3035
3036    -- move left is enough to invoke the bell
3037    feed_data 'h'
3038    -- visual change to show we process events after this
3039    feed_data 'i'
3040    screen:expect([[
3041      ^                                                  |
3042      {100:~                                                 }|*3
3043      {3:[No Name]                                         }|
3044      {5:-- INSERT --}                                      |
3045      {5:-- TERMINAL --}                                    |
3046    ]])
3047  end)
3048
3049  it('no assert failure on deadly signal #21896', function()
3050    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigterm')]])
3051    screen:expect(is_os('win') and { any = '%[Process exited 1%]' } or [[
3052      Nvim: Caught deadly signal 'SIGTERM'              |
3053      ^                                                  |
3054      [Process exited 1]                                |
3055                                                        |*3
3056      {5:-- TERMINAL --}                                    |
3057    ]])
3058  end)
3059
3060  it('exit status 1 and error message with deadly signal sent to server', function()
3061    local _, server_pid = child_session:request('nvim_call_function', 'getpid', {})
3062    exec_lua([[vim.uv.kill(..., 'sigterm')]], server_pid)
3063    if not is_os('win') then
3064      screen:expect({ any = vim.pesc([[Nvim: Caught deadly signal 'SIGTERM']]) })
3065    end
3066    screen:expect({ any = vim.pesc('[Process exited 1]') })
3067  end)
3068
3069  it('exits properly when :quit non-last window in event handler #14379', function()
3070    local code = [[
3071      vim.defer_fn(function()
3072        vim.cmd('vsplit | quit')
3073      end, 0)
3074      vim.cmd('quit')
3075    ]]
3076    child_session:notify('nvim_exec_lua', code, {})
3077    screen:expect([[
3078      ^                                                  |
3079      [Process exited 0]                                |
3080                                                        |*4
3081      {5:-- TERMINAL --}                                    |
3082    ]])
3083  end)
3084
3085  it('no stack-use-after-scope with cursor color #22432', function()
3086    screen:set_option('rgb', true)
3087    command('set termguicolors')
3088    child_session:request(
3089      'nvim_exec2',
3090      [[
3091      set tgc
3092      hi Cursor guifg=Red guibg=Green
3093      set guicursor=n:block-Cursor/lCursor
3094    ]],
3095      {}
3096    )
3097    screen:expect([[
3098      ^                                                  |
3099      {1:~}{18:                                                 }|*3
3100      {3:[No Name]                                         }|
3101                                                        |
3102      {5:-- TERMINAL --}                                    |
3103    ]])
3104    feed_data('i')
3105    screen:expect([[
3106      ^                                                  |
3107      {1:~}{18:                                                 }|*3
3108      {3:[No Name]                                         }|
3109      {5:-- INSERT --}                                      |
3110      {5:-- TERMINAL --}                                    |
3111    ]])
3112  end)
3113
3114  it('redraws on SIGWINCH even if terminal size is unchanged #23411', function()
3115    -- On Windows, SIGWINCH cannot be sent as a signal with uv_kill(), while
3116    -- SIGWINCH handlers are only called on terminal resize.
3117    t.skip(is_os('win'), 'N/A for Windows')
3118    child_session:request('nvim_echo', { { 'foo' } }, false, {})
3119    screen:expect([[
3120      ^                                                  |
3121      {100:~                                                 }|*3
3122      {3:[No Name]                                         }|
3123      foo                                               |
3124      {5:-- TERMINAL --}                                    |
3125    ]])
3126    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigwinch')]])
3127    screen:expect([[
3128      ^                                                  |
3129      {100:~                                                 }|*3
3130      {3:[No Name]                                         }|
3131                                                        |
3132      {5:-- TERMINAL --}                                    |
3133    ]])
3134  end)
3135
3136  it('supports hiding cursor', function()
3137    child_session:request(
3138      'nvim_command',
3139      "let g:id = jobstart([v:progpath, '--clean', '--headless'])"
3140    )
3141    feed_data(':call jobwait([g:id])\n')
3142    screen:expect([[
3143                                                        |
3144      {100:~                                                 }|*3
3145      {3:[No Name]                                         }|
3146      :call jobwait([g:id])                             |
3147      {5:-- TERMINAL --}                                    |
3148    ]])
3149    feed_data('\003')
3150    screen:expect([[
3151      ^                                                  |
3152      {100:~                                                 }|*3
3153      {3:[No Name]                                         }|
3154      Type  :qa  and press <Enter> to exit Nvim         |
3155      {5:-- TERMINAL --}                                    |
3156    ]])
3157  end)
3158
3159  it('cursor is not hidden on incsearch with no match', function()
3160    feed_data('ifoo\027')
3161    feed_data('/foo')
3162    screen:expect([[
3163      {2:foo}                                               |
3164      {100:~                                                 }|*3
3165      {3:[No Name] [+]                                     }|
3166      /foo^                                              |
3167      {5:-- TERMINAL --}                                    |
3168    ]])
3169    screen:sleep(10)
3170    feed_data('b')
3171    screen:expect([[
3172      foo                                               |
3173      {100:~                                                 }|*3
3174      {3:[No Name] [+]                                     }|
3175      /foob^                                             |
3176      {5:-- TERMINAL --}                                    |
3177    ]])
3178    screen:sleep(10)
3179    feed_data('a')
3180    screen:expect([[
3181      foo                                               |
3182      {100:~                                                 }|*3
3183      {3:[No Name] [+]                                     }|
3184      /fooba^                                            |
3185      {5:-- TERMINAL --}                                    |
3186    ]])
3187  end)
3188
3189  it('emits hyperlinks with OSC 8', function()
3190    t.skip(is_os('win'), 'FIXME: does not work on Windows')
3191    exec_lua([[
3192      local buf = vim.api.nvim_get_current_buf()
3193      _G.urls = {}
3194      vim.api.nvim_create_autocmd('TermRequest', {
3195        buf = buf,
3196        callback = function(ev)
3197          local req = ev.data.sequence
3198          if not req then
3199            return
3200          end
3201          local id, url = req:match('\027]8;id=(%d+);(.*)$')
3202          if id ~= nil and url ~= nil then
3203            table.insert(_G.urls, { id = tonumber(id), url = url })
3204          end
3205        end,
3206      })
3207    ]])
3208    child_exec_lua([[
3209      vim.api.nvim_buf_set_lines(0, 0, 0, true, {'Hello'})
3210      _G.NS = vim.api.nvim_create_namespace('test')
3211      vim.api.nvim_buf_set_extmark(0, _G.NS, 0, 1, {
3212        end_col = 3,
3213        url = 'https://example.com',
3214      })
3215    ]])
3216    retry(nil, 1000, function()
3217      eq({ { id = 0xE1EA0000, url = 'https://example.com' } }, exec_lua([[return _G.urls]]))
3218    end)
3219    -- No crash with very long URL #30794
3220    child_exec_lua([[
3221      vim.api.nvim_buf_set_extmark(0, _G.NS, 0, 3, {
3222        end_col = 5,
3223        url = 'https://example.com/' .. ('a'):rep(65536),
3224      })
3225    ]])
3226    retry(nil, nil, function()
3227      eq({
3228        { id = 0xE1EA0000, url = 'https://example.com' },
3229        { id = 0xE1EA0001, url = 'https://example.com/' .. ('a'):rep(65536) },
3230      }, exec_lua([[return _G.urls]]))
3231    end)
3232  end)
3233
3234  it('TermResponse on kitty-multiple-cursors protocol query', function()
3235    child_exec_lua([[
3236      _G.termresponse = nil
3237      vim.api.nvim_create_autocmd('TermResponse', {
3238        once = true,
3239        callback = function(ev)
3240          _G.termresponse = ev.data.sequence
3241        end,
3242      })
3243    ]])
3244    feed_data('\027[>1;2;3;29;30;40;100;101 q')
3245    retry(nil, nil, function()
3246      eq('\027[>1;2;3;29;30;40;100;101 q', child_exec_lua('return _G.termresponse'))
3247    end)
3248  end)
3249
3250  it('TermResponse works with vim.wait() from another autocommand #32706', function()
3251    child_exec_lua([[
3252      _G.termresponse = nil
3253      vim.api.nvim_create_autocmd('TermResponse', {
3254        callback = function(ev)
3255          _G.sequence = ev.data.sequence
3256          _G.v_termresponse = vim.v.termresponse
3257        end,
3258      })
3259      vim.api.nvim_create_autocmd('InsertEnter', {
3260        buf = 0,
3261        callback = function()
3262          _G.result = vim.wait(3000, function()
3263            local expected = '\027P1+r5463'
3264            return _G.sequence == expected and _G.v_termresponse == expected
3265          end)
3266        end,
3267      })
3268    ]])
3269    feed_data('i')
3270    feed_data('\027P1+r5463\027\\')
3271    retry(nil, 4000, function()
3272      eq(true, child_exec_lua('return _G.result'))
3273    end)
3274  end)
3275
3276  it('TermResponse from unblock_autocmds() sets "data"', function()
3277    if not child_exec_lua('return pcall(require, "ffi")') then
3278      pending('N/A: missing LuaJIT FFI')
3279    end
3280    child_exec_lua([[
3281      local ffi = require('ffi')
3282      ffi.cdef[=[
3283        void block_autocmds(void);
3284        void unblock_autocmds(void);
3285      ]=]
3286      ffi.C.block_autocmds()
3287      vim.api.nvim_create_autocmd('TermResponse', {
3288        once = true,
3289        callback = function(ev)
3290          _G.data = ev.data
3291        end,
3292      })
3293    ]])
3294    local chan = child_exec_lua('return vim.api.nvim_list_uis()[1].chan')
3295    feed_data('\027P0$r\027\\')
3296    retry(nil, 4000, function()
3297      eq('\027P0$r', child_exec_lua('return vim.v.termresponse'))
3298    end)
3299    eq(vim.NIL, child_exec_lua('return _G.data'))
3300    child_exec_lua('require("ffi").C.unblock_autocmds()')
3301    eq({ sequence = '\027P0$r', chan = chan }, child_exec_lua('return _G.data'))
3302
3303    -- If TermResponse during TermResponse changes v:termresponse, data.sequence contains the actual
3304    -- response that triggered the autocommand.
3305    -- The second autocommand below forces a use-after-free when v:termresponse's value changes
3306    -- during TermResponse if data.sequence didn't allocate its own copy.
3307    child_exec_lua([[
3308      require('ffi').C.block_autocmds()
3309      vim.api.nvim_create_autocmd('TermResponse', {
3310        once = true,
3311        callback = function(ev)
3312          _G.au1_termresponse1 = vim.v.termresponse
3313          _G.au1_sequence1 = ev.data.sequence
3314          local chan = vim.fn.sockconnect('pipe', vim.v.servername, { rpc = true })
3315          vim.rpcrequest(chan, 'nvim_ui_term_event', 'termresponse', 'baz')
3316          _G.au1_termresponse2 = vim.v.termresponse
3317          _G.au1_sequence2 = ev.data.sequence
3318        end,
3319      })
3320      _G.au2_sequences = {}
3321      vim.api.nvim_create_autocmd('TermResponse', {
3322        callback = function(ev)
3323          table.insert(_G.au2_sequences, ev.data.sequence)
3324        end,
3325      })
3326    ]])
3327    child_session:request('nvim_ui_term_event', 'termresponse', 'foobar')
3328    eq('foobar', child_exec_lua('return vim.v.termresponse'))
3329    -- For good measure, check deferred TermResponse doesn't try to fire if autocmds are still
3330    -- blocked after unblock_autocmds.
3331    child_exec_lua('require("ffi").C.block_autocmds() require("ffi").C.unblock_autocmds()')
3332    eq(vim.NIL, child_exec_lua('return _G.au1_termresponse1'))
3333    child_exec_lua('require("ffi").C.unblock_autocmds()')
3334    eq('foobar', child_exec_lua('return _G.au1_termresponse1'))
3335    eq('foobar', child_exec_lua('return _G.au1_sequence1'))
3336    eq('baz', child_exec_lua('return _G.au1_termresponse2'))
3337    eq('foobar', child_exec_lua('return _G.au1_sequence2')) -- unchanged
3338    -- Second autocmd triggers due to "baz" (via the nested TermResponse), then from "foobar".
3339    eq({ 'baz', 'foobar' }, child_exec_lua('return _G.au2_sequences'))
3340  end)
3341
3342  it('nvim_ui_send works', function()
3343    child_session:request('nvim_ui_send', '\027]2;TEST_TITLE\027\\')
3344    retry(nil, nil, function()
3345      eq('TEST_TITLE', api.nvim_buf_get_var(0, 'term_title'))
3346    end)
3347  end)
3348
3349  it('stdin and stdout are tty fds in embedded server #38172', function()
3350    eq(
3351      { 'tty', 'tty' },
3352      child_exec_lua('return { vim.uv.guess_handle(0), vim.uv.guess_handle(1) }')
3353    )
3354    -- Also works after :restart! #38745
3355    feed_data(':restart! lua ={ vim.uv.guess_handle(0), vim.uv.guess_handle(1) }\r')
3356    screen:expect([[
3357      ^                                                  |
3358      {100:~                                                 }|*3
3359      {3:[No Name]                                         }|
3360      { "tty", "tty" }                                  |
3361      {5:-- TERMINAL --}                                    |
3362    ]])
3363    -- The server is now detached and needs to be quit explicitly.
3364    feed_data(':qall!\r')
3365    screen:expect({ any = vim.pesc('[Process exited 0]') })
3366  end)
3367end)
3368
3369describe('TUI', function()
3370  before_each(clear)
3371
3372  it('resize at startup #17285 #15044 #11330', function()
3373    local screen = Screen.new(50, 10)
3374    screen:add_extra_attr_ids({
3375      [100] = { foreground = tonumber('0x4040ff'), fg_indexed = true },
3376      [101] = { foreground = Screen.colors.Gray100, background = Screen.colors.DarkGreen },
3377    })
3378    fn.jobstart({
3379      nvim_prog,
3380      '--clean',
3381      '--cmd',
3382      'colorscheme vim',
3383      '--cmd',
3384      'set notermguicolors',
3385      '--cmd',
3386      nvim_set,
3387      '--cmd',
3388      'let start = reltime() | while v:true | if reltimefloat(reltime(start)) > 2 | break | endif | endwhile',
3389    }, {
3390      term = true,
3391      env = {
3392        VIMRUNTIME = os.getenv('VIMRUNTIME'),
3393      },
3394    })
3395    exec([[
3396      sleep 500m
3397      vs new
3398    ]])
3399    screen:expect(([[
3400      ^                         │                        |
3401      {1:~                        }│{100:~                       }|*6
3402      {1:~                        }│                        |
3403      {3:new                       }{101:{MATCH:<.*%s} [-] }|
3404                                                        |
3405    ]]):format(is_os('win') and '[/\\]nvim%.exe' or '/nvim'))
3406  end)
3407
3408  -- #28667, #28668
3409  for _, guicolors in ipairs({ 'notermguicolors', 'termguicolors' }) do
3410    it('has no black flicker when clearing regions during startup with ' .. guicolors, function()
3411      local screen = Screen.new(50, 10)
3412      -- Colorscheme is automatically detected as light in _core/defaults.lua, so fg
3413      -- should be dark except on Windows, where it doesn't respond to the OSC11 query,
3414      -- so bg is dark.
3415      local fg = is_os('win') and Screen.colors.NvimLightGrey2 or Screen.colors.NvimDarkGrey2
3416      local bg = is_os('win') and Screen.colors.NvimDarkGrey2 or Screen.colors.NvimLightGrey2
3417      screen:add_extra_attr_ids({
3418        [100] = {
3419          foreground = fg,
3420          background = bg,
3421        },
3422      })
3423      fn.jobstart({
3424        nvim_prog,
3425        '--clean',
3426        '--cmd',
3427        'set ' .. guicolors,
3428        '--cmd',
3429        'echo "foo"',
3430        '--cmd',
3431        'sleep 10',
3432      }, {
3433        term = true,
3434        env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
3435      })
3436      if guicolors == 'termguicolors' then
3437        screen:expect([[
3438          {100:^                                                  }|
3439          {100:                                                  }|*7
3440          {100:foo                                               }|
3441                                                            |
3442        ]])
3443      else
3444        screen:expect([[
3445          ^                                                  |
3446                                                            |*7
3447          foo                                               |
3448                                                            |
3449        ]])
3450      end
3451    end)
3452  end
3453
3454  it('argv[0] can be overridden #23953', function()
3455    t.skip(is_os('win'), 'N/A for Windows')
3456    t.skip(t.is_arch('s390x'), 'FIXME s390x')
3457    local screen = Screen.new(50, 7, { rgb = false })
3458    fn.jobstart(
3459      { testprg('shell-test'), 'EXECVP', nvim_prog, 'Xargv0nvim', '--clean' },
3460      { term = true, env = { VIMRUNTIME = os.getenv('VIMRUNTIME') } }
3461    )
3462    command('startinsert')
3463    screen:expect([[
3464      ^                                                  |
3465      ~                                                 |*3
3466      [No Name]                       0,0-1          All|
3467                                                        |
3468      {5:-- TERMINAL --}                                    |
3469    ]])
3470    feed_data(':put =v:argv + [v:progname]\n')
3471    screen:expect([[
3472      Xargv0nvim                                        |
3473      --embed                                           |
3474      --clean                                           |
3475      ^Xargv0nvim                                        |
3476      [No Name] [+]                   5,1            Bot|
3477      4 more lines                                      |
3478      {5:-- TERMINAL --}                                    |
3479    ]])
3480  end)
3481
3482  it("float is still highlighted with 'winblend' over uninitialized cells #34360", function()
3483    write_file(
3484      'Xblend.lua',
3485      [[
3486        local win = vim.api.nvim_open_win(0, false, { relative = 'editor', width = 3, height = 1, row = 1000, col = 0, zindex = 400 })
3487        vim.api.nvim_set_option_value('winblend', 30, { win = win })
3488        vim.fn.setline(1, "foo")
3489        vim.api.nvim_buf_set_extmark(0, vim.api.nvim_create_namespace(''), 0, 0, { end_col = 3, hl_group = 'Title' })
3490    ]]
3491    )
3492    finally(function()
3493      os.remove('Xblend.lua')
3494    end)
3495    local screen = tt.setup_child_nvim({ '--clean', '-u', 'Xblend.lua' })
3496    screen:expect([[
3497      {5:^foo}                                               |
3498      ~                                                 |*3
3499      [No Name] [+]                   1,1            All|
3500      {5:foo}                                               |
3501      {5:-- TERMINAL --}                                    |
3502    ]])
3503  end)
3504
3505  it('with non-tty (pipe) stdout/stderr', function()
3506    t.skip(is_os('win'), 'N/A for Windows')
3507    finally(function()
3508      os.remove('testF')
3509      os.remove(testlog)
3510    end)
3511    local screen = tt.setup_screen(
3512      0,
3513      ('"%s" --clean --cmd "set noswapfile noshowcmd noruler" --cmd "normal iabc" > /dev/null 2>&1 && cat testF && rm testF'):format(
3514        nvim_prog
3515      ),
3516      nil,
3517      { VIMRUNTIME = os.getenv('VIMRUNTIME'), NVIM_LOG_FILE = testlog }
3518    )
3519    feed_data(':w testF\n:q\n')
3520    screen:expect([[
3521      :w testF                                          |
3522      :q                                                |
3523      abc                                               |
3524      ^                                                  |
3525      [Process exited 0]                                |
3526                                                        |
3527      {5:-- TERMINAL --}                                    |
3528    ]])
3529    assert_log('TUI: timed out waiting for DA1 response', testlog)
3530  end)
3531
3532  it('<C-h> #10134', function()
3533    local screen = tt.setup_child_nvim({
3534      '--clean',
3535      '--cmd',
3536      'colorscheme vim',
3537      '--cmd',
3538      'set noruler',
3539      '--cmd',
3540      ':nnoremap <C-h> :echomsg "\\<C-h\\>"<CR>',
3541    }, { env = env_notermguicolors })
3542    screen:expect([[
3543      ^                                                  |
3544      {100:~                                                 }|*3
3545      {3:[No Name]                                         }|
3546                                                        |
3547      {5:-- TERMINAL --}                                    |
3548    ]])
3549
3550    command([[call chansend(b:terminal_job_id, "\<C-h>")]])
3551    screen:expect([[
3552      ^                                                  |
3553      {100:~                                                 }|*3
3554      {3:[No Name]                                         }|
3555      <C-h>                                             |
3556      {5:-- TERMINAL --}                                    |
3557    ]])
3558  end)
3559
3560  it('draws line with many trailing spaces correctly #24955', function()
3561    local screen = tt.setup_child_nvim({
3562      '--clean',
3563      '--cmd',
3564      'colorscheme vim',
3565      '--cmd',
3566      'call setline(1, ["1st line" .. repeat(" ", 153), "2nd line"])',
3567    }, { cols = 80, env = env_notermguicolors })
3568    screen:expect([[
3569      ^1st line                                                                        |
3570                                                                                      |*2
3571      2nd line                                                                        |
3572      {3:[No Name] [+]                                                 1,1            All}|
3573                                                                                      |
3574      {5:-- TERMINAL --}                                                                  |
3575    ]])
3576    feed_data('$')
3577    screen:expect([[
3578      1st line                                                                        |
3579                                                                                      |
3580      ^                                                                                |
3581      2nd line                                                                        |
3582      {3:[No Name] [+]                                                 1,161          All}|
3583                                                                                      |
3584      {5:-- TERMINAL --}                                                                  |
3585    ]])
3586  end)
3587
3588  it('draws screen lines with leading spaces correctly #29711', function()
3589    local screen = tt.setup_child_nvim({
3590      '--clean',
3591      '--cmd',
3592      'set foldcolumn=6 | call setline(1, ["", repeat("aabb", 1000)]) | echo 42',
3593    }, { extra_rows = 10, cols = 66 })
3594    screen:expect([[
3595            ^                                                            |
3596            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabb|*12
3597            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba@@@|
3598      [No Name] [+]                                   1,0-1          Top|
3599      42                                                                |
3600      {5:-- TERMINAL --}                                                    |
3601    ]])
3602    feed_data('\12') -- Ctrl-L
3603    -- The first line counts as 3 cells.
3604    -- For the second line, 6 repeated spaces at the start counts as 2 cells,
3605    -- so each screen line of the second line counts as 62 cells.
3606    -- After drawing the first line and 8 screen lines of the second line,
3607    -- 3 + 8 * 62 = 499 cells have been counted.
3608    -- The 6 repeated spaces at the start of the next screen line exceeds the
3609    -- 500-cell limit, so the buffer is flushed after these spaces.
3610    screen:expect([[
3611            ^                                                            |
3612            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabb|*12
3613            aabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabbaabba@@@|
3614      [No Name] [+]                                   1,0-1          Top|
3615                                                                        |
3616      {5:-- TERMINAL --}                                                    |
3617    ]])
3618  end)
3619
3620  it('no heap-buffer-overflow when changing &columns', function()
3621    t.skip(is_os('win'), 'FIXME: does not work on Windows')
3622    -- Set a different bg colour and change $TERM to something dumber so the `print_spaces()`
3623    -- codepath in `clear_region()` is hit.
3624    local screen = tt.setup_child_nvim({
3625      '--clean',
3626      '--cmd',
3627      'set notermguicolors | highlight Normal ctermbg=red',
3628      '--cmd',
3629      'call setline(1, ["a"->repeat(&columns)])',
3630    }, { env = { TERM = 'ansi' } })
3631
3632    screen:expect([[
3633      {117:^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}|
3634      {117:~                                                 }|*3
3635      {118:[No Name] [+]                   1,1            All}|
3636      {117:                                                  }|
3637      {5:-- TERMINAL --}                                    |
3638    ]])
3639
3640    feed_data(':set columns=12\n')
3641    screen:expect([[
3642      {117:^aaaaaaaaaaaa                                      }|
3643      {117:aaaaaaaaaaaa                                      }|*3
3644      {118:<        All}{117:                                      }|
3645      {117:                                                  }|
3646      {5:-- TERMINAL --}                                    |
3647    ]])
3648
3649    -- Wider than TUI, so screen state will look weird.
3650    -- Wait for the statusline to redraw to confirm that the TUI lives and ASAN is happy.
3651    feed_data(':set columns=99|set stl=redrawn%m\n')
3652    screen:expect({ any = 'redrawn%[%+%]' })
3653  end)
3654
3655  it('missing DSR response does not lead to hit-enter prompt #38877', function()
3656    local child_server = n.new_pipename()
3657    exec_lua('vim.uv.os_unsetenv("NVIM_TEST")')
3658    local job = fn.jobstart({ nvim_prog, '--clean', '--listen', child_server }, {
3659      -- Use pty = true for a PTY without a terminal, so that there is no DSR response.
3660      pty = true,
3661      env = {
3662        VIMRUNTIME = os.getenv('VIMRUNTIME'),
3663        COLORTERM = 'xterm-256color',
3664        NVIM_LOG_FILE = testlog,
3665      },
3666    })
3667    finally(function()
3668      exec_lua(function()
3669        vim.fn.jobstop(job)
3670        vim.fn.jobwait({ job }, 5000)
3671      end)
3672      os.remove(testlog)
3673    end)
3674    retry(nil, nil, function()
3675      t.neq(nil, vim.uv.fs_stat(child_server))
3676    end)
3677    local child_session = n.connect(child_server)
3678    local expected_msg =
3679      "E1568: Terminal did not respond to DSR request for 'background' color. Startup may be slower. :help 'ttyfast'"
3680    retry(nil, 4000, function()
3681      eq({ true, { mode = 'n', blocking = false } }, { child_session:request('nvim_get_mode') })
3682      if not is_os('win') then -- ConPTY provides DSR response on Windows?
3683        eq(
3684          { true, { output = expected_msg } },
3685          { child_session:request('nvim_exec2', 'messages', { output = true }) }
3686        )
3687      end
3688    end)
3689  end)
3690
3691  it('exits immediately when stdin is closed #35744', function()
3692    local screen = tt.setup_child_nvim(
3693      { '--clean', '--cmd', 'set laststatus=2' },
3694      { env = vim.tbl_extend('force', env_notermguicolors, { NVIM_LOG_FILE = testlog }) }
3695    )
3696    finally(function()
3697      os.remove(testlog)
3698    end)
3699    screen:expect({ any = '%[No Name%]' })
3700
3701    local chan = api.nvim_get_option_value('channel', { buf = 0 })
3702    local pid = fn.jobpid(chan)
3703    fn.chanclose(chan)
3704    -- On Windows the console terminates the child with STATUS_CONTROL_C_EXIT (-1073741510).
3705    screen:expect({
3706      any = is_os('win') and '%[Process exited %-?%d+%]' or '%[Process exited 1%]',
3707    })
3708    -- Closing stdin must skip the DA1 wait.
3709    t.assert_nolog('timed out waiting for DA1 response', testlog, 100)
3710    eq(vim.NIL, api.nvim_get_proc(pid))
3711  end)
3712end)
3713
3714describe('TUI UIEnter/UILeave', function()
3715  it('fires exactly once, after VimEnter', function()
3716    clear()
3717    local screen = tt.setup_child_nvim({
3718      '--clean',
3719      '--cmd',
3720      'colorscheme vim',
3721      '--cmd',
3722      'set noswapfile noshowcmd noruler',
3723      '--cmd',
3724      'let g:evs = []',
3725      '--cmd',
3726      'autocmd UIEnter *  :call add(g:evs, "UIEnter")',
3727      '--cmd',
3728      'autocmd UILeave *  :call add(g:evs, "UILeave")',
3729      '--cmd',
3730      'autocmd VimEnter * :call add(g:evs, "VimEnter")',
3731    }, { env = env_notermguicolors })
3732    screen:expect([[
3733      ^                                                  |
3734      {100:~                                                 }|*3
3735      {3:[No Name]                                         }|
3736                                                        |
3737      {5:-- TERMINAL --}                                    |
3738    ]])
3739    feed_data(':echo g:evs\n')
3740    screen:expect([[
3741      ^                                                  |
3742      {100:~                                                 }|*3
3743      {3:[No Name]                                         }|
3744      ['VimEnter', 'UIEnter']                           |
3745      {5:-- TERMINAL --}                                    |
3746    ]])
3747  end)
3748end)
3749
3750describe('TUI FocusGained/FocusLost', function()
3751  local screen --[[@type test.functional.ui.screen]]
3752  local child_session --[[@type test.Session]]
3753
3754  before_each(function()
3755    clear()
3756    local child_server = new_pipename()
3757    screen = tt.setup_child_nvim({
3758      '--listen',
3759      child_server,
3760      '-u',
3761      'NONE',
3762      '-i',
3763      'NONE',
3764      '--cmd',
3765      'colorscheme vim',
3766      '--cmd',
3767      'set noswapfile noshowcmd noruler background=dark',
3768    }, { env = env_notermguicolors })
3769
3770    screen:expect([[
3771      ^                                                  |
3772      {100:~                                                 }|*3
3773      {3:[No Name]                                         }|
3774                                                        |
3775      {5:-- TERMINAL --}                                    |
3776    ]])
3777    child_session = n.connect(child_server)
3778    child_session:request(
3779      'nvim_exec2',
3780      [[
3781      autocmd FocusGained * echo 'gained'
3782      autocmd FocusLost * echo 'lost'
3783    ]],
3784      {}
3785    )
3786    feed_data('\034\016') -- CTRL-\ CTRL-N
3787  end)
3788
3789  it('in normal-mode', function()
3790    retry(2, 3 * screen.timeout, function()
3791      feed_data('\027[I')
3792      screen:expect([[
3793        ^                                                  |
3794        {100:~                                                 }|*3
3795        {3:[No Name]                                         }|
3796        gained                                            |
3797        {5:-- TERMINAL --}                                    |
3798      ]])
3799
3800      feed_data('\027[O')
3801      screen:expect([[
3802        ^                                                  |
3803        {100:~                                                 }|*3
3804        {3:[No Name]                                         }|
3805        lost                                              |
3806        {5:-- TERMINAL --}                                    |
3807      ]])
3808    end)
3809  end)
3810
3811  it('in insert-mode', function()
3812    feed_data(':set noshowmode\r')
3813    feed_data('i')
3814    screen:expect([[
3815      ^                                                  |
3816      {100:~                                                 }|*3
3817      {3:[No Name]                                         }|
3818      :set noshowmode                                   |
3819      {5:-- TERMINAL --}                                    |
3820    ]])
3821    retry(2, 3 * screen.timeout, function()
3822      feed_data('\027[I')
3823      screen:expect([[
3824        ^                                                  |
3825        {100:~                                                 }|*3
3826        {3:[No Name]                                         }|
3827        gained                                            |
3828        {5:-- TERMINAL --}                                    |
3829      ]])
3830      feed_data('\027[O')
3831      screen:expect([[
3832        ^                                                  |
3833        {100:~                                                 }|*3
3834        {3:[No Name]                                         }|
3835        lost                                              |
3836        {5:-- TERMINAL --}                                    |
3837      ]])
3838    end)
3839  end)
3840
3841  -- During cmdline-mode we ignore :echo invoked by timers/events.
3842  -- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
3843  it('in cmdline-mode does NOT :echo', function()
3844    feed_data(':')
3845    feed_data('\027[I')
3846    screen:expect([[
3847                                                        |
3848      {100:~                                                 }|*3
3849      {3:[No Name]                                         }|
3850      :^                                                 |
3851      {5:-- TERMINAL --}                                    |
3852    ]])
3853    feed_data('\027[O')
3854    screen:expect_unchanged()
3855  end)
3856
3857  it('in cmdline-mode', function()
3858    -- Set up autocmds that modify the buffer, instead of just calling :echo.
3859    -- This is how we can test handling of focus gained/lost during cmdline-mode.
3860    -- See commit: 5cc87d4dabd02167117be7a978b5c8faaa975419.
3861    child_session:request(
3862      'nvim_exec2',
3863      [[
3864      autocmd!
3865      autocmd FocusLost * call append(line('$'), 'lost')
3866      autocmd FocusGained * call append(line('$'), 'gained')
3867    ]],
3868      {}
3869    )
3870    retry(2, 3 * screen.timeout, function()
3871      -- Enter cmdline-mode.
3872      feed_data(':')
3873      screen:sleep(1)
3874      -- Send focus lost/gained termcodes.
3875      feed_data('\027[O')
3876      feed_data('\027[I')
3877      screen:sleep(1)
3878      -- Exit cmdline-mode. Redraws from timers/events are blocked during
3879      -- cmdline-mode, so the buffer won't be updated until we exit cmdline-mode.
3880      feed_data('\n')
3881      screen:expect { any = 'lost' .. (' '):rep(46) .. '|\ngained' }
3882    end)
3883  end)
3884
3885  it('in terminal-mode', function()
3886    feed_data(':set shell=' .. testprg('shell-test') .. ' shellcmdflag=EXE\n')
3887    feed_data(':set shellxquote=\n') -- win: avoid extra quotes
3888    feed_data(':set noshowmode laststatus=0\n')
3889
3890    feed_data(':terminal zia\n')
3891    -- Wait for terminal to be ready.
3892    screen:expect([[
3893      ^ready $ zia                                       |
3894                                                        |
3895      [Process exited 0]                                |
3896                                                        |*2
3897      :terminal zia                                     |
3898      {5:-- TERMINAL --}                                    |
3899    ]])
3900
3901    feed_data('\027[I')
3902    screen:expect {
3903      grid = [[
3904      ^ready $ zia                                       |
3905                                                        |
3906      [Process exited 0]                                |
3907                                                        |*2
3908      gained                                            |
3909      {5:-- TERMINAL --}                                    |
3910    ]],
3911      timeout = (4 * screen.timeout),
3912    }
3913
3914    feed_data('\027[O')
3915    screen:expect([[
3916      ^ready $ zia                                       |
3917                                                        |
3918      [Process exited 0]                                |
3919                                                        |*2
3920      lost                                              |
3921      {5:-- TERMINAL --}                                    |
3922    ]])
3923  end)
3924
3925  it('in hit-enter prompt', function()
3926    tt.override_screen_expect_for_conpty(screen)
3927    feed_data(":echom 'msg1'|echom 'msg2'|echom 'msg3'|echom 'msg4'|echom 'msg5'\n")
3928    screen:expect([[
3929      msg1                                              |
3930      msg2                                              |
3931      msg3                                              |
3932      msg4                                              |
3933      msg5                                              |
3934      {102:Press ENTER or type command to continue}^           |
3935      {5:-- TERMINAL --}                                    |
3936    ]])
3937    feed_data('\027[I')
3938    feed_data('\027[I')
3939    screen:expect_unchanged()
3940  end)
3941end)
3942
3943-- These tests require `tt` because --headless/--embed does not initialize the TUI.
3944describe("TUI 't_Co' (terminal colors)", function()
3945  local screen --[[@type test.functional.ui.screen]]
3946
3947  local function assert_term_colors(term, colorterm, maxcolors, builtin_maxcolors)
3948    clear({ env = { TERM = term }, args = {} })
3949    if builtin_maxcolors and (is_os('freebsd') or is_os('win') or fn.has('terminfo') == 0) then
3950      maxcolors = builtin_maxcolors
3951    end
3952    screen = tt.setup_child_nvim({
3953      '--clean',
3954      '--cmd',
3955      'colorscheme vim',
3956      '--cmd',
3957      nvim_set .. ' notermguicolors',
3958    }, {
3959      env = {
3960        LANG = 'C',
3961        TERM = term or '',
3962        COLORTERM = colorterm or '',
3963      },
3964    })
3965
3966    local tline --[[@type string]]
3967    if maxcolors == 8 then
3968      tline = '{112:~                                                 }'
3969    elseif maxcolors == 16 then
3970      tline = '~                                                 '
3971    else
3972      tline = '{100:~                                                 }'
3973    end
3974
3975    screen:expect(string.format(
3976      [[
3977      ^                                                  |
3978      %s|*4
3979                                                        |
3980      {5:-- TERMINAL --}                                    |
3981    ]],
3982      tline
3983    ))
3984
3985    feed_data(':echo &t_Co\n')
3986    screen:expect(string.format(
3987      [[
3988      ^                                                  |
3989      %s|*4
3990      %-3s                                               |
3991      {5:-- TERMINAL --}                                    |
3992    ]],
3993      tline,
3994      tostring(maxcolors and maxcolors or '')
3995    ))
3996  end
3997
3998  -- ansi and no terminal type at all:
3999
4000  if is_os('win') then
4001    it('guessed vtpcon with no TERM uses 256 colors', function()
4002      assert_term_colors(nil, nil, 256)
4003    end)
4004  else
4005    it('no TERM uses 8 colors', function()
4006      assert_term_colors(nil, nil, 8)
4007    end)
4008  end
4009
4010  it('TERM=ansi no COLORTERM uses 8 colors', function()
4011    assert_term_colors('ansi', nil, 8)
4012  end)
4013
4014  it('TERM=ansi with COLORTERM=anything-no-number uses 16 colors', function()
4015    assert_term_colors('ansi', 'yet-another-term', 16)
4016  end)
4017
4018  it('unknown TERM COLORTERM with 256 in name uses 256 colors', function()
4019    assert_term_colors('ansi', 'yet-another-term-256color', 256)
4020  end)
4021
4022  it('TERM=ansi-256color sets 256 colours', function()
4023    assert_term_colors('ansi-256color', nil, 256)
4024  end)
4025
4026  -- Unknown terminal types:
4027
4028  it('unknown TERM no COLORTERM sets 8 colours', function()
4029    assert_term_colors('yet-another-term', nil, 8)
4030  end)
4031
4032  it('unknown TERM with COLORTERM=anything-no-number uses 16 colors', function()
4033    assert_term_colors('yet-another-term', 'yet-another-term', 16)
4034  end)
4035
4036  it('unknown TERM with 256 in name sets 256 colours', function()
4037    assert_term_colors('yet-another-term-256color', nil, 256)
4038  end)
4039
4040  it('unknown TERM COLORTERM with 256 in name uses 256 colors', function()
4041    assert_term_colors('yet-another-term', 'yet-another-term-256color', 256)
4042  end)
4043
4044  -- Linux kernel terminal emulator:
4045
4046  it('TERM=linux uses 256 colors', function()
4047    assert_term_colors('linux', nil, 256)
4048  end)
4049
4050  it('TERM=linux-16color uses 256 colors', function()
4051    assert_term_colors('linux-16color', nil, 256)
4052  end)
4053
4054  it('TERM=linux-256color uses 256 colors', function()
4055    assert_term_colors('linux-256color', nil, 256)
4056  end)
4057
4058  -- screen:
4059  --
4060  -- FreeBSD/Windows (any build without terminfo) fall back to built-in "screen-256colour".
4061  -- Linux/MacOS have a screen entry in external terminfo with 8 colours, raised to 16 by COLORTERM.
4062
4063  it('TERM=screen no COLORTERM uses 8/256 colors', function()
4064    assert_term_colors('screen', nil, 8, 256)
4065  end)
4066
4067  it('TERM=screen COLORTERM=screen uses 16/256 colors', function()
4068    assert_term_colors('screen', 'screen', 16, 256)
4069  end)
4070
4071  it('TERM=screen COLORTERM=screen-256color uses 256 colors', function()
4072    assert_term_colors('screen', 'screen-256color', 256)
4073  end)
4074
4075  it('TERM=screen-256color no COLORTERM uses 256 colors', function()
4076    assert_term_colors('screen-256color', nil, 256)
4077  end)
4078
4079  -- tmux:
4080  --
4081  -- FreeBSD and MacOS fall back to the built-in tmux-256colour entry.
4082  -- Linux has a tmux entry in external terminfo with 8 colours,
4083  -- which is raised to 256.
4084
4085  it('TERM=tmux no COLORTERM uses 256 colors', function()
4086    assert_term_colors('tmux', nil, 256)
4087  end)
4088
4089  it('TERM=tmux COLORTERM=tmux uses 256 colors', function()
4090    assert_term_colors('tmux', 'tmux', 256)
4091  end)
4092
4093  it('TERM=tmux COLORTERM=tmux-256color uses 256 colors', function()
4094    assert_term_colors('tmux', 'tmux-256color', 256)
4095  end)
4096
4097  it('TERM=tmux-256color no COLORTERM uses 256 colors', function()
4098    assert_term_colors('tmux-256color', nil, 256)
4099  end)
4100
4101  -- xterm and imitators:
4102
4103  it('TERM=xterm uses 256 colors', function()
4104    assert_term_colors('xterm', nil, 256)
4105  end)
4106
4107  it('TERM=xterm COLORTERM=gnome-terminal uses 256 colors', function()
4108    assert_term_colors('xterm', 'gnome-terminal', 256)
4109  end)
4110
4111  it('TERM=xterm COLORTERM=mate-terminal uses 256 colors', function()
4112    assert_term_colors('xterm', 'mate-terminal', 256)
4113  end)
4114
4115  it('TERM=xterm-256color uses 256 colors', function()
4116    assert_term_colors('xterm-256color', nil, 256)
4117  end)
4118
4119  -- rxvt and stterm:
4120  --
4121  -- FreeBSD and MacOS fall back to the built-in rxvt-256color and
4122  -- st-256colour entries.
4123  -- Linux has an rxvt, an st, and an st-16color entry in external terminfo
4124  -- with 8, 8, and 16 colours respectively, which are raised to 256.
4125
4126  it('TERM=rxvt no COLORTERM uses 256 colors', function()
4127    assert_term_colors('rxvt', nil, 256)
4128  end)
4129
4130  it('TERM=rxvt COLORTERM=rxvt uses 256 colors', function()
4131    assert_term_colors('rxvt', 'rxvt', 256)
4132  end)
4133
4134  it('TERM=rxvt-256color uses 256 colors', function()
4135    assert_term_colors('rxvt-256color', nil, 256)
4136  end)
4137
4138  it('TERM=st no COLORTERM uses 256 colors', function()
4139    assert_term_colors('st', nil, 256)
4140  end)
4141
4142  it('TERM=st COLORTERM=st uses 256 colors', function()
4143    assert_term_colors('st', 'st', 256)
4144  end)
4145
4146  it('TERM=st COLORTERM=st-256color uses 256 colors', function()
4147    assert_term_colors('st', 'st-256color', 256)
4148  end)
4149
4150  it('TERM=st-16color no COLORTERM uses 8/256 colors', function()
4151    assert_term_colors('st', nil, 256)
4152  end)
4153
4154  it('TERM=st-16color COLORTERM=st uses 16/256 colors', function()
4155    assert_term_colors('st', 'st', 256)
4156  end)
4157
4158  it('TERM=st-16color COLORTERM=st-256color uses 256 colors', function()
4159    assert_term_colors('st', 'st-256color', 256)
4160  end)
4161
4162  it('TERM=st-256color uses 256 colors', function()
4163    assert_term_colors('st-256color', nil, 256)
4164  end)
4165
4166  -- gnome and vte:
4167  --
4168  -- FreeBSD and MacOS fall back to the built-in vte-256color entry.
4169  -- Linux has a gnome, a vte, a gnome-256color, and a vte-256color entry in
4170  -- external terminfo with 8, 8, 256, and 256 colours respectively, which are
4171  -- raised to 256.
4172
4173  it('TERM=gnome no COLORTERM uses 256 colors', function()
4174    assert_term_colors('gnome', nil, 256)
4175  end)
4176
4177  it('TERM=gnome COLORTERM=gnome uses 256 colors', function()
4178    assert_term_colors('gnome', 'gnome', 256)
4179  end)
4180
4181  it('TERM=gnome COLORTERM=gnome-256color uses 256 colors', function()
4182    assert_term_colors('gnome', 'gnome-256color', 256)
4183  end)
4184
4185  it('TERM=gnome-256color uses 256 colors', function()
4186    assert_term_colors('gnome-256color', nil, 256)
4187  end)
4188
4189  it('TERM=vte no COLORTERM uses 256 colors', function()
4190    assert_term_colors('vte', nil, 256)
4191  end)
4192
4193  it('TERM=vte COLORTERM=vte uses 256 colors', function()
4194    assert_term_colors('vte', 'vte', 256)
4195  end)
4196
4197  it('TERM=vte COLORTERM=vte-256color uses 256 colors', function()
4198    assert_term_colors('vte', 'vte-256color', 256)
4199  end)
4200
4201  it('TERM=vte-256color uses 256 colors', function()
4202    assert_term_colors('vte-256color', nil, 256)
4203  end)
4204
4205  -- others:
4206
4207  -- TODO(blueyed): this is made pending, since it causes failure + later hang
4208  --                when using non-compatible libvterm (#9494/#10179).
4209  pending('TERM=interix uses 8 colors', function()
4210    assert_term_colors('interix', nil, 8)
4211  end)
4212
4213  it('TERM=iTerm.app uses 256 colors', function()
4214    assert_term_colors('iTerm.app', nil, 256)
4215  end)
4216
4217  it('TERM=iterm uses 256 colors', function()
4218    assert_term_colors('iterm', nil, 256)
4219  end)
4220end)
4221
4222-- These tests require `tt` because --headless/--embed does not initialize the TUI.
4223describe("TUI 'term' option", function()
4224  local screen --[[@type test.functional.ui.screen]]
4225
4226  local function assert_term(term_envvar, term_expected)
4227    clear()
4228    screen = tt.setup_child_nvim({
4229      '--clean',
4230      '--cmd',
4231      nvim_set .. ' notermguicolors',
4232    }, {
4233      env = {
4234        LANG = 'C',
4235        TERM = term_envvar or '',
4236      },
4237    })
4238
4239    local full_timeout = screen.timeout
4240    retry(nil, 2 * full_timeout, function() -- Wait for TUI thread to set 'term'.
4241      feed_data(":echo 'term='.(&term)\n")
4242      screen:expect { any = 'term=' .. term_expected, timeout = 250 }
4243    end)
4244  end
4245
4246  it('gets builtin term if $TERM is invalid', function()
4247    assert_term('foo', 'ansi')
4248  end)
4249
4250  it('gets system-provided term if $TERM is valid', function()
4251    if is_os('openbsd') then
4252      assert_term('xterm', 'xterm')
4253    elseif is_os('bsd') then -- BSD lacks terminfo, builtin is always used.
4254      assert_term('xterm', 'xterm')
4255    elseif is_os('mac') then
4256      local status, _ = pcall(assert_term, 'xterm', 'xterm')
4257      if not status then
4258        pending('macOS: unibilium could not find terminfo')
4259      end
4260    else
4261      assert_term('xterm', 'xterm')
4262    end
4263  end)
4264
4265  it('builtin terms', function()
4266    -- These non-standard terminfos are always builtin.
4267    assert_term('win32con', 'win32con')
4268    assert_term('conemu', 'conemu')
4269    assert_term('vtpcon', 'vtpcon')
4270  end)
4271end)
4272
4273-- These tests require `tt` because --headless/--embed does not initialize the TUI.
4274describe('TUI', function()
4275  local screen --[[@type test.functional.ui.screen]]
4276
4277  -- Runs (child) `nvim` in a TTY (:terminal), to start the builtin TUI.
4278  local function nvim_tui(extra_args, extra_env)
4279    clear()
4280    extra_env = extra_env or {}
4281    local env = vim.tbl_extend('force', { LANG = 'C' }, extra_env)
4282
4283    screen = tt.setup_child_nvim({
4284      '--clean',
4285      '--cmd',
4286      'colorscheme vim',
4287      '--cmd',
4288      nvim_set .. ' notermguicolors',
4289      extra_args,
4290    }, {
4291      env = env,
4292    })
4293  end
4294
4295  it('-V3log logs terminfo values', function()
4296    local logfile = 'Xtest_tui_verbose_log'
4297    nvim_tui('-V3' .. logfile)
4298    finally(function()
4299      os.remove(logfile)
4300    end)
4301
4302    -- Wait for TUI to start.
4303    feed_data('Gitext')
4304    screen:expect([[
4305      text^                                              |
4306      {100:~                                                 }|*4
4307      {5:-- INSERT --}                                      |
4308      {5:-- TERMINAL --}                                    |
4309    ]])
4310
4311    retry(nil, 3000, function() -- Wait for log file to be flushed.
4312      local log = read_file(logfile) or ''
4313      eq('--- Terminal info --- {{{\n', string.match(log, '%-%-%- Terminal.-\n')) -- }}}
4314      ok(#log > 50)
4315    end)
4316  end)
4317
4318  it('uses $NVIM_TERMDEFS to override terminfo', function()
4319    local logfile = 'Xtest_terminfo_override_verbose_log'
4320    finally(function()
4321      os.remove(logfile)
4322    end)
4323
4324    local terminfo = {
4325      enter_ca_mode = 'ENTER_CA_MODE',
4326      reset_cursor_style = '\027[0 q',
4327      key_home = { 'ABC', 'DEF' },
4328      key_npage = 'npage',
4329      key_end = { 'GHI' },
4330      key_f1 = 'JKL',
4331      key_f63 = 'MNO',
4332      Su = true,
4333      max_colors = 999,
4334    }
4335
4336    nvim_tui('-V3' .. logfile, { NVIM_TERMDEFS = vim.json.encode(terminfo) })
4337
4338    assert_log('enter_ca_mode[^\n]*= ' .. terminfo.enter_ca_mode, logfile, 9999)
4339    assert_log(
4340      'reset_cursor_style[^\n]*= ' .. vim.pesc(terminfo.reset_cursor_style:gsub('\027', '^[')),
4341      logfile,
4342      9999
4343    )
4344    assert_log(
4345      string.format('key_home%%s*= %s, key_shome = %s', terminfo.key_home[1], terminfo.key_home[2]),
4346      logfile,
4347      9999
4348    )
4349    assert_log('key_npage%s*= ' .. terminfo.key_npage, logfile, 9999)
4350    assert_log('key_end%s*= ' .. terminfo.key_end[1] .. '\n', logfile, 9999)
4351    assert_log('key_f1%s*= ' .. terminfo.key_f1, logfile, 9999)
4352    assert_log('key_f63%s*= ' .. terminfo.key_f63, logfile, 9999)
4353    assert_log('extended underline[^\n]*: ' .. tostring(terminfo.Su), logfile, 9999)
4354    assert_log('max_colors: ' .. terminfo.max_colors, logfile, 9999)
4355  end)
4356
4357  it('does not crash on large inputs #26099', function()
4358    nvim_tui()
4359
4360    screen:expect([[
4361      ^                                                  |
4362      {100:~                                                 }|*4
4363                                                        |
4364      {5:-- TERMINAL --}                                    |
4365    ]])
4366
4367    feed_data(string.format('\027]52;c;%s\027\\', string.rep('A', 8192)))
4368
4369    screen:expect_unchanged()
4370  end)
4371
4372  it('queries the terminal for truecolor support', function()
4373    t.skip(is_os('win'), 'FIXME: does not work on Windows')
4374    clear()
4375    exec_lua([[
4376      vim.api.nvim_create_autocmd('TermRequest', {
4377        callback = function(ev)
4378          local req = ev.data.sequence
4379          local sequence = req:match('^\027P%+q([%x;]+)$')
4380          if sequence then
4381            local t = {}
4382            for cap in vim.gsplit(sequence, ';') do
4383              local resp = string.format('\027P1+r%s\027\\', sequence)
4384              vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
4385              t[vim.text.hexdecode(cap)] = true
4386            end
4387            vim.g.xtgettcap = t
4388            return true
4389          end
4390        end,
4391      })
4392    ]])
4393
4394    local child_server = new_pipename()
4395    screen = tt.setup_child_nvim({
4396      '--clean',
4397      '--listen',
4398      child_server,
4399    }, {
4400      env = {
4401        VIMRUNTIME = os.getenv('VIMRUNTIME'),
4402
4403        -- Force COLORTERM to be unset and use a TERM that does not contain Tc or RGB in terminfo.
4404        -- This will force the nested nvim instance to query with XTGETTCAP
4405        COLORTERM = '',
4406        TERM = 'xterm-256colors',
4407      },
4408    })
4409
4410    screen:expect({ any = '%[No Name%]' })
4411
4412    local child_session = n.connect(child_server)
4413    retry(nil, 1000, function()
4414      eq({
4415        Tc = true,
4416        RGB = true,
4417        setrgbf = true,
4418        setrgbb = true,
4419      }, eval("get(g:, 'xtgettcap', '')"))
4420      eq({ true, 1 }, { child_session:request('nvim_eval', '&termguicolors') })
4421    end)
4422  end)
4423
4424  it('does not query the terminal for truecolor support if $COLORTERM is set', function()
4425    clear()
4426    exec_lua([[
4427      vim.api.nvim_create_autocmd('TermRequest', {
4428        callback = function(ev)
4429          local req = ev.data.sequence
4430          vim.g.termrequest = req
4431          local xtgettcap = req:match('^\027P%+q([%x;]+)$')
4432          if xtgettcap then
4433            local t = {}
4434            for cap in vim.gsplit(xtgettcap, ';') do
4435              local resp = string.format('\027P1+r%s\027\\', xtgettcap)
4436              vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
4437              t[vim.text.hexdecode(cap)] = true
4438            end
4439            vim.g.xtgettcap = t
4440            return true
4441          elseif req:match('^\027P$qm\027\\$') then
4442            vim.g.decrqss = true
4443          end
4444        end,
4445      })
4446    ]])
4447
4448    local child_server = new_pipename()
4449    screen = tt.setup_child_nvim({
4450      '--clean',
4451      '--listen',
4452      child_server,
4453    }, {
4454      env = {
4455        VIMRUNTIME = os.getenv('VIMRUNTIME'),
4456        -- With COLORTERM=256, Nvim should not query the terminal and should not set 'tgc'
4457        COLORTERM = '256',
4458        TERM = 'xterm-256colors',
4459      },
4460    })
4461
4462    screen:expect({ any = '%[No Name%]' })
4463
4464    local child_session = n.connect(child_server)
4465    retry(nil, 1000, function()
4466      local xtgettcap = eval("get(g:, 'xtgettcap', {})")
4467      eq(nil, xtgettcap['Tc'])
4468      eq(nil, xtgettcap['RGB'])
4469      eq(nil, xtgettcap['setrgbf'])
4470      eq(nil, xtgettcap['setrgbb'])
4471      eq(0, eval([[get(g:, 'decrqss')]]))
4472      eq({ true, 0 }, { child_session:request('nvim_eval', '&termguicolors') })
4473    end)
4474  end)
4475
4476  it('queries the terminal for OSC 52 support with XTGETTCAP', function()
4477    t.skip(is_os('win'), 'FIXME: does not work on Windows')
4478    clear()
4479    if not exec_lua('return pcall(require, "ffi")') then
4480      pending('N/A: missing LuaJIT FFI')
4481    end
4482
4483    -- Change vterm's DA1 response so that it doesn't include 52
4484    exec_lua(function()
4485      local ffi = require('ffi')
4486      ffi.cdef [[
4487        extern char vterm_primary_device_attr[]
4488      ]]
4489
4490      ffi.copy(ffi.C.vterm_primary_device_attr, '61;22')
4491    end)
4492
4493    exec_lua([[
4494      _G.query = false
4495      vim.api.nvim_create_autocmd('TermRequest', {
4496        callback = function(ev)
4497          local req = ev.data.sequence
4498          local sequence = req:match('^\027P%+q([%x;]+)$')
4499          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
4500            local resp = string.format('\027P1+r%s=%s\027\\', sequence, vim.text.hexencode('\027]52;;\027\\'))
4501            vim.api.nvim_chan_send(vim.bo[ev.buf].channel, resp)
4502            _G.query = true
4503            return true
4504          end
4505        end,
4506      })
4507    ]])
4508
4509    local child_server = new_pipename()
4510    screen = tt.setup_child_nvim({
4511      '--listen',
4512      child_server,
4513      '--clean',
4514    }, {
4515      env = {
4516        VIMRUNTIME = os.getenv('VIMRUNTIME'),
4517      },
4518    })
4519
4520    screen:expect({ any = '%[No Name%]' })
4521
4522    local child_session = n.connect(child_server)
4523    retry(nil, 1000, function()
4524      eq({ true, { osc52 = true } }, { child_session:request('nvim_eval', 'g:termfeatures') })
4525    end)
4526    eq(true, exec_lua([[return _G.query]]))
4527
4528    -- Attach another (non-TUI) UI to the child instance
4529    local alt = Screen.new(nil, nil, nil, child_session)
4530    finally(function()
4531      alt:detach()
4532      -- Avoid a dangling process after :detach.
4533      child_session:request('nvim_command', 'qall!')
4534    end)
4535
4536    -- Detach the first (primary) client so only the second UI is attached
4537    feed_data(':detach\n')
4538
4539    alt:expect({ any = '%[No Name%]' })
4540
4541    -- osc52 should be cleared from termfeatures
4542    eq({ true, {} }, { child_session:request('nvim_eval', 'g:termfeatures') })
4543  end)
4544
4545  it('determines OSC 52 support from DA1 response', function()
4546    t.skip(is_os('win'), 'FIXME: does not work on Windows')
4547    clear()
4548    exec_lua([[
4549      -- Check that we do not emit an XTGETTCAP request when DA1 indicates support
4550      _G.query = false
4551      vim.api.nvim_create_autocmd('TermRequest', {
4552        callback = function(ev)
4553          local req = ev.data.sequence
4554          local sequence = req:match('^\027P%+q([%x;]+)$')
4555          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
4556            _G.query = true
4557            return true
4558          end
4559        end,
4560      })
4561    ]])
4562
4563    local child_server = new_pipename()
4564    screen = tt.setup_child_nvim({
4565      '--listen',
4566      child_server,
4567      '--clean',
4568    }, {
4569      env = {
4570        VIMRUNTIME = os.getenv('VIMRUNTIME'),
4571      },
4572    })
4573
4574    screen:expect({ any = '%[No Name%]' })
4575
4576    local child_session = n.connect(child_server)
4577    retry(nil, 1000, function()
4578      eq({ true, { osc52 = true } }, { child_session:request('nvim_eval', 'g:termfeatures') })
4579    end)
4580    eq(false, exec_lua([[return _G.query]]))
4581  end)
4582
4583  it('does not query the terminal for OSC 52 support when disabled', function()
4584    clear()
4585    exec_lua([[
4586      _G.query = false
4587      vim.api.nvim_create_autocmd('TermRequest', {
4588        callback = function(ev)
4589          local req = ev.data.sequence
4590          local sequence = req:match('^\027P%+q([%x;]+)$')
4591          if sequence and vim.text.hexdecode(sequence) == 'Ms' then
4592            _G.query = true
4593            return true
4594          end
4595        end,
4596      })
4597    ]])
4598
4599    local child_server = new_pipename()
4600    screen = tt.setup_child_nvim({
4601      '--listen',
4602      child_server,
4603      '--clean',
4604      '--cmd',
4605      'let g:termfeatures = #{osc52: v:false}',
4606    }, {
4607      env = {
4608        VIMRUNTIME = os.getenv('VIMRUNTIME'),
4609      },
4610    })
4611
4612    screen:expect({ any = '%[No Name%]' })
4613
4614    local child_session = n.connect(child_server)
4615    eq({ true, { osc52 = false } }, { child_session:request('nvim_eval', 'g:termfeatures') })
4616    eq(false, exec_lua([[return _G.query]]))
4617  end)
4618end)
4619
4620describe('TUI bg color', function()
4621  if t.skip(is_os('win')) then
4622    return
4623  end
4624
4625  before_each(clear)
4626
4627  it('is properly set in a nested Nvim instance when background=dark', function()
4628    command('highlight clear Normal')
4629    command('set background=dark') -- set outer Nvim background
4630    local child_server = new_pipename()
4631    local screen = tt.setup_child_nvim({
4632      '--clean',
4633      '--listen',
4634      child_server,
4635      '--cmd',
4636      'colorscheme vim',
4637      '--cmd',
4638      'set noswapfile',
4639    })
4640    screen:expect({ any = '%[No Name%]' })
4641    local child_session = n.connect(child_server)
4642    retry(nil, nil, function()
4643      eq({ true, 'dark' }, { child_session:request('nvim_eval', '&background') })
4644    end)
4645  end)
4646
4647  it('is properly set in a nested Nvim instance when background=light', function()
4648    command('highlight clear Normal')
4649    command('set background=light') -- set outer Nvim background
4650    local child_server = new_pipename()
4651    local screen = tt.setup_child_nvim({
4652      '--clean',
4653      '--listen',
4654      child_server,
4655      '--cmd',
4656      'colorscheme vim',
4657      '--cmd',
4658      'set noswapfile',
4659    })
4660    screen:expect({ any = '%[No Name%]' })
4661    local child_session = n.connect(child_server)
4662    retry(nil, nil, function()
4663      eq({ true, 'light' }, { child_session:request('nvim_eval', '&background') })
4664    end)
4665  end)
4666
4667  it('queries the terminal for background color', function()
4668    exec_lua([[
4669      vim.api.nvim_create_autocmd('TermRequest', {
4670        callback = function(ev)
4671          local req = ev.data.sequence
4672          if req == '\027]11;?' then
4673            vim.g.oscrequest = true
4674            return true
4675          end
4676        end,
4677      })
4678    ]])
4679    tt.setup_child_nvim({
4680      '--clean',
4681      '--cmd',
4682      'colorscheme vim',
4683      '--cmd',
4684      'set noswapfile',
4685    })
4686    retry(nil, 1000, function()
4687      eq(true, eval("get(g:, 'oscrequest', v:false)"))
4688    end)
4689  end)
4690
4691  it('sends theme update notifications when background changes #31652', function()
4692    command('set background=dark') -- set outer Nvim background
4693    local child_server = new_pipename()
4694    local screen = tt.setup_child_nvim({
4695      '--clean',
4696      '--listen',
4697      child_server,
4698      '--cmd',
4699      'colorscheme vim',
4700      '--cmd',
4701      'set noswapfile',
4702      '-c',
4703      [[autocmd OptionSet background let g:background_option_old = v:option_old]],
4704      '-c',
4705      [[autocmd OptionSet background let g:background_option_new = v:option_new]],
4706    })
4707    screen:expect({ any = '%[No Name%]' })
4708    local child_session = n.connect(child_server)
4709    retry(nil, nil, function()
4710      eq({ true, 'dark' }, { child_session:request('nvim_eval', '&background') })
4711    end)
4712    command('set background=light') -- set outer Nvim background
4713    retry(nil, nil, function()
4714      eq({ true, 'light' }, { child_session:request('nvim_eval', '&background') })
4715    end)
4716    -- Make sure it triggered OptionSet with v:option_* values #38551 #41146
4717    eq({ true, 'dark' }, { child_session:request('nvim_eval', 'g:background_option_old') })
4718    eq({ true, 'light' }, { child_session:request('nvim_eval', 'g:background_option_new') })
4719  end)
4720
4721  -- Start a headless server (the outer Nvim is its OSC-11-answering terminal),
4722  -- cleaned up when the test ends, and return its address and a client session.
4723  local function start_headless(extra)
4724    local server = new_pipename()
4725    local argv = { nvim_prog, '--clean', '--headless', '--listen', server }
4726    local job = fn.jobstart(vim.list_extend(argv, extra or {}))
4727    finally(function()
4728      pcall(fn.jobstop, job)
4729    end)
4730    local session
4731    retry(nil, nil, function()
4732      session = n.connect(server)
4733    end)
4734    return server, session
4735  end
4736
4737  it('is detected on remote-ui attach to a headless server #30320', function()
4738    command('highlight clear Normal')
4739    command('set background=light') -- outer Nvim acts as a light terminal
4740    local server, session =
4741      start_headless({ '--cmd', 'colorscheme vim', '--cmd', 'set noswapfile' })
4742    local screen = tt.setup_child_nvim({ '--remote-ui', '--server', server })
4743    screen:expect({ any = '%[No Name%]' })
4744    retry(nil, nil, function()
4745      eq({ true, 'light' }, { session:request('nvim_eval', '&background') })
4746    end)
4747  end)
4748
4749  it('enables termguicolors on remote-ui attach to a headless server #30320', function()
4750    command('set background=light')
4751    local server, session =
4752      start_headless({ '--cmd', 'colorscheme vim', '--cmd', 'set noswapfile' })
4753    eq({ true, 0 }, { session:request('nvim_eval', '&termguicolors') })
4754    -- A truecolor terminal so the attaching client reports rgb=true.
4755    local screen = tt.setup_child_nvim(
4756      { '--remote-ui', '--server', server },
4757      { env = { COLORTERM = 'truecolor' } }
4758    )
4759    screen:expect({ any = '%[No Name%]' })
4760    retry(nil, nil, function()
4761      eq({ true, 1 }, { session:request('nvim_eval', '&termguicolors') })
4762    end)
4763  end)
4764
4765  it('does not override an explicit user background on remote-ui attach', function()
4766    command('highlight clear Normal')
4767    command('set background=light') -- light terminal
4768    local server, session = start_headless({
4769      '--cmd',
4770      'set background=dark', -- user pins dark
4771      '--cmd',
4772      'colorscheme vim',
4773      '--cmd',
4774      'set noswapfile',
4775    })
4776    -- Count OSC 11 responses so we can wait for the attach round-trip to finish
4777    -- (a deterministic barrier) before asserting the user's value held.
4778    session:request(
4779      'nvim_exec_lua',
4780      [[
4781        _G.osc11 = 0
4782        vim.api.nvim_create_autocmd('TermResponse', { callback = function(ev)
4783          if ev.data.sequence:find(']11;rgb', 1, true) then
4784            _G.osc11 = _G.osc11 + 1
4785          end
4786        end })
4787      ]],
4788      {}
4789    )
4790    local screen = tt.setup_child_nvim({ '--remote-ui', '--server', server })
4791    screen:expect({ any = '%[No Name%]' })
4792    retry(nil, nil, function()
4793      eq({ true, true }, { session:request('nvim_exec_lua', 'return _G.osc11 > 0', {}) })
4794    end)
4795    eq({ true, 'dark' }, { session:request('nvim_eval', '&background') })
4796  end)
4797
4798  it('reacts to a runtime theme change over remote-ui', function()
4799    command('highlight clear Normal')
4800    command('set background=light') -- start light
4801    local server, session =
4802      start_headless({ '--cmd', 'colorscheme vim', '--cmd', 'set noswapfile' })
4803    local screen = tt.setup_child_nvim({ '--remote-ui', '--server', server })
4804    screen:expect({ any = '%[No Name%]' })
4805    retry(nil, nil, function()
4806      eq({ true, 'light' }, { session:request('nvim_eval', '&background') })
4807    end)
4808    command('highlight clear Normal')
4809    command('set background=dark') -- flip the outer terminal at runtime
4810    retry(nil, nil, function()
4811      eq({ true, 'dark' }, { session:request('nvim_eval', '&background') })
4812    end)
4813  end)
4814end)
4815
4816describe('TUI client', function()
4817  local function start_tui_and_remote_client()
4818    local server_super = n.clear()
4819    local client_super = n.new_session(true)
4820    finally(function()
4821      client_super:close()
4822      server_super:close()
4823    end)
4824
4825    local server_pipe = new_pipename()
4826    local screen_server = tt.setup_child_nvim({
4827      '--clean',
4828      '--listen',
4829      server_pipe,
4830      '--cmd',
4831      'colorscheme vim',
4832      '--cmd',
4833      nvim_set .. ' laststatus=2 background=dark',
4834    }, { env = env_notermguicolors })
4835    screen_server:expect([[
4836      ^                                                  |
4837      {100:~                                                 }|*3
4838      {3:[No Name]                                         }|
4839                                                        |
4840      {5:-- TERMINAL --}                                    |
4841    ]])
4842
4843    feed_data('iHello, World')
4844    screen_server:expect([[
4845      Hello, World^                                      |
4846      {100:~                                                 }|*3
4847      {3:[No Name] [+]                                     }|
4848      {5:-- INSERT --}                                      |
4849      {5:-- TERMINAL --}                                    |
4850    ]])
4851    feed_data('\027')
4852    local s0 = [[
4853      Hello, Worl^d                                      |
4854      {100:~                                                 }|*3
4855      {3:[No Name] [+]                                     }|
4856                                                        |
4857      {5:-- TERMINAL --}                                    |
4858    ]]
4859    screen_server:expect(s0)
4860
4861    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
4862    screen_server:expect({ any = 'GUI Running: 0' })
4863
4864    set_session(client_super)
4865    local screen_client = tt.setup_child_nvim({
4866      '--remote-ui',
4867      '--server',
4868      server_pipe,
4869    }, { env = env_notermguicolors })
4870    screen_client:expect(s0)
4871
4872    return server_super, screen_server, screen_client
4873  end
4874
4875  it('connects to remote instance (with its own TUI)', function()
4876    local _, screen_server, screen_client = start_tui_and_remote_client()
4877
4878    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
4879    screen_client:expect({ any = 'GUI Running: 0' })
4880
4881    -- grid smaller than containing terminal window is cleared properly
4882    feed_data(":call setline(1,['a'->repeat(&columns)]->repeat(&lines))\n")
4883    feed_data('0:set lines=3\n')
4884    local s1 = [[
4885      ^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|
4886      {3:[No Name] [+]                                     }|
4887                                                        |*4
4888      {5:-- TERMINAL --}                                    |
4889    ]]
4890    screen_client:expect(s1)
4891    screen_server:expect(s1)
4892  end)
4893
4894  it(':restart! works when connecting to remote instance (with its own TUI)', function()
4895    local _, screen_server, screen_client = start_tui_and_remote_client()
4896
4897    -- Both clients should attach to the new server.
4898    feed_data(':restart! +qall!\n')
4899    local screen_restarted = [[
4900      ^                                                  |
4901      {100:~                                                 }|*3
4902      {3:[No Name]                                         }|
4903                                                        |
4904      {5:-- TERMINAL --}                                    |
4905    ]]
4906    screen_client:expect(screen_restarted)
4907    screen_server:expect(screen_restarted)
4908
4909    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
4910    screen_client:expect({ any = 'GUI Running: 0' })
4911
4912    -- The :vsplit command should only be executed once.
4913    feed_data(':restart! vsplit\r')
4914    screen_restarted = [[
4915      ^                         │                        |
4916      {100:~                        }│{100:~                       }|*3
4917      {3:[No Name]                 }{2:[No Name]               }|
4918                                                        |
4919      {5:-- TERMINAL --}                                    |
4920    ]]
4921    screen_client:expect(screen_restarted)
4922    screen_server:expect(screen_restarted)
4923
4924    feed_data(':qall!\r')
4925    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
4926    screen_server:expect({ any = vim.pesc('[Process exited 0]') })
4927  end)
4928
4929  local function start_headless_server_and_client(use_testlog)
4930    local server = n.new_session(false, {
4931      args_rm = { '--cmd' },
4932      args = {
4933        '--cmd',
4934        'colorscheme vim',
4935        '--cmd',
4936        nvim_set .. ' notermguicolors background=dark',
4937      },
4938    })
4939    local client_super =
4940      n.new_session(true, use_testlog and { env = { NVIM_LOG_FILE = testlog } } or {})
4941    finally(function()
4942      client_super:close()
4943      server:close()
4944      os.remove(testlog)
4945    end)
4946
4947    set_session(server)
4948    --- @type string
4949    local server_pipe = api.nvim_get_vvar('servername')
4950    server:request('nvim_input', 'iHalloj!<Esc>')
4951
4952    set_session(client_super)
4953    local screen_client = tt.setup_child_nvim({
4954      '--remote-ui',
4955      '--server',
4956      server_pipe,
4957    }, { env = env_notermguicolors })
4958    screen_client:expect([[
4959      Halloj^!                                           |
4960      {100:~                                                 }|*4
4961                                                        |
4962      {5:-- TERMINAL --}                                    |
4963    ]])
4964
4965    return server, server_pipe, screen_client
4966  end
4967
4968  it('connects to remote instance (--headless)', function()
4969    local server, server_pipe, screen_client = start_headless_server_and_client(false)
4970
4971    -- No heap-use-after-free when receiving UI events after deadly signal #22184
4972    server:request('nvim_input', ('a'):rep(1000))
4973    exec_lua([[vim.uv.kill(vim.fn.jobpid(vim.bo.channel), 'sigterm')]])
4974    screen_client:expect(is_os('win') and { any = '%[Process exited 1%]' } or [[
4975      Nvim: Caught deadly signal 'SIGTERM'              |
4976      ^                                                  |
4977      [Process exited 1]                                |
4978                                                        |*3
4979      {5:-- TERMINAL --}                                    |
4980    ]])
4981
4982    eq(0, api.nvim_get_vvar('shell_error'))
4983    -- exits on input eof #22244
4984    -- Use system() without input so that stdin is closed.
4985    fn.system({ nvim_prog, '--remote-ui', '--server', server_pipe })
4986    eq(1, api.nvim_get_vvar('shell_error'))
4987
4988    command('bwipe!')
4989    -- Start another remote client to attach to the same server.
4990    fn.jobstart({ nvim_prog, '--remote-ui', '--server', server_pipe }, { term = true })
4991    command('startinsert')
4992    screen_client:expect([[
4993      {100:<<<}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|
4994      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|*3
4995      aaaaaa^                                            |
4996      {5:-- INSERT --}                                      |
4997      {5:-- TERMINAL --}                                    |
4998    ]])
4999    feed_data('\027')
5000
5001    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
5002    screen_client:expect({ any = 'GUI Running: 0' })
5003  end)
5004
5005  it(':restart! works when connecting to remote instance (--headless)', function()
5006    local _, server_pipe, screen_client = start_headless_server_and_client(false)
5007
5008    -- The client should attach to the new server and the original server should exit.
5009    feed_data(':restart! +qall!\n')
5010    screen_client:expect([[
5011      ^                                                  |
5012      {100:~                                                 }|*4
5013                                                        |
5014      {5:-- TERMINAL --}                                    |
5015    ]])
5016    retry(nil, nil, function()
5017      eq(nil, vim.uv.fs_stat(server_pipe))
5018    end)
5019
5020    feed_data(':echo "GUI Running: " .. has("gui_running")\013')
5021    screen_client:expect({ any = 'GUI Running: 0' })
5022
5023    feed_data(':q!\r')
5024    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
5025  end)
5026
5027  local ffi_str_defs = [[
5028    local ffi = require('ffi')
5029    local cstr = ffi.typeof('char[?]')
5030    ffi.cdef('typedef struct { char *data; size_t size; } String;')
5031    local function to_api_string(str)
5032      return ffi.new('String', { data = cstr(#str + 1, str), size = #str })
5033    end
5034  ]]
5035
5036  it('does not crash or hang with a very long title', function()
5037    local server, _, screen_client = start_headless_server_and_client(true)
5038    local server_exec_lua = tt.make_lua_executor(server)
5039    if not server_exec_lua('return pcall(require, "ffi")') then
5040      pending('N/A: missing LuaJIT FFI')
5041    end
5042
5043    server:request('nvim_set_option_value', 'titlestring', '%t%( %M%) - Nvim', {})
5044    local bufname = api.nvim_buf_get_name(0)
5045    local old_title = api.nvim_buf_get_var(0, 'term_title')
5046    if not is_os('win') then
5047      eq(bufname, old_title)
5048    end
5049    -- Normally a title cannot be longer than the 65535-byte buffer as maketitle()
5050    -- limits it length. Use FFI to send a very long title directly.
5051    server_exec_lua(ffi_str_defs .. [[
5052      ffi.cdef('void ui_call_set_title(String title);')
5053      ffi.C.ui_call_set_title(to_api_string(('a'):rep(65536)))
5054    ]])
5055    screen_client:expect_unchanged()
5056    assert_log('set_title: title string too long!', testlog)
5057    eq(old_title, api.nvim_buf_get_var(0, 'term_title'))
5058
5059    -- Following escape sequences are not affected.
5060    server:request('nvim_set_option_value', 'title', true, {})
5061    retry(nil, nil, function()
5062      eq('[No Name] + - Nvim', api.nvim_buf_get_var(0, 'term_title'))
5063    end)
5064  end)
5065
5066  it('logs chdir failure properly', function()
5067    t.skip(is_os('win'), 'N/A for Windows')
5068    local server, _, screen_client = start_headless_server_and_client(true)
5069    local server_exec_lua = tt.make_lua_executor(server)
5070    if not server_exec_lua('return pcall(require, "ffi")') then
5071      pending('N/A: missing LuaJIT FFI')
5072    end
5073
5074    -- Use FFI to send a chdir event to a non-directory path.
5075    server_exec_lua(ffi_str_defs .. [[
5076      ffi.cdef('void ui_call_chdir(String path);')
5077      ffi.C.ui_call_chdir(to_api_string('README.md'))
5078    ]])
5079    screen_client:expect_unchanged()
5080    assert_log('Failed to chdir to README%.md: not a directory', testlog)
5081  end)
5082
5083  it('nvim_ui_send works with remote client #36317', function()
5084    local server, _, _ = start_headless_server_and_client(false)
5085    server:request('nvim_ui_send', '\027]2;TEST_TITLE\027\\')
5086    retry(nil, nil, function()
5087      eq('TEST_TITLE', api.nvim_buf_get_var(0, 'term_title'))
5088    end)
5089  end)
5090
5091  it('throws error when no server exists', function()
5092    clear()
5093    local screen = tt.setup_child_nvim({
5094      '--remote-ui',
5095      '--server',
5096      '127.0.0.1:2436546',
5097    }, { cols = 60 })
5098
5099    screen:expect([[
5100      Remote ui failed to start: {MATCH:.*}|
5101      ^                                                            |
5102      [Process exited 1]                                          |
5103                                                                  |*3
5104      {5:-- TERMINAL --}                                              |
5105    ]])
5106  end)
5107
5108  local function test_remote_tui_quit(status)
5109    local server_super, screen_server, screen_client = start_tui_and_remote_client()
5110
5111    -- quitting the server
5112    set_session(server_super)
5113    feed_data(status and ':' .. status .. 'cquit!\n' or ':quit!\n')
5114    status = status and status or 0
5115    screen_server:expect({ any = 'Process exited ' .. status })
5116    screen_client:expect({ any = 'Process exited ' .. status })
5117  end
5118
5119  describe('exits when server quits', function()
5120    it('with :quit', function()
5121      test_remote_tui_quit()
5122    end)
5123
5124    it('with :cquit', function()
5125      test_remote_tui_quit(42)
5126    end)
5127  end)
5128
5129  it('suspend/resume works with multiple clients', function()
5130    t.skip(is_os('win'), 'N/A for Windows')
5131    local server_super, screen_server, screen_client = start_tui_and_remote_client()
5132
5133    local screen_normal = [[
5134      Hello, Worl^d                                      |
5135      {100:~                                                 }|*3
5136      {3:[No Name] [+]                                     }|
5137                                                        |
5138      {5:-- TERMINAL --}                                    |
5139    ]]
5140    local screen_suspended = [[
5141                                                        |*5
5142      ^[Process suspended]                               |
5143      {5:-- TERMINAL --}                                    |
5144    ]]
5145
5146    screen_client:expect({ grid = screen_normal, unchanged = true })
5147    screen_server:expect({ grid = screen_normal, unchanged = true })
5148
5149    -- Suspend both clients.
5150    feed_data(':suspend\r')
5151    screen_client:expect({ grid = screen_suspended })
5152    screen_server:expect({ grid = screen_suspended })
5153
5154    -- Resume the remote client.
5155    n.feed('<Space>')
5156    screen_client:expect({ grid = screen_normal })
5157    screen_server:expect({ grid = screen_suspended, unchanged = true })
5158
5159    -- Resume the embedding client.
5160    server_super:request('nvim_input', '<Space>')
5161    screen_server:expect({ grid = screen_normal })
5162    screen_client:expect({ grid = screen_normal, unchanged = true })
5163
5164    -- Suspend both clients again.
5165    feed_data(':suspend\r')
5166    screen_client:expect({ grid = screen_suspended })
5167    screen_server:expect({ grid = screen_suspended })
5168
5169    -- Resume the remote client.
5170    n.feed('<Space>')
5171    screen_client:expect({ grid = screen_normal })
5172    screen_server:expect({ grid = screen_suspended, unchanged = true })
5173
5174    -- Suspend the remote client again.
5175    feed_data(':suspend\r')
5176    screen_client:expect({ grid = screen_suspended })
5177    screen_server:expect({ grid = screen_suspended, unchanged = true })
5178
5179    -- Resume the embedding client.
5180    server_super:request('nvim_input', '<Space>')
5181    screen_server:expect({ grid = screen_normal })
5182    screen_client:expect({ grid = screen_suspended, unchanged = true })
5183
5184    -- Resume the remote client.
5185    n.feed('<Space>')
5186    screen_client:expect({ grid = screen_normal })
5187    screen_server:expect({ grid = screen_normal, unchanged = true })
5188
5189    feed_data(':quit!\r')
5190    screen_server:expect({ any = vim.pesc('[Process exited 0]') })
5191    screen_client:expect({ any = vim.pesc('[Process exited 0]') })
5192  end)
5193end)