robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
66.9 KiB1861 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local tt = require('test.functional.testterm')
5
6local describe, it, before_each, finally = t.describe, t.it, t.before_each, t.finally
7local assert_alive = n.assert_alive
8local feed, clear = n.feed, n.clear
9local poke_eventloop = n.poke_eventloop
10local nvim_prog = n.nvim_prog
11local eval, source = n.eval, n.source
12local pcall_err = t.pcall_err
13local eq, neq = t.eq, t.neq
14local api = n.api
15local retry = t.retry
16local testprg = n.testprg
17local write_file = t.write_file
18local command = n.command
19local matches = t.matches
20local not_matches = t.not_matches
21local exec_lua = n.exec_lua
22local sleep = vim.uv.sleep
23local fn = n.fn
24local is_os = t.is_os
25local skip = t.skip
26
27describe(':terminal buffer', function()
28  local screen
29
30  before_each(function()
31    clear()
32    command('set modifiable swapfile undolevels=20')
33    screen = tt.setup_screen()
34  end)
35
36  it('terminal-mode forces various options', function()
37    local expr =
38      '[&l:cursorlineopt, &l:cursorline, &l:cursorcolumn, &l:scrolloff, &l:sidescrolloff]'
39
40    feed([[<C-\><C-N>]])
41    command('setlocal cursorline cursorlineopt=both cursorcolumn scrolloff=4 sidescrolloff=7')
42    eq({ 'both', 1, 1, 4, 7 }, eval(expr))
43    eq('nt', eval('mode(1)'))
44
45    -- Enter Terminal mode ("insert" mode in :terminal).
46    feed('i')
47    eq('t', eval('mode(1)'))
48    eq({ 'number', 1, 0, 0, 0 }, eval(expr))
49
50    -- Return to Normal mode.
51    feed([[<C-\><C-N>]])
52    eq('nt', eval('mode(1)'))
53    eq({ 'both', 1, 1, 4, 7 }, eval(expr))
54
55    -- Enter Terminal mode again.
56    feed('i')
57    eq('t', eval('mode(1)'))
58    eq({ 'number', 1, 0, 0, 0 }, eval(expr))
59
60    -- Delete the terminal buffer and return to the previous buffer.
61    command('bwipe!')
62    feed('<Ignore>') -- Add input to separate two RPC requests
63    eq('n', eval('mode(1)'))
64    -- Window options in the old buffer should be unchanged. #37484
65    eq({ 'both', 0, 0, -1, -1 }, eval(expr))
66  end)
67
68  it('terminal-mode does not change cursorlineopt if cursorline is disabled', function()
69    feed([[<C-\><C-N>]])
70    command('setlocal nocursorline cursorlineopt=both')
71    feed('i')
72    eq({ 0, 'both' }, eval('[&l:cursorline, &l:cursorlineopt]'))
73  end)
74
75  it('terminal-mode disables cursorline when cursorlineopt is only set to "line"', function()
76    feed([[<C-\><C-N>]])
77    command('setlocal cursorline cursorlineopt=line')
78    feed('i')
79    eq({ 0, 'line' }, eval('[&l:cursorline, &l:cursorlineopt]'))
80  end)
81
82  describe('swap and undo', function()
83    before_each(function()
84      feed('<c-\\><c-n>')
85      screen:expect([[
86        tty ready                                         |
87        ^                                                  |
88                                                          |*5
89      ]])
90    end)
91
92    it('does not create swap files', function()
93      eq('No swap file', n.exec_capture('swapname'))
94    end)
95
96    it('does not create undo files', function()
97      local undofile = api.nvim_eval('undofile(bufname("%"))')
98      eq(nil, io.open(undofile))
99    end)
100  end)
101
102  it('cannot be modified directly', function()
103    feed('<c-\\><c-n>dd')
104    screen:expect([[
105      tty ready                                         |
106      ^                                                  |
107                                                        |*4
108      {101:E21: Cannot make changes, 'modifiable' is off}     |
109    ]])
110  end)
111
112  it('sends data to the terminal when the "put" operator is used', function()
113    feed('<c-\\><c-n>gg"ayj')
114    fn.setreg('a', 'appended ' .. fn.getreg('a'))
115    feed('"ap"ap')
116    screen:expect([[
117      ^tty ready                                         |
118      appended tty ready                                |*2
119                                                        |*4
120    ]])
121    -- operator count is also taken into consideration
122    feed('3"ap')
123    screen:expect([[
124      ^tty ready                                         |
125      appended tty ready                                |*5
126                                                        |
127    ]])
128    -- pasting expression register shouldn't leak memory
129    feed([["="abcd\nefghi"<CR>pi]])
130    screen:expect([[
131      appended tty ready                                |*4
132      abcd                                              |
133      efghi^                                             |
134      {5:-- TERMINAL --}                                    |
135    ]])
136  end)
137
138  it('sends data to the terminal when the ":put" command is used', function()
139    feed('<c-\\><c-n>gg"ayj')
140    fn.setreg('a', 'appended ' .. fn.getreg('a'))
141    feed(':put a<CR>')
142    screen:expect([[
143      ^tty ready                                         |
144      appended tty ready                                |
145                                                        |*4
146      :put a                                            |
147    ]])
148    -- line argument is only used to move the cursor
149    feed(':6put a<CR>')
150    screen:expect([[
151      tty ready                                         |
152      appended tty ready                                |*2
153                                                        |*2
154      ^                                                  |
155      :6put a                                           |
156    ]])
157  end)
158
159  it('can be deleted', function()
160    feed('<c-\\><c-n>:bd!<cr>')
161    screen:expect([[
162      ^                                                  |
163      {100:~                                                 }|*5
164      :bd!                                              |
165    ]])
166    feed(':bnext<CR>')
167    screen:expect([[
168      ^                                                  |
169      {100:~                                                 }|*5
170      :bnext                                            |
171    ]])
172  end)
173
174  it('handles loss of focus gracefully', function()
175    -- Change the statusline to avoid printing the file name, which varies.
176    api.nvim_set_option_value('statusline', '==========', {})
177
178    -- Save the buffer number of the terminal for later testing.
179    local tbuf = eval('bufnr("%")')
180    local exitcmd = is_os('win') and "['cmd', '/c', 'exit']" or "['sh', '-c', 'exit']"
181    source([[
182    function! SplitWindow(id, data, event)
183      new
184      call feedkeys("iabc\<Esc>")
185    endfunction
186
187    startinsert
188    call jobstart(]] .. exitcmd .. [[, {'on_exit': function("SplitWindow")})
189    call feedkeys("\<C-\>", 't')  " vim will expect <C-n>, but be exited out of
190                                  " the terminal before it can be entered.
191    ]])
192
193    -- We should be in a new buffer now.
194    screen:expect([[
195      ab^c                                               |
196      {100:~                                                 }|
197      {3:==========                                        }|
198      rows: 2, cols: 50                                 |
199                                                        |
200      {119:==========                                        }|
201                                                        |
202    ]])
203
204    neq(tbuf, eval('bufnr("%")'))
205    command('quit!') -- Should exit the new window, not the terminal.
206    eq(tbuf, eval('bufnr("%")'))
207  end)
208
209  describe('handles confirmations', function()
210    it('with :confirm', function()
211      feed('<c-\\><c-n>')
212      feed(':confirm bdelete<CR>')
213      screen:expect { any = 'Close "term://' }
214    end)
215
216    it('with &confirm', function()
217      feed('<c-\\><c-n>')
218      feed(':bdelete<CR>')
219      screen:expect { any = 'E89' }
220      feed('<cr>')
221      eq('terminal', eval('&buftype'))
222      feed(':set confirm | bdelete<CR>')
223      screen:expect { any = 'Close "term://' }
224      feed('y')
225      neq('terminal', eval('&buftype'))
226    end)
227  end)
228
229  it('it works with set rightleft #11438', function()
230    local columns = eval('&columns')
231    feed(string.rep('a', columns))
232    command('set rightleft')
233    screen:expect([[
234                                               ydaer ytt|
235      ^aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa|
236                                                        |*4
237      {5:-- TERMINAL --}                                    |
238    ]])
239    command('bdelete!')
240  end)
241
242  it('requires bang (!) to close a running job #15402', function()
243    eq('Vim(wqall):E948: Job still running (add ! to end the job)', pcall_err(command, 'wqall'))
244    command('redir => g:wqall_out | silent! wqall | redir END')
245    matches('E948:', api.nvim_get_var('wqall_out'))
246    not_matches('E676:', api.nvim_get_var('wqall_out'))
247    for _, cmd in ipairs({ 'bdelete', '%bdelete', 'bwipeout', 'bunload' }) do
248      matches(
249        '^Vim%('
250          .. cmd:gsub('%%', '')
251          .. '%):E89: term://.*tty%-test.* will be killed %(add %! to override%)$',
252        pcall_err(command, cmd)
253      )
254    end
255    command('call jobstop(&channel)')
256    assert(0 >= eval('jobwait([&channel], 1000)[0]'))
257    command('bdelete')
258  end)
259
260  it(':wqall! closes a running job', function()
261    n.expect_exit(command, 'wqall!')
262  end)
263
264  it('stops running jobs with :quit', function()
265    -- Open in a new window to avoid terminating the nvim instance
266    command('split')
267    command('terminal')
268    command('set nohidden')
269    command('quit')
270  end)
271
272  it('does not segfault when pasting empty register #13955', function()
273    feed('<c-\\><c-n>')
274    command('put a') -- register a is empty
275    n.assert_alive()
276  end)
277
278  it([[can use temporary normal mode <c-\><c-o>]], function()
279    eq('t', fn.mode(1))
280    feed [[<c-\><c-o>]]
281    screen:expect([[
282      tty ready                                         |
283      ^                                                  |
284                                                        |*4
285      {5:-- (terminal) --}                                  |
286    ]])
287    eq('ntT', fn.mode(1))
288
289    feed [[:let g:x = 17]]
290    screen:expect([[
291      tty ready                                         |
292                                                        |*5
293      :let g:x = 17^                                     |
294    ]])
295
296    feed [[<cr>]]
297    screen:expect([[
298      tty ready                                         |
299      ^                                                  |
300                                                        |*4
301      {5:-- TERMINAL --}                                    |
302    ]])
303    eq('t', fn.mode(1))
304  end)
305
306  it('is refreshed with partial mappings in Terminal mode #9167', function()
307    command([[set timeoutlen=20000 | tnoremap jk <C-\><C-N>]])
308    feed('j') -- Won't reach the terminal until the next character is typed
309    screen:expect_unchanged()
310    feed('j') -- Refresh scheduled for the first 'j' but not processed
311    screen:expect_unchanged()
312    for i = 1, 10 do
313      eq({ mode = 't', blocking = true }, api.nvim_get_mode())
314      -- Wait for the previously scheduled refresh timer to arrive. Must comfortably exceed
315      -- terminal.c REFRESH_DELAY *plus* PTY echo round-trip; else the refresh isn't queued before
316      -- the next key and, since a partial mapping never drains main_loop.events, screen is stale.
317      vim.uv.sleep(50)
318      feed('j') -- Refresh scheduled for the last 'j' and processed for the one before
319      screen:expect(([[
320        tty ready                                         |
321        %s^%s|
322                                                          |*4
323        {5:-- TERMINAL --}                                    |
324      ]]):format(('j'):rep(i), (' '):rep(50 - i)))
325    end
326    feed('l') -- No partial mapping, so all pending refreshes should be processed
327    screen:expect([[
328      tty ready                                         |
329      jjjjjjjjjjjjl^                                     |
330                                                        |*4
331      {5:-- TERMINAL --}                                    |
332    ]])
333  end)
334
335  it('is refreshed with partial mappings in Normal mode', function()
336    command('set timeoutlen=20000 | nnoremap jk :')
337    command('nnoremap j <Cmd>call chansend(&channel, "j")<CR>')
338    feed([[<C-\><C-N>]])
339    screen:expect([[
340      tty ready                                         |
341      ^                                                  |
342                                                        |*5
343    ]])
344    feed('j') -- Won't reach the terminal until the next character is typed
345    screen:expect_unchanged()
346    feed('j') -- Refresh scheduled for the first 'j' but not processed
347    screen:expect_unchanged()
348    for i = 1, 10 do
349      eq({ mode = 'nt', blocking = true }, api.nvim_get_mode())
350      -- Wait for the previously scheduled refresh timer to arrive. Must comfortably exceed
351      -- terminal.c REFRESH_DELAY *plus* PTY echo round-trip; else the refresh isn't queued before
352      -- the next key and, since a partial mapping never drains main_loop.events, screen is stale.
353      vim.uv.sleep(50)
354      feed('j') -- Refresh scheduled for the last 'j' and processed for the one before
355      screen:expect(([[
356        tty ready                                         |
357        ^%s%s|
358                                                          |*5
359      ]]):format(('j'):rep(i), (' '):rep(50 - i)))
360    end
361    feed('l') -- No partial mapping, so all pending refreshes should be processed
362    screen:expect([[
363      tty ready                                         |
364      j^jjjjjjjjjjj                                      |
365                                                        |*5
366    ]])
367  end)
368
369  it('writing to an existing file with :w fails #13549', function()
370    eq(
371      'Vim(write):E13: File exists (add ! to override)',
372      pcall_err(command, 'write test/functional/fixtures/tty-test.c')
373    )
374  end)
375
376  it('external interrupt (got_int) does not hang #20726', function()
377    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
378    command('call timer_start(0, {-> interrupt()})')
379    feed('<Ignore>') -- Add input to separate two RPC requests
380    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
381    feed([[<C-\><C-N>]])
382    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
383    command('bd!')
384  end)
385
386  it('correct size when switching buffers', function()
387    local term_buf = api.nvim_get_current_buf()
388    command('file foo | enew | vsplit')
389    api.nvim_set_current_buf(term_buf)
390    screen:expect([[
391      tty ready                │                        |
392      ^rows: 5, cols: 25        │{100:~                       }|
393                               │{100:~                       }|*3
394      {120:foo [-]                   }{2:[No Name]               }|
395                                                        |
396    ]])
397
398    feed('<C-^><C-W><C-O><C-^>')
399    screen:expect([[
400      tty ready                                         |
401      ^rows: 5, cols: 25                                 |
402      rows: 6, cols: 50                                 |
403                                                        |*4
404    ]])
405  end)
406
407  it('reports focus notifications when requested', function()
408    feed([[<C-\><C-N>]])
409    exec_lua(function()
410      local function new_test_term()
411        local chan = vim.api.nvim_open_term(0, {
412          on_input = function(_, term, buf, data)
413            if data == '\27[I' then
414              vim.b[buf].term_focused = true
415              vim.api.nvim_chan_send(term, 'focused\n')
416            elseif data == '\27[O' then
417              vim.b[buf].term_focused = false
418              vim.api.nvim_chan_send(term, 'unfocused\n')
419            end
420          end,
421        })
422        vim.b.term_focused = false
423        vim.api.nvim_chan_send(chan, '\27[?1004h') -- Enable focus reporting
424      end
425
426      vim.cmd 'edit bar'
427      new_test_term()
428      vim.cmd 'vnew foo'
429      new_test_term()
430      vim.cmd 'vsplit'
431    end)
432    screen:expect([[
433      ^                    │              │              |
434                          │              │              |*4
435      {120:foo [-]              }{119:foo [-]        bar [-]       }|
436                                                        |
437    ]])
438
439    -- TermEnter/Leave happens *after* entering/leaving terminal mode, so focus should've changed
440    -- already by the time these events run.
441    exec_lua(function()
442      _G.last_event = nil
443      vim.api.nvim_create_autocmd({ 'TermEnter', 'TermLeave' }, {
444        callback = function(ev)
445          _G.last_event = ev.event
446            .. ' '
447            .. vim.fs.basename(ev.file)
448            .. ' '
449            .. tostring(vim.b[ev.buf].term_focused)
450        end,
451      })
452    end)
453
454    feed('i')
455    screen:expect([[
456      focused             │focused       │              |
457      ^                    │              │              |
458                          │              │              |*3
459      {120:foo [-]              }{119:foo [-]        bar [-]       }|
460      {5:-- TERMINAL --}                                    |
461    ]])
462    eq('TermEnter foo true', exec_lua('return _G.last_event'))
463
464    -- Next window has the same terminal; no new notifications.
465    command('wincmd w')
466    screen:expect([[
467      focused             │focused             │        |
468                          │^                    │        |
469                          │                    │        |*3
470      {119:foo [-]              }{120:foo [-]              }{119:bar [-] }|
471      {5:-- TERMINAL --}                                    |
472    ]])
473    -- Next window has a different terminal; expect new unfocus and focus notifications.
474    command('wincmd w')
475    screen:expect([[
476      focused             │focused │focused             |
477      unfocused           │unfocuse│^                    |
478                          │        │                    |*3
479      {119:foo [-]              foo [-]  }{120:bar [-]             }|
480      {5:-- TERMINAL --}                                    |
481    ]])
482    -- Leaving terminal mode; expect a new unfocus notification.
483    feed([[<C-\><C-N>]])
484    screen:expect([[
485      focused             │focused │focused             |
486      unfocused           │unfocuse│unfocused           |
487                          │        │^                    |
488                          │        │                    |*2
489      {119:foo [-]              foo [-]  }{120:bar [-]             }|
490                                                        |
491    ]])
492    eq('TermLeave bar false', exec_lua('return _G.last_event'))
493  end)
494
495  it('no crash with race between buffer close and OSC 2', function()
496    skip(is_os('win'), 'tty-test cannot forward OSC 2 on Windows?')
497    exec_lua(function()
498      vim.api.nvim_chan_send(vim.bo.channel, '\027]2;SOME_TITLE\007')
499    end)
500    retry(nil, 4000, function()
501      eq('SOME_TITLE', api.nvim_buf_get_var(0, 'term_title'))
502    end)
503    screen:expect_unchanged()
504    --- @type string
505    local title_before_del = exec_lua(function()
506      vim.wait(10) -- Ensure there are no pending events so that a write isn't queued.
507      vim.api.nvim_chan_send(vim.bo.channel, '\027]2;OTHER_TITLE\007')
508      vim.uv.sleep(50) -- Block the event loop and wait for tty-test to forward OSC 2.
509      local term_title = vim.b.term_title
510      vim.api.nvim_buf_delete(0, { force = true })
511      vim.wait(10, nil, nil, true) -- Process fast events only.
512      return term_title
513    end)
514    -- Title isn't changed until the second vim.wait().
515    eq('SOME_TITLE', title_before_del)
516    screen:expect([[
517      ^                                                  |
518      {100:~                                                 }|*5
519                                                        |
520    ]])
521    assert_alive()
522  end)
523
524  describe('handles suspended PTY process', function()
525    if skip(is_os('win'), 'N/A for Windows') then
526      return
527    end
528
529    --- @param external_resume boolean
530    local function test_term_process_suspend_resume(external_resume)
531      command('set mousemodel=extend')
532      local pid = eval('jobpid(&channel)')
533      vim.uv.kill(pid, 'sigstop')
534      -- In Terminal mode the cursor is at the "[Process suspended]" text to hint that
535      -- pressing a key will change the suspended state.
536      local s0 = [[
537        tty ready                                         |
538                                                          |*4
539        ^[Process suspended]                               |
540        {5:-- TERMINAL --}                                    |
541      ]]
542      screen:expect(s0)
543      feed([[<C-\><C-N>]])
544      -- Returning to Normal mode puts the cursor at its previous position as that's
545      -- closer to the terminal output, making it easier for the user to copy.
546      screen:expect([[
547        tty ready                                         |
548        ^                                                  |
549                                                          |*3
550        [Process suspended]                               |
551                                                          |
552      ]])
553      feed('i')
554      screen:expect(s0)
555      command('set laststatus=0 | botright vsplit')
556      screen:expect([[
557        tty ready               │tty ready                |
558                                │                         |*4
559        [Process suspended]     │^[Process suspended]      |
560        {5:-- TERMINAL --}                                    |
561      ]])
562      -- Resize is detected by the process on resume.
563      if external_resume then
564        vim.uv.kill(pid, 'sigcont')
565      else
566        feed('a')
567      end
568      screen:expect([[
569        tty ready               │tty ready                |
570        rows: 6, cols: 25       │rows: 6, cols: 25        |
571                                │^                         |
572                                │                         |*3
573        {5:-- TERMINAL --}                                    |
574      ]])
575      tt.enable_mouse()
576      tt.feed_data('mouse enabled\n\n\n\n')
577      screen:expect([[
578        rows: 6, cols: 25       │rows: 6, cols: 25        |
579        mouse enabled           │mouse enabled            |
580                                │                         |*3
581                                │^                         |
582        {5:-- TERMINAL --}                                    |
583      ]])
584      api.nvim_input_mouse('right', 'press', '', 0, 0, 25)
585      screen:expect({ any = vim.pesc('"!!^') })
586      api.nvim_input_mouse('right', 'release', '', 0, 0, 25)
587      screen:expect({ any = vim.pesc('#!!^') })
588      vim.uv.kill(pid, 'sigstop')
589      local s1 = [[
590        rows: 6, cols: 25       │rows: 6, cols: 25        |
591        mouse enabled           │mouse enabled            |
592                                │                         |*3
593        [Process suspended]     │^[Process suspended]      |
594        {5:-- TERMINAL --}                                    |
595      ]]
596      screen:expect(s1)
597      -- Mouse isn't forwarded when process is suspended.
598      api.nvim_input_mouse('right', 'press', '', 0, 1, 27)
599      api.nvim_input_mouse('right', 'release', '', 0, 1, 27)
600      screen:expect([[
601        rows: 6, cols: 25       │rows: 6, cols: 25        |
602        mo{108:use enabled}           │mo{108:^use enabled}            |
603        {108: }                       │{108: }                        |*3
604        [Process suspended]     │[Process suspended]      |
605        {5:-- VISUAL --}                                      |
606      ]])
607      feed('<Esc>i')
608      screen:expect(s1)
609      if external_resume then
610        vim.uv.kill(pid, 'sigcont')
611      else
612        feed('a')
613      end
614      screen:expect([[
615        rows: 6, cols: 25       │rows: 6, cols: 25        |
616        mouse enabled           │mouse enabled            |
617                                │                         |*3
618           #!!                  │   #!!^                   |
619        {5:-- TERMINAL --}                                    |
620      ]])
621      -- Mouse is forwarded after process is resumed.
622      api.nvim_input_mouse('right', 'press', '', 0, 0, 28)
623      screen:expect({ any = vim.pesc('"$!^') })
624      api.nvim_input_mouse('right', 'release', '', 0, 0, 28)
625      screen:expect({ any = vim.pesc('#$!^') })
626    end
627
628    it('resumed by an external signal', function()
629      skip(is_os('mac'), 'FIXME: does not work on macOS')
630      test_term_process_suspend_resume(true)
631    end)
632
633    it('resumed by pressing a key', function()
634      test_term_process_suspend_resume(false)
635    end)
636  end)
637end)
638
639describe(':terminal buffer', function()
640  before_each(clear)
641
642  it('exit emits FileChangedShell #41759', function()
643    local path = t.tmpname()
644    write_file(path, 'foo\n')
645    command('edit ' .. path)
646    command('set noautoread') -- Disable 'autoread' to exercise :checktime specifically.
647    api.nvim_buf_set_lines(0, 0, -1, true, { 'local change' })
648    n.exec('let g:fcs = 0 | autocmd FileChangedShell * let g:fcs = 1')
649    write_file(path, 'external change\n')
650
651    -- Terminal in another tab, so returning to the buffer is not what triggers the check.
652    command('tabnew')
653    fn.jobstart({ testprg('shell-test'), 'EXIT', '0' }, { term = true })
654    retry(nil, 10000, function()
655      eq(1, api.nvim_get_var('fcs'))
656    end)
657  end)
658
659  it('can resume suspended PTY process running in fish', function()
660    skip(is_os('win'), 'N/A for Windows')
661    skip(fn.executable('fish') == 0, 'missing "fish" command')
662
663    local screen = Screen.new(50, 7)
664    screen:add_extra_attr_ids({
665      [100] = {
666        foreground = Screen.colors.NvimDarkGrey2,
667        background = Screen.colors.NvimLightGrey2,
668      },
669      [101] = {
670        foreground = Screen.colors.NvimLightGrey4,
671        background = Screen.colors.NvimLightGrey2,
672      },
673      [102] = {
674        foreground = Screen.colors.NvimDarkGrey2,
675        background = Screen.colors.NvimLightGrey4,
676      },
677    })
678    command('set shell=fish termguicolors')
679    command(('terminal %s -u NONE -i NONE'):format(fn.shellescape(nvim_prog)))
680    command('startinsert')
681    local s0 = [[
682      {100:^                                                  }|
683      {101:~                                                 }|*3
684      {102:[No Name]                       0,0-1          All}|
685      {100:                                                  }|
686      {5:-- TERMINAL --}                                    |
687    ]]
688    screen:expect(s0)
689    feed('<C-Z>')
690    screen:expect([[
691                                                        |*5
692      ^[Process suspended]                               |
693      {5:-- TERMINAL --}                                    |
694    ]])
695    feed('<Space>')
696    screen:expect(s0)
697  end)
698
699  it('term_close() use-after-free #4393', function()
700    command('terminal yes')
701    feed('<Ignore>') -- Add input to separate two RPC requests
702    command('bdelete!')
703  end)
704
705  describe('TermRequest', function()
706    it('emits events #26972', function()
707      local term = api.nvim_open_term(0, {})
708      local termbuf = api.nvim_get_current_buf()
709
710      -- Test that <abuf> is the terminal buffer, not the current buffer
711      command('au TermRequest * let g:termbuf = +expand("<abuf>")')
712      command('wincmd p')
713
714      -- cwd will be inserted in a file URI, which cannot contain backs
715      local cwd = t.fix_slashes(fn.getcwd())
716      local parent = cwd:match('^(.+/)')
717      local expected = '\027]7;file://host' .. parent
718      api.nvim_chan_send(term, string.format('%s\027\\', expected))
719      eq(expected, eval('v:termrequest'))
720      eq(termbuf, eval('g:termbuf'))
721    end)
722
723    it('emits events for APC', function()
724      local term = api.nvim_open_term(0, {})
725
726      -- cwd will be inserted in a file URI, which cannot contain backs
727      local cwd = t.fix_slashes(fn.getcwd())
728      local parent = cwd:match('^(.+/)')
729      local expected = '\027_Gfile://host' .. parent
730      api.nvim_chan_send(term, string.format('%s\027\\', expected))
731      eq(expected, eval('v:termrequest'))
732    end)
733
734    it('synchronization #27572', function()
735      command('autocmd! nvim.terminal TermRequest')
736      local term = exec_lua([[
737        _G.input = {}
738        local term = vim.api.nvim_open_term(0, {
739          on_input = function(_, _, _, data)
740            table.insert(_G.input, data)
741          end,
742          force_crlf = false,
743        })
744        vim.api.nvim_create_autocmd('TermRequest', {
745          callback = function(ev)
746            if ev.data.sequence == '\027]11;?' then
747              table.insert(_G.input, '\027]11;rgb:0000/0000/0000\027\\')
748            end
749          end
750        })
751        return term
752      ]])
753      api.nvim_chan_send(term, '\027]11;?\007\027[5n\027]11;?\007\027[5n')
754      eq({
755        '\027]11;rgb:0000/0000/0000\027\\',
756        '\027[0n',
757        '\027]11;rgb:0000/0000/0000\027\\',
758        '\027[0n',
759      }, exec_lua('return _G.input'))
760    end)
761
762    it('works with vim.wait() from another autocommand #32706', function()
763      command('autocmd! nvim.terminal TermRequest')
764      exec_lua([[
765        local term = vim.api.nvim_open_term(0, {})
766        vim.api.nvim_create_autocmd('TermRequest', {
767          buf = 0,
768          callback = function(ev)
769            _G.sequence = ev.data.sequence
770            _G.v_termrequest = vim.v.termrequest
771          end,
772        })
773        vim.api.nvim_create_autocmd('TermEnter', {
774          buf = 0,
775          callback = function()
776            vim.api.nvim_chan_send(term, '\027]11;?\027\\')
777            _G.result = vim.wait(3000, function()
778              local expected = '\027]11;?'
779              return _G.sequence == expected and _G.v_termrequest == expected
780            end)
781          end,
782        })
783      ]])
784      feed('i')
785      retry(nil, 4000, function()
786        eq(true, exec_lua('return _G.result'))
787      end)
788    end)
789
790    it('includes cursor position #31609', function()
791      command('autocmd! nvim.terminal TermRequest')
792      local screen = Screen.new(50, 10)
793      local term = exec_lua([[
794        _G.cursor = {}
795        local term = vim.api.nvim_open_term(0, {})
796        vim.api.nvim_create_autocmd('TermRequest', {
797          callback = function(ev)
798            _G.cursor = ev.data.cursor
799          end
800        })
801        return term
802      ]])
803      -- Enter terminal mode so that the cursor follows the output
804      feed('a')
805
806      -- Put some lines into the scrollback. This tests the conversion from terminal line to buffer
807      -- line.
808      api.nvim_chan_send(term, string.rep('>\n', 20))
809      screen:expect([[
810        >                                                 |*8
811        ^                                                  |
812        {5:-- TERMINAL --}                                    |
813      ]])
814
815      -- Emit an OSC escape sequence
816      api.nvim_chan_send(term, 'Hello\nworld!\027]133;D\027\\')
817      screen:expect([[
818        >                                                 |*7
819        Hello                                             |
820        world!^                                            |
821        {5:-- TERMINAL --}                                    |
822      ]])
823      eq({ 22, 6 }, exec_lua('return _G.cursor'))
824
825      api.nvim_chan_send(term, '\nHello\027]133;D\027\\\nworld!\n')
826      screen:expect([[
827        >                                                 |*4
828        Hello                                             |
829        world!                                            |
830        Hello                                             |
831        world!                                            |
832        ^                                                  |
833        {5:-- TERMINAL --}                                    |
834      ]])
835      eq({ 23, 5 }, exec_lua('return _G.cursor'))
836
837      api.nvim_chan_send(term, 'Hello\027]133;D\027\\\nworld!' .. ('\n'):rep(6))
838      screen:expect([[
839        world!                                            |
840        Hello                                             |
841        world!                                            |
842                                                          |*5
843        ^                                                  |
844        {5:-- TERMINAL --}                                    |
845      ]])
846      eq({ 25, 5 }, exec_lua('return _G.cursor'))
847
848      api.nvim_set_option_value('scrollback', 10, {})
849      eq(19, api.nvim_buf_line_count(0))
850
851      api.nvim_chan_send(term, 'Hello\nworld!\027]133;D\027\\')
852      screen:expect([[
853        Hello                                             |
854        world!                                            |
855                                                          |*5
856        Hello                                             |
857        world!^                                            |
858        {5:-- TERMINAL --}                                    |
859      ]])
860      eq({ 19, 6 }, exec_lua('return _G.cursor'))
861
862      api.nvim_chan_send(term, '\nHello\027]133;D\027\\\nworld!\n')
863      screen:expect([[
864                                                          |*4
865        Hello                                             |
866        world!                                            |
867        Hello                                             |
868        world!                                            |
869        ^                                                  |
870        {5:-- TERMINAL --}                                    |
871      ]])
872      eq({ 17, 5 }, exec_lua('return _G.cursor'))
873
874      api.nvim_chan_send(term, 'Hello\027]133;D\027\\\nworld!' .. ('\n'):rep(6))
875      screen:expect([[
876        world!                                            |
877        Hello                                             |
878        world!                                            |
879                                                          |*5
880        ^                                                  |
881        {5:-- TERMINAL --}                                    |
882      ]])
883      eq({ 12, 5 }, exec_lua('return _G.cursor'))
884
885      api.nvim_chan_send(term, 'Hello\027]133;D\027\\\nworld!' .. ('\n'):rep(8))
886      screen:expect([[
887        world!                                            |
888                                                          |*7
889        ^                                                  |
890        {5:-- TERMINAL --}                                    |
891      ]])
892      eq({ 10, 5 }, exec_lua('return _G.cursor'))
893
894      api.nvim_chan_send(term, 'Hello\027]133;D\027\\\nworld!' .. ('\n'):rep(20))
895      screen:expect([[
896                                                          |*8
897        ^                                                  |
898        {5:-- TERMINAL --}                                    |
899      ]])
900      eq({ -2, 5 }, exec_lua('return _G.cursor'))
901    end)
902
903    it('does not cause hang in vim.wait() #32753', function()
904      local screen = Screen.new(50, 10)
905
906      exec_lua(function()
907        local term = vim.api.nvim_open_term(0, {})
908
909        -- Write OSC sequence with pending scrollback. TermRequest will
910        -- reschedule itself onto an event queue until the pending scrollback is
911        -- processed (i.e. the terminal is refreshed).
912        vim.api.nvim_chan_send(term, string.format('%s\027]133;;\007', string.rep('a\n', 100)))
913
914        -- vim.wait() drains the event queue. The terminal won't be refreshed
915        -- until the event queue is empty. This test ensures that TermRequest
916        -- does not continuously reschedule itself onto the same event queue,
917        -- causing an infinite loop.
918        vim.wait(100)
919      end)
920
921      screen:expect([[
922        ^a                                                 |
923        a                                                 |*8
924                                                          |
925      ]])
926    end)
927
928    describe('no heap-use-after-free after', function()
929      local term
930
931      before_each(function()
932        term = exec_lua(function()
933          vim.api.nvim_create_autocmd('TermRequest', { callback = function() end })
934          return vim.api.nvim_open_term(0, {})
935        end)
936      end)
937
938      it('wiping buffer with pending TermRequest #37226', function()
939        exec_lua(function()
940          vim.api.nvim_chan_send(term, '\027]8;;https://example.com\027\\')
941          vim.api.nvim_buf_delete(0, { force = true })
942        end)
943        assert_alive()
944      end)
945
946      it('unloading buffer with pending TermRequest #37226', function()
947        api.nvim_create_buf(true, false) -- Create a buffer to switch to.
948        exec_lua(function()
949          vim.api.nvim_chan_send(term, '\027]8;;https://example.com\027\\')
950          vim.api.nvim_buf_delete(0, { force = true, unload = true })
951        end)
952        assert_alive()
953      end)
954    end)
955  end)
956
957  it('no heap-buffer-overflow when using jobstart("echo",{term=true}) #3161', function()
958    local testfilename = 'Xtestfile-functional-terminal-buffers_spec'
959    write_file(testfilename, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')
960    finally(function()
961      os.remove(testfilename)
962    end)
963    feed(':edit ' .. testfilename .. '<CR>')
964    -- Move cursor away from the beginning of the line
965    feed('$')
966    -- Let jobstart(…,{term=true}) modify the buffer
967    fn.jobstart('echo', { term = true })
968    assert_alive()
969    command('bdelete!')
970  end)
971
972  it('no heap-buffer-overflow when sending long line with nowrap #11548', function()
973    command('set nowrap | autocmd TermOpen * startinsert')
974    feed(':call feedkeys("4000ai\\<esc>:terminal!\\<cr>")<CR>')
975    assert_alive()
976  end)
977
978  it('truncates the size of grapheme clusters', function()
979    local chan = api.nvim_open_term(0, {})
980    local composing = ('a̳'):sub(2)
981    api.nvim_chan_send(chan, 'a' .. composing:rep(20))
982    retry(nil, nil, function()
983      eq('a' .. composing:rep(14), api.nvim_get_current_line())
984    end)
985  end)
986
987  it('handles extended grapheme clusters', function()
988    local screen = Screen.new(50, 7)
989    feed 'i'
990    local chan = api.nvim_open_term(0, {})
991    api.nvim_chan_send(chan, '🏴‍☠️ yarrr')
992    screen:expect([[
993      🏴‍☠️ yarrr^                                          |
994                                                        |*5
995      {5:-- TERMINAL --}                                    |
996    ]])
997    eq('🏴‍☠️ yarrr', api.nvim_get_current_line())
998  end)
999
1000  it('handles split UTF-8 sequences #16245', function()
1001    local screen = Screen.new(50, 10)
1002    fn.jobstart({ testprg('shell-test'), 'UTF-8' }, { term = true })
1003    screen:expect([[
1004      ^å                                                 |
1005      ref: å̲                                            |
1006      1: å̲                                              |
1007      2: å̲                                              |
1008      3: å̲                                              |
1009                                                        |
1010      [Process exited 0]                                |
1011                                                        |*3
1012    ]])
1013    -- Test with Unicode char at right edge using a 4-wide terminal
1014    command('bwipe! | set laststatus=0 | 4vnew')
1015    fn.jobstart({ testprg('shell-test'), 'UTF-8' }, { term = true })
1016    screen:expect([[
1017      ^å   │                                             |
1018      ref:│{1:~                                            }|
1019       å̲  │{1:~                                            }|
1020      1: å̲│{1:~                                            }|
1021      2: å̲│{1:~                                            }|
1022      3: å̲│{1:~                                            }|
1023          │{1:~                                            }|
1024      [Pro│{1:~                                            }|
1025          │{1:~                                            }|
1026                                                        |
1027    ]])
1028  end)
1029
1030  --- @param subcmd 'REP'|'REPFAST'
1031  local function check_term_rep(subcmd, count, scrollback)
1032    local screen = Screen.new(50, 7)
1033    api.nvim_set_option_value('scrollback', scrollback, {})
1034    api.nvim_create_autocmd('TermClose', { command = 'let g:did_termclose = 1' })
1035    fn.jobstart({ testprg('shell-test'), subcmd, count, 'TEST' }, { term = true })
1036    retry(nil, 10000 + count, function()
1037      eq(1, api.nvim_get_var('did_termclose'))
1038    end)
1039    feed('i')
1040    screen:expect(([[
1041      %d: TEST{MATCH: +}|
1042      %d: TEST{MATCH: +}|
1043      %d: TEST{MATCH: +}|
1044      %d: TEST{MATCH: +}|
1045      %d: TEST{MATCH: +}|
1046      ^[Process exited 0]                                |
1047      {5:-- TERMINAL --}                                    |
1048    ]]):format(count - 5, count - 4, count - 3, count - 2, count - 1))
1049    local lines = api.nvim_buf_get_lines(0, 0, -1, true)
1050    local start = math.max(count + 1 - scrollback - 6, 0)
1051    for i = start, count - 1 do
1052      eq(('%d: TEST'):format(i), lines[i - start + 1])
1053    end
1054    eq('', lines[#lines])
1055    eq(count - start + 1, #lines)
1056  end
1057
1058  it('does not drop data when job exits immediately after output #3030', function()
1059    check_term_rep('REPFAST', 20000, 30000)
1060  end)
1061
1062  it('does not drop data when autocommands poll for events #37559', function()
1063    api.nvim_create_autocmd('BufFilePre', { command = 'sleep 50m', nested = true })
1064    api.nvim_create_autocmd('BufFilePost', { command = 'sleep 50m', nested = true })
1065    api.nvim_create_autocmd('TermOpen', { command = 'sleep 50m', nested = true })
1066    -- REP pauses 1 ms every 100 lines, so each autocommand processes some output.
1067    check_term_rep('REP', 20000, 30000)
1068  end)
1069
1070  describe('scrollback is correct if all output is drained by', function()
1071    for _, event in ipairs({ 'BufFilePre', 'BufFilePost', 'TermOpen' }) do
1072      describe(('%s autocommand that lasts for'):format(event), function()
1073        for _, delay in ipairs({ 5, 15, 25 }) do
1074          -- Terminal refresh delay is 10 ms.
1075          it(('%.1f * terminal refresh delay'):format(delay / 10), function()
1076            local cmd = ('sleep %dm'):format(delay)
1077            api.nvim_create_autocmd(event, { command = cmd, nested = true })
1078            check_term_rep('REPFAST', 200, 10000)
1079          end)
1080        end
1081      end)
1082    end
1083  end)
1084
1085  it('scrollback is correct if buffer update callbacks poll for uv events', function()
1086    -- Use vim.regex:match_str(), which may poll for uv events.
1087    exec_lua(function()
1088      local regex = vim.regex([[^\d\+: TEST]])
1089      _G.matched_lines = {} --- @type table<string,boolean>
1090      vim.api.nvim_create_autocmd('TermOpen', {
1091        callback = function(ev)
1092          vim.api.nvim_buf_attach(ev.buf, false, {
1093            on_lines = function(_, buf, _, first, _, last, _)
1094              local lines = vim.api.nvim_buf_get_lines(buf, first, last, true)
1095              for _, line in ipairs(lines) do
1096                if regex:match_str(line) then
1097                  _G.matched_lines[vim.trim(line)] = true
1098                end
1099              end
1100            end,
1101          })
1102        end,
1103      })
1104    end)
1105    -- Use a 'scrollback' value smaller than the number of printed lines.
1106    -- REP pauses 1 ms every 100 lines, so this can take at least 20 refresh cycles.
1107    check_term_rep('REP', 20000, 10000)
1108    -- Check that buffer update callbacks have seen all output lines.
1109    local matched_lines = exec_lua('return _G.matched_lines')
1110    for i = 0, 19999 do
1111      local line = ('%d: TEST'):format(i)
1112      eq(true, matched_lines[line], line)
1113    end
1114  end)
1115
1116  it('handles unprintable chars', function()
1117    local screen = Screen.new(50, 7)
1118    feed 'i'
1119    local chan = api.nvim_open_term(0, {})
1120    api.nvim_chan_send(chan, '\239\187\191') -- '\xef\xbb\xbf'
1121    screen:expect([[
1122      {18:<feff>}^                                            |
1123                                                        |*5
1124      {5:-- TERMINAL --}                                    |
1125    ]])
1126    eq('\239\187\191', api.nvim_get_current_line())
1127  end)
1128
1129  it("handles bell respecting 'belloff' and 'visualbell'", function()
1130    local screen = Screen.new(50, 7)
1131    local chan = api.nvim_open_term(0, {})
1132
1133    command('set belloff=')
1134    api.nvim_chan_send(chan, '\a')
1135    screen:expect(function()
1136      eq({ true, false }, { screen.bell, screen.visual_bell })
1137    end)
1138    screen.bell = false
1139
1140    command('set visualbell')
1141    api.nvim_chan_send(chan, '\a')
1142    screen:expect(function()
1143      eq({ false, true }, { screen.bell, screen.visual_bell })
1144    end)
1145    screen.visual_bell = false
1146
1147    command('set belloff=term')
1148    api.nvim_chan_send(chan, '\a')
1149    screen:expect({
1150      condition = function()
1151        eq({ false, false }, { screen.bell, screen.visual_bell })
1152      end,
1153      unchanged = true,
1154    })
1155
1156    command('set belloff=all')
1157    api.nvim_chan_send(chan, '\a')
1158    screen:expect({
1159      condition = function()
1160        eq({ false, false }, { screen.bell, screen.visual_bell })
1161      end,
1162      unchanged = true,
1163    })
1164  end)
1165
1166  it('does not wipeout unrelated buffer after channel closes', function()
1167    local screen = Screen.new(50, 7)
1168    screen:set_default_attr_ids({
1169      [1] = { foreground = Screen.colors.Blue1, bold = true },
1170      [2] = { reverse = true },
1171      [31] = { background = Screen.colors.DarkGreen, foreground = Screen.colors.White, bold = true },
1172    })
1173
1174    local old_buf = api.nvim_get_current_buf()
1175    command('new')
1176    fn.chanclose(api.nvim_open_term(0, {}))
1177    local term_buf = api.nvim_get_current_buf()
1178    screen:expect([[
1179      ^                                                  |
1180      [Terminal closed]                                 |
1181      {31:[Scratch] [-]                                     }|
1182                                                        |
1183      {1:~                                                 }|
1184      {2:[No Name]                                         }|
1185                                                        |
1186    ]])
1187
1188    -- Autocommand should not result in the wrong buffer being wiped out.
1189    command('autocmd TermLeave * ++once wincmd p')
1190    feed('ii')
1191    screen:expect([[
1192      ^                                                  |
1193      {1:~                                                 }|*5
1194                                                        |
1195    ]])
1196    eq(old_buf, api.nvim_get_current_buf())
1197    eq(false, api.nvim_buf_is_valid(term_buf))
1198
1199    term_buf = api.nvim_get_current_buf()
1200    fn.chanclose(api.nvim_open_term(term_buf, {}))
1201    screen:expect([[
1202      ^                                                  |
1203      [Terminal closed]                                 |
1204                                                        |*5
1205    ]])
1206
1207    -- Autocommand should not result in a heap UAF if it frees the terminal prematurely.
1208    command('autocmd TermLeave * ++once bwipeout!')
1209    feed('ii')
1210    screen:expect([[
1211      ^                                                  |
1212      {1:~                                                 }|*5
1213                                                        |
1214    ]])
1215    eq(false, api.nvim_buf_is_valid(term_buf))
1216  end)
1217
1218  it('no heap-use-after-free from autocmds when entering terminal mode', function()
1219    local buf = api.nvim_get_current_buf()
1220    local chan = api.nvim_open_term(0, {})
1221    command('autocmd TermEnter,ModeChanged * ++once bwipeout!')
1222    feed('i')
1223    eq(false, api.nvim_buf_is_valid(buf))
1224    eq({}, api.nvim_get_chan_info(chan))
1225    eq('n', fn.mode())
1226
1227    -- Remain in Terminal mode if autocmds put us in a different terminal.
1228    buf = api.nvim_get_current_buf()
1229    chan = api.nvim_open_term(0, {})
1230    command('autocmd TermEnter,ModeChanged * ++once bwipeout! | let g:chan = nvim_open_term(0, {})')
1231    feed('i')
1232    eq(false, api.nvim_buf_is_valid(buf))
1233    eq({}, api.nvim_get_chan_info(chan))
1234    eq(api.nvim_get_current_buf(), api.nvim_get_chan_info(eval('g:chan')).buffer)
1235    eq('t', fn.mode())
1236  end)
1237
1238  local enew_screen = [[
1239    ^                                                  |
1240    {1:~                                                 }|*5
1241                                                      |
1242  ]]
1243
1244  local function test_enew_in_buf_with_running_term(env)
1245    describe('editing a new file', function()
1246      it('hides terminal buffer ignoring bufhidden=wipe', function()
1247        local old_snapshot = env.screen:get_snapshot()
1248        command('setlocal bufhidden=wipe')
1249        command('enew')
1250        neq(env.buf, api.nvim_get_current_buf())
1251        env.screen:expect(enew_screen)
1252        feed('<C-^>')
1253        eq(env.buf, api.nvim_get_current_buf())
1254        env.screen:expect(old_snapshot)
1255      end)
1256    end)
1257  end
1258
1259  local function test_open_term_in_buf_with_running_term(env)
1260    describe('does not allow opening another terminal', function()
1261      it('with jobstart() in same buffer', function()
1262        eq(
1263          ('Vim:Terminal already connected to buffer %d'):format(env.buf),
1264          pcall_err(fn.jobstart, { testprg('tty-test') }, { term = true })
1265        )
1266        env.screen:expect_unchanged()
1267      end)
1268
1269      it('with nvim_open_term() in same buffer', function()
1270        eq(
1271          ('Terminal already connected to buffer %d'):format(env.buf),
1272          pcall_err(api.nvim_open_term, env.buf, {})
1273        )
1274        env.screen:expect_unchanged()
1275      end)
1276    end)
1277  end
1278
1279  describe('with running terminal job', function()
1280    local env = {}
1281
1282    before_each(function()
1283      env.screen = Screen.new(50, 7)
1284      fn.jobstart({ testprg('tty-test') }, { term = true })
1285      env.screen:expect([[
1286        ^tty ready                                         |
1287                                                          |*6
1288      ]])
1289      env.buf = api.nvim_get_current_buf()
1290      api.nvim_set_option_value('modified', false, { buf = env.buf })
1291    end)
1292
1293    test_enew_in_buf_with_running_term(env)
1294    test_open_term_in_buf_with_running_term(env)
1295  end)
1296
1297  describe('with open nvim_open_term() channel', function()
1298    local env = {}
1299
1300    before_each(function()
1301      env.screen = Screen.new(50, 7)
1302      local chan = api.nvim_open_term(0, {})
1303      api.nvim_chan_send(chan, 'TEST')
1304      env.screen:expect([[
1305        ^TEST                                              |
1306                                                          |*6
1307      ]])
1308      env.buf = api.nvim_get_current_buf()
1309      api.nvim_set_option_value('modified', false, { buf = env.buf })
1310    end)
1311
1312    test_enew_in_buf_with_running_term(env)
1313    test_open_term_in_buf_with_running_term(env)
1314  end)
1315
1316  local function test_enew_in_buf_with_finished_term(env)
1317    describe('editing a new file', function()
1318      it('hides terminal buffer with bufhidden=hide', function()
1319        local old_snapshot = env.screen:get_snapshot()
1320        command('setlocal bufhidden=hide')
1321        command('enew')
1322        neq(env.buf, api.nvim_get_current_buf())
1323        env.screen:expect(enew_screen)
1324        feed('<C-^>')
1325        eq(env.buf, api.nvim_get_current_buf())
1326        env.screen:expect(old_snapshot)
1327      end)
1328
1329      it('wipes terminal buffer with bufhidden=wipe', function()
1330        command('setlocal bufhidden=wipe')
1331        command('enew')
1332        neq(env.buf, api.nvim_get_current_buf())
1333        eq(false, api.nvim_buf_is_valid(env.buf))
1334        env.screen:expect(enew_screen)
1335        feed('<C-^>')
1336        env.screen:expect([[
1337          ^                                                  |
1338          {1:~                                                 }|*5
1339          {9:E23: No alternate file}                            |
1340        ]])
1341      end)
1342    end)
1343  end
1344
1345  local function test_open_term_in_buf_with_finished_term(env)
1346    describe('does not leak memory when opening another terminal', function()
1347      describe('with jobstart() in same buffer', function()
1348        it('in Normal mode', function()
1349          fn.jobstart({ testprg('tty-test') }, { term = true })
1350          env.screen:expect([[
1351            ^tty ready                                         |
1352                                                              |*6
1353          ]])
1354        end)
1355
1356        it('in Terminal mode', function()
1357          feed('i')
1358          eq({ blocking = false, mode = 't' }, api.nvim_get_mode())
1359          fn.jobstart({ testprg('tty-test') }, { term = true })
1360          env.screen:expect([[
1361            tty ready                                         |
1362            ^                                                  |
1363                                                              |*4
1364            {5:-- TERMINAL --}                                    |
1365          ]])
1366        end)
1367      end)
1368
1369      describe('with nvim_open_term() in same buffer', function()
1370        it('in Normal mode', function()
1371          local chan = api.nvim_open_term(env.buf, {})
1372          api.nvim_chan_send(chan, 'OTHER')
1373          env.screen:expect([[
1374            ^OTHER                                             |
1375                                                              |*6
1376          ]])
1377        end)
1378
1379        it('in Terminal mode', function()
1380          feed('i')
1381          eq({ blocking = false, mode = 't' }, api.nvim_get_mode())
1382          local chan = api.nvim_open_term(env.buf, {})
1383          api.nvim_chan_send(chan, 'OTHER')
1384          env.screen:expect([[
1385            OTHER^                                             |
1386                                                              |*5
1387            {5:-- TERMINAL --}                                    |
1388          ]])
1389        end)
1390      end)
1391    end)
1392  end
1393
1394  describe('with exited terminal job', function()
1395    local env = {}
1396
1397    before_each(function()
1398      env.screen = Screen.new(50, 7)
1399      fn.jobstart({ testprg('shell-test') }, { term = true })
1400      env.screen:expect([[
1401        ^ready $                                           |
1402        [Process exited 0]                                |
1403                                                          |*5
1404      ]])
1405      env.buf = api.nvim_get_current_buf()
1406      api.nvim_set_option_value('modified', false, { buf = env.buf })
1407    end)
1408
1409    test_enew_in_buf_with_finished_term(env)
1410    test_open_term_in_buf_with_finished_term(env)
1411  end)
1412
1413  describe('with closed nvim_open_term() channel', function()
1414    local env = {}
1415
1416    before_each(function()
1417      env.screen = Screen.new(50, 7)
1418      local chan = api.nvim_open_term(0, {})
1419      api.nvim_chan_send(chan, 'TEST')
1420      fn.chanclose(chan)
1421      env.screen:expect([[
1422        ^TEST                                              |
1423        [Terminal closed]                                 |
1424                                                          |*5
1425      ]])
1426      env.buf = api.nvim_get_current_buf()
1427      api.nvim_set_option_value('modified', false, { buf = env.buf })
1428    end)
1429
1430    test_enew_in_buf_with_finished_term(env)
1431    test_open_term_in_buf_with_finished_term(env)
1432  end)
1433
1434  it('with nvim_open_term() channel and only 1 line is not reused by :enew', function()
1435    command('1new')
1436    local oldbuf = api.nvim_get_current_buf()
1437    api.nvim_open_term(oldbuf, {})
1438    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1439    feed('i')
1440    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1441    feed([[<C-\><C-N>]])
1442    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1443
1444    command('enew')
1445    neq(oldbuf, api.nvim_get_current_buf())
1446    eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
1447    feed('i')
1448    eq({ mode = 'i', blocking = false }, api.nvim_get_mode())
1449    feed('<Esc>')
1450    eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
1451
1452    command('buffer #')
1453    eq(oldbuf, api.nvim_get_current_buf())
1454    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1455    feed('i')
1456    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1457    feed([[<C-\><C-N>]])
1458    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1459  end)
1460
1461  it('does not allow OptionSet or b:term_title watcher to delete buffer', function()
1462    local chan = exec_lua([[
1463      local au = vim.api.nvim_create_autocmd('OptionSet', { command = 'bwipeout!' })
1464      local chan = vim.api.nvim_open_term(0, {})
1465      vim.api.nvim_del_autocmd(au)
1466      return chan
1467    ]])
1468    matches('^E937: ', api.nvim_get_vvar('errmsg'))
1469    api.nvim_set_vvar('errmsg', '')
1470    api.nvim_chan_send(chan, '\027]2;SOME_TITLE\007')
1471    eq('SOME_TITLE', api.nvim_buf_get_var(0, 'term_title'))
1472    command([[call dictwatcheradd(b:, 'term_title', {-> execute('bwipe!')})]])
1473    api.nvim_chan_send(chan, '\027]2;OTHER_TITLE\007')
1474    eq('OTHER_TITLE', api.nvim_buf_get_var(0, 'term_title'))
1475    matches('^E937: ', api.nvim_get_vvar('errmsg'))
1476  end)
1477
1478  it('using NameBuff in BufFilePre does not interfere with buffer rename', function()
1479    local oldbuf = api.nvim_get_current_buf()
1480    n.exec([[
1481      file Xoldfile
1482      new Xotherfile
1483      wincmd w
1484      let g:BufFilePre_bufs = []
1485      let g:BufFilePost_bufs = []
1486      autocmd BufFilePre * call add(g:BufFilePre_bufs, [bufnr(), bufname()])
1487      autocmd BufFilePost * call add(g:BufFilePost_bufs, [bufnr(), bufname()])
1488      autocmd BufFilePre,BufFilePost * call execute('ls')
1489    ]])
1490    fn.jobstart({ testprg('shell-test') }, { term = true })
1491    eq({ { oldbuf, 'Xoldfile' } }, api.nvim_get_var('BufFilePre_bufs'))
1492    local buffilepost_bufs = api.nvim_get_var('BufFilePost_bufs')
1493    eq(1, #buffilepost_bufs)
1494    eq(oldbuf, buffilepost_bufs[1][1])
1495    matches('^term://', buffilepost_bufs[1][2])
1496  end)
1497
1498  it('double width char does not crash 1-wide terminal #41856', function()
1499    command('botright vnew')
1500    local screen = Screen.new(50, 7)
1501    local chan = api.nvim_open_term(0, {})
1502    screen:try_resize(25, 7)
1503    api.nvim_chan_send(chan, 'キ')
1504    assert_alive()
1505  end)
1506end)
1507
1508describe('on_lines does not emit out-of-bounds line indexes when', function()
1509  before_each(function()
1510    clear()
1511    exec_lua([[
1512      function _G.register_callback(bufnr)
1513        _G.cb_error = ''
1514        vim.api.nvim_buf_attach(bufnr, false, {
1515          on_lines = function(_, bufnr, _, firstline, _, _)
1516            local status, msg = pcall(vim.api.nvim_buf_get_offset, bufnr, firstline)
1517            if not status then
1518              _G.cb_error = msg
1519            end
1520          end
1521        })
1522      end
1523    ]])
1524  end)
1525
1526  it('creating a terminal buffer #16394', function()
1527    command('autocmd TermOpen * ++once call v:lua.register_callback(str2nr(expand("<abuf>")))')
1528    command('terminal')
1529    sleep(500)
1530    eq('', exec_lua([[return _G.cb_error]]))
1531  end)
1532
1533  it('deleting a terminal buffer #16394', function()
1534    command('terminal')
1535    sleep(500)
1536    local cb_error = exec_lua([[
1537      _G.register_callback(0)
1538      vim.cmd('bdelete!')
1539      return _G.cb_error
1540    ]])
1541    eq('', cb_error)
1542  end)
1543end)
1544
1545describe('terminal input', function()
1546  local chan --- @type integer
1547
1548  before_each(function()
1549    clear()
1550    chan = exec_lua(function()
1551      _G.input_data = ''
1552      return vim.api.nvim_open_term(0, {
1553        on_input = function(_, _, _, data)
1554          _G.input_data = _G.input_data .. data
1555        end,
1556      })
1557    end)
1558    feed('i')
1559    poke_eventloop()
1560  end)
1561
1562  it('<C-Space> is sent as NUL byte', function()
1563    feed('aaa<C-Space>bbb')
1564    eq('aaa\0bbb', exec_lua([[return _G.input_data]]))
1565  end)
1566
1567  it('unknown special keys are not sent', function()
1568    feed('aaa<Help>bbb')
1569    eq('aaabbb', exec_lua([[return _G.input_data]]))
1570  end)
1571
1572  it('<Ignore> is no-op', function()
1573    feed('aaa<Ignore>bbb')
1574    eq('aaabbb', exec_lua([[return _G.input_data]]))
1575    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1576    feed([[<C-\><Ignore><C-N>]])
1577    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1578    feed('v')
1579    eq({ mode = 'v', blocking = false }, api.nvim_get_mode())
1580    feed('<Esc>')
1581    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
1582    feed('i')
1583    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1584    feed([[<C-\><Ignore><C-O>]])
1585    eq({ mode = 'ntT', blocking = false }, api.nvim_get_mode())
1586    feed('v')
1587    eq({ mode = 'v', blocking = false }, api.nvim_get_mode())
1588    feed('<Esc>')
1589    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1590    fn.chanclose(chan)
1591    feed('<MouseMove>')
1592    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1593    feed('<Ignore>')
1594    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
1595    eq('terminal', api.nvim_get_option_value('buftype', { buf = 0 }))
1596    feed('<Space>')
1597    eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
1598    eq('', api.nvim_get_option_value('buftype', { buf = 0 }))
1599  end)
1600end)
1601
1602describe('terminal input', function()
1603  it('sends various special keys with modifiers', function()
1604    clear()
1605    local screen = tt.setup_child_nvim({
1606      '-u',
1607      'NONE',
1608      '-i',
1609      'NONE',
1610      '--cmd',
1611      'colorscheme vim',
1612      '--cmd',
1613      'set notermguicolors',
1614      '-c',
1615      'while 1 | redraw | echo keytrans(getcharstr(-1, #{simplify: 0})) | endwhile',
1616    })
1617    screen:expect([[
1618      ^                                                  |
1619      {100:~                                                 }|*3
1620      {3:[No Name]                       0,0-1          All}|
1621                                                        |
1622      {5:-- TERMINAL --}                                    |
1623    ]])
1624    local keys = {
1625      '<Tab>',
1626      '<CR>',
1627      '<Esc>',
1628      '<M-Tab>',
1629      '<M-CR>',
1630      '<M-Esc>',
1631      '<BS>',
1632      '<S-Tab>',
1633      '<Insert>',
1634      '<S-Insert>',
1635      '<Del>',
1636      '<S-Del>',
1637      '<PageUp>',
1638      '<PageDown>',
1639      '<S-Up>',
1640      '<C-Up>',
1641      '<Up>',
1642      '<S-Down>',
1643      '<C-Down>',
1644      '<Down>',
1645      '<S-Left>',
1646      '<C-Left>',
1647      '<Left>',
1648      '<S-Right>',
1649      '<C-Right>',
1650      '<Right>',
1651      '<S-Home>',
1652      '<C-Home>',
1653      '<Home>',
1654      '<S-End>',
1655      '<C-End>',
1656      '<End>',
1657      '<C-LeftMouse><0,0>',
1658      '<C-LeftDrag><0,1>',
1659      '<C-LeftRelease><0,1>',
1660      '<LeftMouse><0,1>',
1661      '<LeftRelease><0,1>',
1662      '<2-LeftMouse><0,1>',
1663      '<2-LeftDrag><0,0>',
1664      '<2-LeftRelease><0,0>',
1665      '<M-MiddleMouse><0,0>',
1666      '<M-MiddleDrag><0,1>',
1667      '<M-MiddleRelease><0,1>',
1668      '<MiddleMouse><0,1>',
1669      '<MiddleRelease><0,1>',
1670      '<2-MiddleMouse><0,1>',
1671      '<2-MiddleDrag><0,0>',
1672      '<2-MiddleRelease><0,0>',
1673      '<S-RightMouse><0,0>',
1674      '<S-RightDrag><0,1>',
1675      '<S-RightRelease><0,1>',
1676      '<RightMouse><0,1>',
1677      '<RightRelease><0,1>',
1678      '<2-RightMouse><0,1>',
1679      '<2-RightDrag><0,0>',
1680      '<2-RightRelease><0,0>',
1681      '<S-X1Mouse><0,0>',
1682      '<S-X1Drag><0,1>',
1683      '<S-X1Release><0,1>',
1684      '<X1Mouse><0,1>',
1685      '<X1Release><0,1>',
1686      '<2-X1Mouse><0,1>',
1687      '<2-X1Drag><0,0>',
1688      '<2-X1Release><0,0>',
1689      '<S-X2Mouse><0,0>',
1690      '<S-X2Drag><0,1>',
1691      '<S-X2Release><0,1>',
1692      '<X2Mouse><0,1>',
1693      '<X2Release><0,1>',
1694      '<2-X2Mouse><0,1>',
1695      '<2-X2Drag><0,0>',
1696      '<2-X2Release><0,0>',
1697      '<S-ScrollWheelUp>',
1698      '<S-ScrollWheelDown>',
1699      '<ScrollWheelUp>',
1700      '<ScrollWheelDown>',
1701      '<S-ScrollWheelLeft>',
1702      '<S-ScrollWheelRight>',
1703      '<ScrollWheelLeft>',
1704      '<ScrollWheelRight>',
1705    }
1706    -- FIXME: The escape sequence to enable kitty keyboard mode doesn't work on Windows
1707    if not is_os('win') then
1708      table.insert(keys, '<S-BS>')
1709      table.insert(keys, '<C-I>')
1710      table.insert(keys, '<C-M>')
1711      table.insert(keys, '<C-[>')
1712    end
1713    for _, key in ipairs(keys) do
1714      feed(key)
1715      screen:expect(([[
1716                                                          |
1717        {100:~                                                 }|*3
1718        {3:[No Name]                       0,0-1          All}|
1719        %s^ {MATCH: *}|
1720        {5:-- TERMINAL --}                                    |
1721      ]]):format(key:gsub('<%d+,%d+>$', '')))
1722    end
1723  end)
1724end)
1725
1726if is_os('win') then
1727  describe(':terminal in Windows', function()
1728    local screen
1729
1730    before_each(function()
1731      clear()
1732      command('set modifiable swapfile undolevels=20')
1733      poke_eventloop()
1734      local cmd = { 'cmd.exe', '/K', 'PROMPT=$g$s' }
1735      screen = tt.setup_screen(nil, cmd)
1736    end)
1737
1738    it('"put" operator sends data normally', function()
1739      feed('<c-\\><c-n>G')
1740      local s = ':: tty ready'
1741      fn.setreg('a', s .. '\n:: appended ' .. s .. '\n\n')
1742      feed('"ap"ap')
1743      screen:expect([[
1744                                                        |
1745      > :: tty ready                                    |
1746      > :: appended :: tty ready                        |
1747      > :: tty ready                                    |
1748      > :: appended :: tty ready                        |
1749      ^>                                                 |
1750                                                        |
1751      ]])
1752      -- operator count is also taken into consideration
1753      feed('3"ap')
1754      screen:expect([[
1755      > :: appended :: tty ready                        |
1756      > :: tty ready                                    |
1757      > :: appended :: tty ready                        |
1758      > :: tty ready                                    |
1759      > :: appended :: tty ready                        |
1760      ^>                                                 |
1761                                                        |
1762      ]])
1763    end)
1764
1765    it('":put" command sends data normally', function()
1766      feed('<c-\\><c-n>G')
1767      local s = ':: tty ready'
1768      fn.setreg('a', s .. '\n:: appended ' .. s .. '\n\n')
1769      feed(':put a<CR>')
1770      screen:expect([[
1771                                                        |
1772      > :: tty ready                                    |
1773      > :: appended :: tty ready                        |
1774      >                                                 |
1775                                                        |
1776      ^                                                  |
1777      :put a                                            |
1778      ]])
1779      -- line argument is only used to move the cursor
1780      feed(':6put a<CR>')
1781      screen:expect([[
1782                                                        |
1783      > :: tty ready                                    |
1784      > :: appended :: tty ready                        |
1785      > :: tty ready                                    |
1786      > :: appended :: tty ready                        |
1787      ^>                                                 |
1788      :6put a                                           |
1789      ]])
1790    end)
1791  end)
1792end
1793
1794describe('termopen() (deprecated alias to `jobstart(…,{term=true})`)', function()
1795  before_each(clear)
1796
1797  it('disallowed when textlocked', function()
1798    command("autocmd TextYankPost <buffer> ++once call termopen('foo')")
1799    matches(
1800      'Vim%(call%):E565: Not allowed to change text or change window$',
1801      pcall_err(command, 'normal! yy')
1802    )
1803
1804    feed('q:')
1805    eq('Vim:jobstart(...,{term=true}) requires unmodified buffer', pcall_err(fn.termopen, 'bar'))
1806  end)
1807end)
1808
1809describe('jobstart(…,{term=true})', function()
1810  before_each(clear)
1811
1812  describe('$COLORTERM value', function()
1813    before_each(function()
1814      -- Outer value should never be propagated to :terminal
1815      fn.setenv('COLORTERM', 'wrongvalue')
1816    end)
1817
1818    local function test_term_colorterm(expected, opts)
1819      local screen = Screen.new(50, 4)
1820      fn.jobstart({
1821        nvim_prog,
1822        '-u',
1823        'NONE',
1824        '-i',
1825        'NONE',
1826        '--headless',
1827        '-c',
1828        'echo $COLORTERM | quit',
1829      }, vim.tbl_extend('error', opts, { term = true }))
1830      screen:expect(([[
1831        ^%s{MATCH:%%s+}|
1832        [Process exited 0]                                |
1833                                                          |*2
1834      ]]):format(expected))
1835    end
1836
1837    describe("with 'notermguicolors'", function()
1838      before_each(function()
1839        command('set notermguicolors')
1840      end)
1841      it('is empty by default', function()
1842        test_term_colorterm('', {})
1843      end)
1844      it('can be overridden', function()
1845        test_term_colorterm('expectedvalue', { env = { COLORTERM = 'expectedvalue' } })
1846      end)
1847    end)
1848
1849    describe("with 'termguicolors'", function()
1850      before_each(function()
1851        command('set termguicolors')
1852      end)
1853      it('is "truecolor" by default', function()
1854        test_term_colorterm('truecolor', {})
1855      end)
1856      it('can be overridden', function()
1857        test_term_colorterm('expectedvalue', { env = { COLORTERM = 'expectedvalue' } })
1858      end)
1859    end)
1860  end)
1861end)