robin/laufey

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

Justin M. Keyesfix(cwd): stale buffer names after temp context-switch #41433b296666e41

master
59.7 KiB2133 linesraw
1-- This module contains the Screen class, a complete Nvim UI implementation
2-- designed for functional testing (verifying screen state, in particular).
3--
4-- Screen:expect() takes a string representing the expected screen state and an
5-- optional set of attribute identifiers for checking highlighted characters.
6--
7-- Example usage:
8--
9--     -- Attach a screen to the current Nvim instance.
10--     local screen = Screen.new(25, 10)
11--     -- Enter insert-mode and type some text.
12--     feed('ihello screen')
13--     -- Assert the expected screen state.
14--     screen:expect([[
15--       hello screen^             |
16--       {1:~                        }|*8
17--       {5:-- INSERT --}             |
18--     ]]) -- <- Last line is stripped
19--
20-- Since screen updates are received asynchronously, expect() actually specifies
21-- the _eventual_ screen state.
22--
23-- This is how expect() works:
24--  * It starts the event loop with a timeout.
25--  * Each time it receives an update it checks that against the expected state.
26--    * If the expected state matches the current state, the event loop will be
27--      stopped and expect() will return.
28--    * If the timeout expires, the last match error will be reported and the
29--      test will fail.
30--
31-- The 31 most common highlight groups are predefined, see init_colors() below.
32-- In this case "5" is a predefined highlight associated with the set composed of one
33-- attribute: bold. Note that since the {5:} markup is not a real part of the
34-- screen, the delimiter "|" moved to the right. Also, the highlighting of the
35-- NonText markers "~" is visible.
36--
37-- Tests will often share a group of extra attribute sets to expect(). Those can be
38-- defined at the beginning of a test:
39--
40--    screen:add_extra_attr_ids({
41--      [100] = { background = Screen.colors.Plum1, underline = true },
42--      [101] = { background = Screen.colors.Red1, bold = true, underline = true },
43--    })
44--
45-- To help write screen tests, see Screen:snapshot_util().
46-- To debug screen tests, see Screen:redraw_debug().
47
48local t = require('test.testutil')
49local n = require('test.functional.testnvim')()
50local uv = vim.uv
51
52local deepcopy = vim.deepcopy
53local shallowcopy = t.shallowcopy
54local concat_tables = t.concat_tables
55local pesc = vim.pesc
56local run_session = n.run_session
57local eq = t.eq
58local dedent = t.dedent
59local get_session = n.get_session
60local create_callindex = n.create_callindex
61
62local inspect = vim.inspect
63
64local function isempty(v)
65  return type(v) == 'table' and next(v) == nil
66end
67
68--- @class test.functional.ui.screen.Grid
69--- @field rows table[][]
70--- @field width integer
71--- @field height integer
72
73--- @class test.functional.ui.screen
74--- @field colors table<string,integer>
75--- @field colornames table<integer,string>
76--- @field uimeths table<string,function>
77--- @field options? table<string,any>
78--- @field timeout integer
79--- @field win_position table<integer,table<string,integer>>
80--- @field float_pos table<integer,table>
81--- @field cmdline table<integer,table>
82--- @field cmdline_hide_level integer?
83--- @field cmdline_block table[]
84--- @field hl_groups table<string,integer> Highlight group to attr ID map
85--- @field hl_names table<integer,string> Highlight ID to group map
86--- @field messages table<integer,table>
87--- @field private _cursor {grid:integer,row:integer,col:integer}
88--- @field private _grids table<integer,test.functional.ui.screen.Grid>
89--- @field private _grid_win_extmarks table<integer,table>
90--- @field private _attr_table table<integer,table>
91--- @field private _hl_info table<integer,table>
92--- @field private _stdout uv.uv_pipe_t?
93local Screen = {}
94Screen.__index = Screen
95
96local default_timeout_factor = 1
97if os.getenv('VALGRIND') then
98  default_timeout_factor = default_timeout_factor * 3
99end
100
101if os.getenv('CI') then
102  default_timeout_factor = default_timeout_factor * 3
103end
104
105local default_screen_timeout = default_timeout_factor * 3500
106
107local function _init_colors()
108  local session = get_session()
109  local status, rv = session:request('nvim_get_color_map')
110  if not status then
111    error('failed to get color map')
112  end
113  local colors = rv --- @type table<string,integer>
114  local colornames = {} --- @type table<integer,string>
115  for name, rgb in pairs(colors) do
116    -- we disregard the case that colornames might not be unique, as
117    -- this is just a helper to get any canonical name of a color
118    colornames[rgb] = name
119  end
120  Screen.colors = colors
121  Screen.colornames = colornames
122
123  Screen._global_default_attr_ids = {
124    [1] = { foreground = Screen.colors.Blue1, bold = true },
125    [2] = { reverse = true },
126    [3] = { bold = true, reverse = true },
127    [4] = { background = Screen.colors.LightMagenta },
128    [5] = { bold = true },
129    [6] = { foreground = Screen.colors.SeaGreen, bold = true },
130    [7] = { background = Screen.colors.Gray, foreground = Screen.colors.DarkBlue },
131    [8] = { foreground = Screen.colors.Brown },
132    [9] = { background = Screen.colors.Red, foreground = Screen.colors.Grey100 },
133    [10] = { background = Screen.colors.Yellow },
134    [11] = {
135      foreground = Screen.colors.Blue1,
136      background = Screen.colors.LightMagenta,
137      bold = true,
138    },
139    [12] = { background = Screen.colors.Gray },
140    [13] = { background = Screen.colors.LightGrey, foreground = Screen.colors.DarkBlue },
141    [14] = { background = Screen.colors.DarkGray, foreground = Screen.colors.LightGrey },
142    [15] = { foreground = Screen.colors.Brown, bold = true },
143    [16] = { foreground = Screen.colors.SlateBlue },
144    [17] = { background = Screen.colors.LightGrey, foreground = Screen.colors.Black },
145    [18] = { foreground = Screen.colors.Blue1 },
146    [19] = { foreground = Screen.colors.Red },
147    [20] = { background = Screen.colors.Yellow, foreground = Screen.colors.Red },
148    [21] = { background = Screen.colors.Grey90 },
149    [22] = { background = Screen.colors.LightBlue },
150    [23] = { foreground = Screen.colors.Blue1, background = Screen.colors.LightCyan, bold = true },
151    [24] = { background = Screen.colors.LightGrey, underline = true },
152    [25] = { foreground = Screen.colors.Cyan4 },
153    [26] = { foreground = Screen.colors.Fuchsia },
154    [27] = { background = Screen.colors.Red, bold = true },
155    [28] = { foreground = Screen.colors.SlateBlue, underline = true },
156    [29] = { foreground = Screen.colors.SlateBlue, bold = true },
157    [30] = { background = Screen.colors.Red },
158    [31] = { background = Screen.colors.Plum1, reverse = true },
159  }
160
161  Screen._global_hl_names = {}
162  for group in pairs(n.api.nvim_get_hl(0, {})) do
163    Screen._global_hl_names[n.api.nvim_get_hl_id_by_name(group)] = group
164  end
165end
166
167--- @class test.functional.ui.screen.Opts
168--- @field ext_linegrid? boolean
169--- @field ext_multigrid? boolean
170--- @field ext_newgrid? boolean
171--- @field ext_popupmenu? boolean
172--- @field ext_wildmenu? boolean
173--- @field rgb? boolean
174--- @field _debug_float? boolean
175
176--- @param width? integer
177--- @param height? integer
178--- @param options? test.functional.ui.screen.Opts
179--- @param session? test.Session|false
180--- @return test.functional.ui.screen
181function Screen.new(width, height, options, session)
182  if not Screen.colors then
183    _init_colors()
184  end
185
186  options = options or {}
187  if options.ext_linegrid == nil then
188    options.ext_linegrid = true
189  end
190
191  local self = setmetatable({
192    timeout = default_screen_timeout,
193    title = '',
194    icon = '',
195    bell = false,
196    update_menu = false,
197    visual_bell = false,
198    suspended = false,
199    mode = 'normal',
200    options = {},
201    pwd = '',
202    popupmenu = nil,
203    cmdline = {},
204    cmdline_block = {},
205    wildmenu_items = nil,
206    wildmenu_selected = nil,
207    win_position = {},
208    win_viewport = {},
209    win_viewport_margins = {},
210    float_pos = {},
211    msg_grid = nil,
212    msg_grid_pos = nil,
213    _session = nil,
214    rpc_async = false,
215    messages = {},
216    msg_history = {},
217    showmode = {},
218    showcmd = {},
219    ruler = {},
220    hl_groups = {},
221    hl_names = vim.deepcopy(Screen._global_hl_names),
222    _default_attr_ids = nil,
223    mouse_enabled = true,
224    _attrs = {},
225    _hl_info = { [0] = {} },
226    _attr_table = { [0] = { {}, {} } },
227    _clear_attrs = nil,
228    _new_attrs = false,
229    _width = width or 53,
230    _height = height or 14,
231    _options = options,
232    _grids = {},
233    _grid_win_extmarks = {},
234    _cursor = {
235      grid = 1,
236      row = 1,
237      col = 1,
238    },
239    _busy = false,
240    _stdout = nil,
241  }, Screen)
242
243  local function ui(method, ...)
244    if self.rpc_async then
245      self._session:notify('nvim_ui_' .. method, ...)
246    else
247      local status, rv = self._session:request('nvim_ui_' .. method, ...)
248      if not status then
249        error(rv[2])
250      end
251    end
252  end
253
254  self.uimeths = create_callindex(ui)
255
256  -- session is often nil, which implies the default session
257  if session ~= false then
258    self:attach(session)
259  end
260
261  return self
262end
263
264function Screen:set_default_attr_ids(attr_ids)
265  self._default_attr_ids = attr_ids
266  self._attrs_overridden = true
267end
268
269function Screen:add_extra_attr_ids(extra_attr_ids)
270  local attr_ids = vim.deepcopy(Screen._global_default_attr_ids)
271  for id, attr in pairs(extra_attr_ids) do
272    if type(id) == 'number' and id < 100 then
273      error('extra attr ids should be at least 100 or be strings')
274    end
275    attr_ids[id] = attr
276  end
277  self._default_attr_ids = attr_ids
278end
279
280function Screen:set_rgb_cterm(val)
281  self._rgb_cterm = val
282end
283
284--- @param fd number
285function Screen:set_stdout(fd)
286  self._stdout = assert(uv.new_pipe())
287  self._stdout:open(fd)
288end
289
290--- @param session? test.Session
291function Screen:attach(session)
292  session = session or get_session()
293  local options = self._options
294
295  if options.ext_linegrid == nil then
296    options.ext_linegrid = true
297  end
298
299  self._session = session
300  self._options = options
301  self._clear_attrs = (not options.ext_linegrid) and {} or nil
302  self:_handle_resize(self._width, self._height)
303  self.uimeths.attach(self._width, self._height, options)
304  if self._options.rgb == nil then
305    -- nvim defaults to rgb=true internally,
306    -- simplify test code by doing the same.
307    self._options.rgb = true
308  end
309  if self._options.ext_multigrid then
310    self._options.ext_linegrid = true
311  end
312
313  if self._default_attr_ids == nil then
314    self._default_attr_ids = Screen._global_default_attr_ids
315  end
316end
317
318function Screen:detach()
319  if self._stdout and not self._stdout:is_closing() then
320    self._stdout:close()
321  end
322  self._stdout = nil
323  self.uimeths.detach()
324  self._session = nil
325end
326
327function Screen:try_resize(columns, rows)
328  self._width = columns
329  self._height = rows
330  self.uimeths.try_resize(columns, rows)
331end
332
333function Screen:try_resize_grid(grid, columns, rows)
334  self.uimeths.try_resize_grid(grid, columns, rows)
335end
336
337--- @param option 'ext_linegrid'|'ext_multigrid'|'ext_popupmenu'|'ext_wildmenu'|'rgb'
338--- @param value boolean
339function Screen:set_option(option, value)
340  self.uimeths.set_option(option, value)
341  --- @diagnostic disable-next-line:no-unknown
342  self._options[option] = value
343end
344
345-- canonical order of ext keys, used  to generate asserts
346local ext_keys = {
347  'popupmenu',
348  'cmdline',
349  'cmdline_block',
350  'wildmenu_items',
351  'wildmenu_pos',
352  'messages',
353  'msg_history',
354  'showmode',
355  'showcmd',
356  'ruler',
357  'win_pos',
358  'float_pos',
359  'win_viewport',
360  'win_viewport_margins',
361}
362
363local expect_keys = {
364  grid = true,
365  attr_ids = true,
366  condition = true,
367  mouse_enabled = true,
368  any = true,
369  none = true,
370  mode = true,
371  unchanged = true,
372  intermediate = true,
373  reset = true,
374  timeout = true,
375  request_cb = true,
376  hl_groups = true,
377  extmarks = true,
378  win_pos = true,
379}
380
381for _, v in ipairs(ext_keys) do
382  expect_keys[v] = true
383end
384
385--- @class test.functional.ui.screen.Expect
386---
387--- Expected screen state (string). Each line represents a screen
388--- row. Last character of each row (typically "|") is stripped.
389--- Common indentation is stripped.
390--- "{MATCH:x}" in a line is matched against Lua pattern `x`.
391--- "*n" at the end of a line means it repeats `n` times.
392--- @field grid? string
393---
394--- Expected text attributes. Screen rows are transformed according
395--- to this table, as follows: each substring S composed of
396--- characters having the same attributes will be substituted by
397--- "{K:S}", where K is a key in `attr_ids`. Any unexpected
398--- attributes in the final state are an error.
399--- Use an empty table for a text-only (no attributes) expectation.
400--- Use screen:set_default_attr_ids() to define attributes for many
401--- expect() calls.
402--- @field attr_ids? table<integer,table<string,any>>
403---
404--- Expected win_extmarks accumulated for the grids. For each grid,
405--- the win_extmark messages are accumulated into an array.
406--- @field extmarks? table<integer,table>
407---
408--- Function asserting some arbitrary condition. Return value is
409--- ignored, throw an error (use eq() or similar) to signal failure.
410--- @field condition? fun()
411---
412--- Lua pattern string expected to match a screen line. NB: the
413--- following chars are magic characters
414---    ( ) . % + - * ? [ ^ $
415--- and must be escaped with a preceding % for a literal match.
416--- @field any? string|table<string>
417---
418--- Lua pattern string expected to not match a screen line. NB: the
419--- following chars are magic characters
420---    ( ) . % + - * ? [ ^ $
421--- and must be escaped with a preceding % for a literal match.
422--- @field none? string|table<string>
423---
424--- Expected mode as signaled by "mode_change" event
425--- @field mode? string
426---
427--- Test that the screen state is unchanged since the previous
428--- expect(...). Any flush event resulting in a different state is
429--- considered an error. Not observing any events until timeout
430--- is acceptable.
431--- @field unchanged? boolean
432---
433--- Test that the final state is the same as the previous expect,
434--- but expect an intermediate state that is different. If possible
435--- it is better to use an explicit screen:expect(...) for this
436--- intermediate state.
437--- @field intermediate? boolean
438---
439--- Reset the state internal to the test Screen before starting to
440--- receive updates. This should be used after command("redraw!")
441--- or some other mechanism that will invoke "redraw!", to check
442--- that all screen state is transmitted again. This includes
443--- state related to ext_ features as mentioned below.
444--- @field reset? boolean
445---
446--- maximum time that will be waited until the expected state is
447--- seen (or maximum time to observe an incorrect change when
448--- `unchanged` flag is used)
449--- @field timeout? integer
450---
451--- @field mouse_enabled? boolean
452---
453--- @field win_viewport? table<integer,table<string,integer>>
454--- @field win_viewport_margins? table<integer,table<string,integer>>
455--- @field win_pos? table<integer,table<string,integer>>
456--- @field float_pos? [integer,integer]
457--- @field hl_groups? table<string,integer>
458---
459--- The following keys should be used to expect the state of various ext_
460--- features. Note that an absent key will assert that the item is currently
461--- NOT present on the screen, also when positional form is used.
462---
463--- Expected ext_popupmenu state,
464--- @field popupmenu? table
465---
466--- Expected ext_cmdline state, as an array of cmdlines of
467--- different level.
468--- @field cmdline? table
469---
470--- Expected ext_cmdline block (for function definitions)
471--- @field cmdline_block? table
472---
473--- items for ext_wildmenu
474--- @field wildmenu_items? table
475---
476--- position for ext_wildmenu
477--- @field wildmenu_pos? table
478
479--- Asserts that the screen state eventually matches an expected state.
480---
481--- Can be called with positional args:
482---    screen:expect(grid, [attr_ids])
483---    screen:expect(condition)
484--- or keyword args (supports more options):
485---    screen:expect({ grid=[[...]], cmdline={...}, condition=function() ... end })
486---
487--- @param expected string|function|test.functional.ui.screen.Expect
488--- @param attr_ids? table<integer,table<string,any>>
489function Screen:expect(expected, attr_ids, ...)
490  --- @type string, fun()
491  local grid, condition
492
493  assert(next({ ... }) == nil, 'invalid args to expect()')
494
495  if type(expected) == 'table' then
496    assert(attr_ids == nil)
497    for k, _ in
498      pairs(expected --[[@as table<string,any>]])
499    do
500      if not expect_keys[k] then
501        error("Screen:expect: Unknown keyword argument '" .. k .. "'")
502      end
503    end
504    grid = expected.grid
505    attr_ids = expected.attr_ids
506    condition = expected.condition
507    assert((expected.any == nil and expected.none == nil) or grid == nil)
508  elseif type(expected) == 'string' then
509    grid = expected
510    expected = {}
511  elseif type(expected) == 'function' then
512    assert(attr_ids == nil)
513    condition = expected
514    expected = {}
515  else
516    assert(false)
517  end
518
519  local expected_rows = {} --- @type string[]
520  if grid then
521    -- Dedent (ignores last line if it is blank).
522    grid = dedent(grid, 0)
523    for row in grid:gmatch('[^\n]+') do
524      table.insert(expected_rows, row)
525    end
526  end
527
528  local attr_state = {
529    ids = attr_ids or self._default_attr_ids,
530  }
531
532  if isempty(attr_ids) then
533    attr_state.ids = nil
534  end
535
536  if self._options.ext_linegrid then
537    attr_state.id_to_index = self:linegrid_check_attrs(attr_state.ids or {})
538  end
539
540  self._new_attrs = false
541  self:_wait(function()
542    if condition then
543      --- @type boolean, string
544      local status, res = pcall(condition)
545      if not status then
546        return tostring(res)
547      end
548    end
549
550    if self._options.ext_linegrid and self._new_attrs then
551      attr_state.id_to_index = self:linegrid_check_attrs(attr_state.ids or {})
552    end
553
554    local actual_rows
555    if expected.any or expected.none or grid then
556      actual_rows = self:render(not (expected.any or expected.none), attr_state)
557    end
558
559    local any_or_none = function(screen_str, value, is_any)
560      if value then
561        local v = value
562        if type(v) == 'string' then
563          v = { v }
564        end
565        local msg
566        if is_any then
567          msg = 'Expected (anywhere): "'
568        else
569          msg = 'Expected (nowhere): "'
570        end
571        for _, v2 in ipairs(v) do
572          local test = screen_str:find(v2)
573          if is_any then
574            test = not test
575          end
576          -- Search for `any` anywhere in the screen lines.
577          if test then
578            return (
579              'Failed to match any screen lines.\n'
580              .. msg
581              .. v2
582              .. '"\n'
583              .. 'Actual:\n  |'
584              .. table.concat(actual_rows, '\n  |')
585              .. '\n\n'
586            )
587          end
588        end
589      end
590      return nil
591    end
592    if expected.any or expected.none then
593      local actual_screen_str = table.concat(actual_rows, '\n')
594      if expected.any then
595        local res = any_or_none(actual_screen_str, expected.any, true)
596        if res then
597          return res
598        end
599      end
600      if expected.none then
601        local res = any_or_none(actual_screen_str, expected.none, false)
602        if res then
603          return res
604        end
605      end
606    end
607
608    if grid then
609      for i, row in ipairs(expected_rows) do
610        local count --- @type integer?
611        row, count = row:match('^(.*%|)%*(%d+)$')
612        if row then
613          count = tonumber(count)
614          table.remove(expected_rows, i)
615          for _ = 1, count do
616            table.insert(expected_rows, i, row)
617          end
618        end
619      end
620      local err_msg = nil
621      -- `expected` must match the screen lines exactly.
622      if #actual_rows ~= #expected_rows then
623        err_msg = 'Expected screen height '
624          .. #expected_rows
625          .. ' differs from actual height '
626          .. #actual_rows
627          .. '.'
628      end
629      local msg_expected_rows = shallowcopy(expected_rows)
630      local msg_actual_rows = shallowcopy(actual_rows)
631      for i, row in ipairs(expected_rows) do
632        local pat = nil --- @type string?
633        if actual_rows[i] and row ~= actual_rows[i] then
634          local after = row
635          while true do
636            local s, e, m = after:find('{MATCH:(.-)}')
637            if not s then
638              pat = pat and (pat .. pesc(after))
639              break
640            end
641            --- @type string
642            pat = (pat or '') .. pesc(after:sub(1, s - 1)) .. m
643            after = after:sub(e + 1)
644          end
645        end
646        pat = pat and '^' .. pat .. '$'
647        if row ~= actual_rows[i] and (not pat or not actual_rows[i]:match(pat)) then
648          msg_expected_rows[i] = '*' .. msg_expected_rows[i]
649          if i <= #actual_rows then
650            msg_actual_rows[i] = '*' .. msg_actual_rows[i]
651          end
652          if err_msg == nil then
653            err_msg = 'Row ' .. tostring(i) .. ' did not match.'
654          end
655        end
656      end
657      if err_msg ~= nil then
658        return (
659          err_msg
660          .. '\nExpected:\n  |'
661          .. table.concat(msg_expected_rows, '\n  |')
662          .. '\n'
663          .. 'Actual:\n  |'
664          .. table.concat(msg_actual_rows, '\n  |')
665          .. '\n\n'
666          .. [[
667To print the expect() call that would assert the current screen state, use
668screen:snapshot_util(). In case of non-deterministic failures, use
669screen:redraw_debug() to show all intermediate screen states.]]
670        )
671      end
672    end
673
674    -- UI extensions. The default expectations should cover the case of
675    -- the ext_ feature being disabled, or the feature currently not activated
676    -- (e.g. no external cmdline visible). Some extensions require
677    -- preprocessing to represent highlights in a reproducible way.
678    local extstate = self:_extstate_repr(attr_state, expected)
679    if expected.mode ~= nil then
680      extstate.mode = self.mode
681    end
682    if expected.mouse_enabled ~= nil then
683      extstate.mouse_enabled = self.mouse_enabled
684    end
685    if expected.win_viewport == nil then
686      extstate.win_viewport = nil
687    end
688    if expected.win_viewport_margins == nil then
689      extstate.win_viewport_margins = nil
690    end
691    if expected.win_pos == nil then
692      extstate.win_pos = nil
693    end
694    if expected.cmdline == nil then
695      extstate.cmdline = nil
696    end
697
698    if expected.float_pos then
699      expected.float_pos = deepcopy(expected.float_pos)
700      for _, v in pairs(expected.float_pos) do
701        if not v.external and v[7] == nil then
702          v[7] = 50
703        end
704      end
705    end
706
707    -- Convert assertion errors into invalid screen state descriptions.
708    for _, k in ipairs(concat_tables(ext_keys, { 'mode', 'mouse_enabled' })) do
709      -- Empty states are considered the default and need not be mentioned.
710      if not (expected[k] == nil and isempty(extstate[k])) then
711        local status, res = pcall(eq, expected[k], extstate[k], k)
712        if not status then
713          return (
714            tostring(res)
715            .. '\nHint: full state of "'
716            .. k
717            .. '":\n  '
718            .. inspect(extstate[k])
719          )
720        end
721      end
722    end
723
724    if expected.hl_groups ~= nil then
725      for name, id in pairs(expected.hl_groups) do
726        local expected_hl = attr_state.ids[id]
727        local actual_hl = self._attr_table[self.hl_groups[name]][(self._options.rgb and 1) or 2]
728        local status, res = pcall(eq, expected_hl, actual_hl, 'highlight ' .. name)
729        if not status then
730          return tostring(res)
731        end
732      end
733    end
734
735    if expected.extmarks ~= nil then
736      for gridid, expected_marks in pairs(expected.extmarks) do
737        local stored_marks = self._grid_win_extmarks[gridid]
738        if stored_marks == nil then
739          return 'no win_extmark for grid ' .. tostring(gridid)
740        end
741        local status, res =
742          pcall(eq, expected_marks, stored_marks, 'extmarks for grid ' .. tostring(gridid))
743        if not status then
744          return tostring(res)
745        end
746      end
747      for gridid, _ in pairs(self._grid_win_extmarks) do
748        local expected_marks = expected.extmarks[gridid]
749        if expected_marks == nil then
750          return 'unexpected win_extmark for grid ' .. tostring(gridid)
751        end
752      end
753    end
754  end, expected)
755  -- Only test the abort state of a cmdline level once.
756  if self.cmdline_hide_level ~= nil then
757    self.cmdline[self.cmdline_hide_level] = nil
758    self.cmdline_hide_level = nil
759  end
760  self.messages, self.msg_history = {}, {}
761end
762
763function Screen:expect_unchanged(intermediate, waittime_ms)
764  -- Collect the current screen state.
765  local kwargs = self:get_snapshot()
766
767  if intermediate then
768    kwargs.intermediate = true
769  else
770    kwargs.unchanged = true
771  end
772
773  kwargs.timeout = waittime_ms
774  -- Check that screen state does not change.
775  self:expect(kwargs)
776end
777
778--- @private
779--- @param check fun(): string
780--- @param flags table<string,any>
781function Screen:_wait(check, flags)
782  local err --- @type string?
783  local checked = false
784  local success_seen = false
785  local failure_after_success = false
786  local did_flush = true
787  local warn_immediate = not (flags.unchanged or flags.intermediate)
788
789  if flags.intermediate and flags.unchanged then
790    error("Choose only one of 'intermediate' and 'unchanged', not both")
791  end
792
793  if flags.reset then
794    -- throw away all state, we expect it to be retransmitted
795    self:_reset()
796  end
797
798  -- Maximum timeout, after which a incorrect state will be regarded as a
799  -- failure
800  local timeout = flags.timeout or self.timeout
801
802  -- Minimal timeout before the loop is allowed to be stopped so we
803  -- always do some check for failure after success.
804  local minimal_timeout = default_timeout_factor * 2
805
806  local immediate_seen, intermediate_seen = false, false
807  local intermediate_state_snapshot = ''
808  if not check() then
809    minimal_timeout = default_timeout_factor * 20
810    immediate_seen = true
811  end
812
813  -- For an "unchanged" test, flags.timeout is the time during which the state
814  -- must not change, so always wait this full time.
815  if flags.unchanged then
816    minimal_timeout = flags.timeout or default_timeout_factor * 20
817  elseif flags.intermediate then
818    minimal_timeout = default_timeout_factor * 20
819  end
820
821  assert(timeout >= minimal_timeout)
822  local did_minimal_timeout = false
823
824  local function notification_cb(method, args)
825    assert(
826      method == 'redraw',
827      string.format('notification_cb: unexpected method (%s, args=%s)', method, inspect(args))
828    )
829    did_flush = self:_redraw(args)
830    if not did_flush then
831      return
832    end
833    err = check()
834    checked = true
835    if err and immediate_seen then
836      if not intermediate_seen and flags.unchanged then
837        -- Save the first intermediate state for the error message.
838        intermediate_state_snapshot = self:_print_snapshot()
839      end
840      intermediate_seen = true
841    end
842
843    if not err and (not flags.intermediate or intermediate_seen) then
844      success_seen = true
845      if did_minimal_timeout then
846        self._session:stop()
847      end
848    elseif err and success_seen and #args > 0 then
849      success_seen = false
850      failure_after_success = true
851      -- print(inspect(args))
852    end
853
854    return true
855  end
856  local eof = run_session(self._session, flags.request_cb, notification_cb, nil, minimal_timeout)
857  if not did_flush then
858    if eof then
859      err = 'no flush received'
860    end
861  elseif not checked then
862    err = check()
863    if not err and flags.unchanged then
864      -- expecting NO screen change: use a shorter timeout
865      success_seen = true
866    end
867  end
868
869  if not success_seen and not eof then
870    did_minimal_timeout = true
871    eof =
872      run_session(self._session, flags.request_cb, notification_cb, nil, timeout - minimal_timeout)
873    if not did_flush then
874      err = 'no flush received'
875    end
876  end
877
878  local did_warn = false
879  if warn_immediate and immediate_seen then
880    print([[
881
882warning: Screen test succeeded immediately. Try to avoid this unless the
883purpose of the test really requires it.]])
884    if intermediate_seen then
885      print([[
886There are intermediate states between the two identical expects.
887Use screen:snapshot_util() or screen:redraw_debug() to find them, and add them
888to the test if they make sense.
889]])
890    else
891      print([[If necessary, silence this warning with 'unchanged' argument of screen:expect.]])
892    end
893    did_warn = true
894  end
895
896  if failure_after_success then
897    print([[
898
899warning: Screen changes were received after the expected state. This indicates
900indeterminism in the test. Try adding screen:expect(...) (or poke_eventloop())
901between asynchronous (feed(), nvim_input()) and synchronous API calls.
902  - Use screen:redraw_debug() to investigate; it may find relevant intermediate
903    states that should be added to the test to make it more robust.
904  - If the purpose of the test is to assert state after some user input sent
905    with feed(), adding screen:expect() before the feed() will help to ensure
906    the input is sent when Nvim is in a predictable state. This is preferable
907    to poke_eventloop(), for being closer to real user interaction.
908  - poke_eventloop() can trigger redraws and thus generate more indeterminism.
909    Try removing poke_eventloop().
910      ]])
911    did_warn = true
912  end
913
914  if err then
915    if eof then
916      err = err .. '\n\n' .. eof[2]
917    end
918    error(err .. '\n\nSnapshot:\n' .. self:_print_snapshot(), 3)
919  elseif did_warn then
920    if eof then
921      print(eof[2])
922    end
923    local tb = debug.traceback()
924    local index = string.find(tb, '\n%s*%[C]')
925    print(string.sub(tb, 1, index))
926  end
927
928  if flags.intermediate and not intermediate_seen then
929    error('Expected intermediate screen state before final screen state', 3)
930  elseif flags.unchanged and intermediate_seen then
931    error(
932      'Expected screen state to be unchanged.\nIntermediate screen state:\n'
933        .. intermediate_state_snapshot,
934      3
935    )
936  end
937end
938
939function Screen:sleep(ms, request_cb)
940  local function notification_cb(method, args)
941    assert(method == 'redraw')
942    self:_redraw(args)
943  end
944  run_session(self._session, request_cb, notification_cb, nil, ms)
945end
946
947--- @private
948--- @param updates {[1]:string, [integer]:any[]}[]
949function Screen:_redraw(updates)
950  local did_flush = false
951  for k, update in ipairs(updates) do
952    -- print('--', inspect(update))
953    local method = update[1]
954    for i = 2, #update do
955      local handler_name = '_handle_' .. method
956      --- @type function
957      local handler = self[handler_name]
958      assert(handler ~= nil, 'missing handler: Screen:' .. handler_name)
959      local status, res = pcall(handler, self, unpack(update[i]))
960      if not status then
961        error(
962          handler_name
963            .. ' failed'
964            .. '\n  payload: '
965            .. inspect(update)
966            .. '\n  error:   '
967            .. tostring(res)
968        )
969      end
970    end
971    if k == #updates and method == 'flush' then
972      did_flush = true
973    end
974  end
975  return did_flush
976end
977
978function Screen:_handle_resize(width, height)
979  self:_handle_grid_resize(1, width, height)
980  self._scroll_region = {
981    top = 1,
982    bot = height,
983    left = 1,
984    right = width,
985  }
986  self._grid = self._grids[1]
987end
988
989local function min(x, y)
990  if x < y then
991    return x
992  else
993    return y
994  end
995end
996
997function Screen:_handle_grid_resize(grid, width, height)
998  local rows = {}
999  for _ = 1, height do
1000    local cols = {}
1001    for _ = 1, width do
1002      table.insert(cols, { text = ' ', attrs = self._clear_attrs, hl_id = 0 })
1003    end
1004    table.insert(rows, cols)
1005  end
1006  if grid > 1 and self._grids[grid] ~= nil then
1007    local old = self._grids[grid]
1008    for i = 1, min(height, old.height) do
1009      for j = 1, min(width, old.width) do
1010        rows[i][j] = old.rows[i][j]
1011      end
1012    end
1013  end
1014
1015  if self._cursor.grid == grid then
1016    self._cursor.row = 1 -- -1 ?
1017    self._cursor.col = 1
1018  end
1019  self._grids[grid] = {
1020    rows = rows,
1021    width = width,
1022    height = height,
1023  }
1024end
1025
1026function Screen:_handle_msg_set_pos(grid, row, scrolled, char, zindex, compindex)
1027  self.msg_grid = grid
1028  self.msg_grid_pos = row
1029  self.msg_scrolled = scrolled
1030  self.msg_sep_char = char
1031  self.msg_zindex = zindex
1032  self.msg_compindex = compindex
1033end
1034
1035function Screen:_handle_flush() end
1036
1037function Screen:_reset()
1038  -- TODO: generalize to multigrid later
1039  self:_handle_grid_clear(1)
1040
1041  -- TODO: share with initialization, so it generalizes?
1042  self.popupmenu = nil
1043  self.cmdline = {}
1044  self.cmdline_block = {}
1045  self.wildmenu_items = nil
1046  self.wildmenu_pos = nil
1047  self._grid_win_extmarks = {}
1048  self.msg_grid = nil
1049  self.msg_grid_pos = nil
1050  self.msg_scrolled = false
1051  self.msg_sep_char = nil
1052end
1053
1054--- @param cursor_style_enabled boolean
1055--- @param mode_info table[]
1056function Screen:_handle_mode_info_set(cursor_style_enabled, mode_info)
1057  self._cursor_style_enabled = cursor_style_enabled
1058  for _, item in pairs(mode_info) do
1059    -- attr IDs are not stable, but their value should be
1060    if item.attr_id ~= nil and self._attr_table[item.attr_id] ~= nil then
1061      item.attr = self._attr_table[item.attr_id][1]
1062      item.attr_id = nil
1063    end
1064    if item.attr_id_lm ~= nil and self._attr_table[item.attr_id_lm] ~= nil then
1065      item.attr_lm = self._attr_table[item.attr_id_lm][1]
1066      item.attr_id_lm = nil
1067    end
1068  end
1069  self._mode_info = mode_info
1070end
1071
1072function Screen:_handle_clear()
1073  -- the first implemented UI protocol clients (python-gui and builitin TUI)
1074  -- allowed the cleared region to be restricted by setting the scroll region.
1075  -- this was never used by nvim tough, and not documented and implemented by
1076  -- newer clients, to check we remain compatible with both kind of clients,
1077  -- ensure the scroll region is in a reset state.
1078  local expected_region = {
1079    top = 1,
1080    bot = self._grid.height,
1081    left = 1,
1082    right = self._grid.width,
1083  }
1084  eq(expected_region, self._scroll_region)
1085  self:_handle_grid_clear(1)
1086end
1087
1088function Screen:_handle_grid_clear(grid)
1089  self:_clear_block(self._grids[grid], 1, self._grids[grid].height, 1, self._grids[grid].width)
1090end
1091
1092function Screen:_handle_grid_destroy(grid)
1093  self._grids[grid] = nil
1094  if self._options.ext_multigrid then
1095    self.win_position[grid] = nil
1096    self.win_viewport[grid] = nil
1097    self.win_viewport_margins[grid] = nil
1098  end
1099end
1100
1101function Screen:_handle_eol_clear()
1102  local row, col = self._cursor.row, self._cursor.col
1103  self:_clear_block(self._grid, row, row, col, self._grid.width)
1104end
1105
1106function Screen:_handle_cursor_goto(row, col)
1107  self._cursor.row = row + 1
1108  self._cursor.col = col + 1
1109end
1110
1111function Screen:_handle_grid_cursor_goto(grid, row, col)
1112  self._cursor.grid = grid
1113  assert(row >= 0 and col >= 0)
1114  self._cursor.row = row + 1
1115  self._cursor.col = col + 1
1116end
1117
1118function Screen:_handle_win_pos(grid, win, startrow, startcol, width, height)
1119  self.win_position[grid] = {
1120    win = win,
1121    startrow = startrow,
1122    startcol = startcol,
1123    width = width,
1124    height = height,
1125  }
1126  self.float_pos[grid] = nil
1127end
1128
1129function Screen:_handle_win_viewport(
1130  grid,
1131  win,
1132  topline,
1133  botline,
1134  curline,
1135  curcol,
1136  linecount,
1137  scroll_delta
1138)
1139  -- accumulate scroll delta
1140  local last_scroll_delta = self.win_viewport[grid] and self.win_viewport[grid].sum_scroll_delta
1141    or 0
1142  self.win_viewport[grid] = {
1143    win = win,
1144    topline = topline,
1145    botline = botline,
1146    curline = curline,
1147    curcol = curcol,
1148    linecount = linecount,
1149    sum_scroll_delta = scroll_delta + last_scroll_delta,
1150  }
1151end
1152
1153function Screen:_handle_win_viewport_margins(grid, win, top, bottom, left, right)
1154  self.win_viewport_margins[grid] = {
1155    win = win,
1156    top = top,
1157    bottom = bottom,
1158    left = left,
1159    right = right,
1160  }
1161end
1162
1163function Screen:_handle_win_float_pos(grid, ...)
1164  self.win_position[grid] = nil
1165  self.float_pos[grid] = { ... }
1166end
1167
1168function Screen:_handle_win_external_pos(grid)
1169  self.win_position[grid] = nil
1170  self.float_pos[grid] = { external = true }
1171end
1172
1173function Screen:_handle_win_hide(grid)
1174  self.win_position[grid] = nil
1175  self.float_pos[grid] = nil
1176end
1177
1178function Screen:_handle_win_close(grid)
1179  self.float_pos[grid] = nil
1180end
1181
1182function Screen:_handle_win_extmark(grid, ...)
1183  if self._grid_win_extmarks[grid] == nil then
1184    self._grid_win_extmarks[grid] = {}
1185  end
1186  table.insert(self._grid_win_extmarks[grid], { ... })
1187end
1188
1189function Screen:_handle_busy_start()
1190  self._busy = true
1191end
1192
1193function Screen:_handle_busy_stop()
1194  self._busy = false
1195end
1196
1197function Screen:_handle_mouse_on()
1198  self.mouse_enabled = true
1199end
1200
1201function Screen:_handle_mouse_off()
1202  self.mouse_enabled = false
1203end
1204
1205function Screen:_handle_mode_change(mode, idx)
1206  assert(mode == self._mode_info[idx + 1].name)
1207  self.mode = mode
1208end
1209
1210function Screen:_handle_set_scroll_region(top, bot, left, right)
1211  self._scroll_region.top = top + 1
1212  self._scroll_region.bot = bot + 1
1213  self._scroll_region.left = left + 1
1214  self._scroll_region.right = right + 1
1215end
1216
1217function Screen:_handle_scroll(count)
1218  local top = self._scroll_region.top
1219  local bot = self._scroll_region.bot
1220  local left = self._scroll_region.left
1221  local right = self._scroll_region.right
1222  self:_handle_grid_scroll(1, top - 1, bot, left - 1, right, count, 0)
1223end
1224
1225--- @param g any
1226--- @param top integer
1227--- @param bot integer
1228--- @param left integer
1229--- @param right integer
1230--- @param rows integer
1231--- @param cols integer
1232function Screen:_handle_grid_scroll(g, top, bot, left, right, rows, cols)
1233  top = top + 1
1234  left = left + 1
1235  assert(cols == 0)
1236  local grid = self._grids[g]
1237  --- @type integer, integer, integer
1238  local start, stop, step
1239
1240  if rows > 0 then
1241    start = top
1242    stop = bot - rows
1243    step = 1
1244  else
1245    start = bot
1246    stop = top - rows
1247    step = -1
1248  end
1249
1250  -- shift scroll region
1251  for i = start, stop, step do
1252    local target = grid.rows[i]
1253    local source = grid.rows[i + rows]
1254    for j = left, right do
1255      target[j].text = source[j].text
1256      target[j].attrs = source[j].attrs
1257      target[j].hl_id = source[j].hl_id
1258    end
1259  end
1260
1261  -- clear invalid rows
1262  for i = stop + step, stop + rows, step do
1263    self:_clear_row_section(grid, i, left, right, true)
1264  end
1265end
1266
1267function Screen:_handle_hl_attr_define(id, rgb_attrs, cterm_attrs, info)
1268  self._attr_table[id] = { rgb_attrs, cterm_attrs }
1269  self._hl_info[id] = info
1270  self._new_attrs = true
1271end
1272
1273--- @param name string
1274--- @param id integer
1275function Screen:_handle_hl_group_set(name, id)
1276  self.hl_groups[name] = id
1277end
1278
1279function Screen:get_hl(val)
1280  if self._options.ext_newgrid then
1281    return self._attr_table[val][1]
1282  end
1283  return val
1284end
1285
1286function Screen:_handle_highlight_set(attrs)
1287  self._attrs = attrs
1288end
1289
1290function Screen:_handle_put(str)
1291  assert(not self._options.ext_linegrid)
1292  local cell = self._grid.rows[self._cursor.row][self._cursor.col]
1293  cell.text = str
1294  cell.attrs = self._attrs
1295  cell.hl_id = -1
1296  self._cursor.col = self._cursor.col + 1
1297end
1298
1299--- @param grid integer
1300--- @param row integer
1301--- @param col integer
1302--- @param items integer[][]
1303function Screen:_handle_grid_line(grid, row, col, items, wrap)
1304  assert(self._options.ext_linegrid)
1305  assert(#items > 0)
1306  local line = self._grids[grid].rows[row + 1]
1307  local colpos = col + 1
1308  local hl_id = 0
1309  line.wrap = wrap
1310  for _, item in ipairs(items) do
1311    local text, hl_id_cell, count = item[1], item[2], item[3]
1312    if hl_id_cell ~= nil then
1313      hl_id = hl_id_cell
1314    end
1315    for _ = 1, (count or 1) do
1316      local cell = line[colpos]
1317      cell.text = text
1318      cell.hl_id = hl_id
1319      colpos = colpos + 1
1320    end
1321  end
1322end
1323
1324function Screen:_handle_bell()
1325  self.bell = true
1326end
1327
1328function Screen:_handle_visual_bell()
1329  self.visual_bell = true
1330end
1331
1332function Screen:_handle_default_colors_set(rgb_fg, rgb_bg, rgb_sp, cterm_fg, cterm_bg)
1333  self.default_colors = {
1334    rgb_fg = rgb_fg,
1335    rgb_bg = rgb_bg,
1336    rgb_sp = rgb_sp,
1337    cterm_fg = cterm_fg,
1338    cterm_bg = cterm_bg,
1339  }
1340end
1341
1342function Screen:_handle_update_fg(fg)
1343  self._fg = fg
1344end
1345
1346function Screen:_handle_update_bg(bg)
1347  self._bg = bg
1348end
1349
1350function Screen:_handle_update_sp(sp)
1351  self._sp = sp
1352end
1353
1354function Screen:_handle_suspend()
1355  self.suspended = true
1356end
1357
1358function Screen:_handle_update_menu()
1359  self.update_menu = true
1360end
1361
1362function Screen:_handle_set_title(title)
1363  self.title = title
1364end
1365
1366function Screen:_handle_set_icon(icon)
1367  self.icon = icon
1368end
1369
1370function Screen:_handle_option_set(name, value)
1371  self.options[name] = value
1372end
1373
1374function Screen:_handle_chdir(path)
1375  self.pwd = vim.fs.normalize(path, { plain = true })
1376end
1377
1378function Screen:_handle_popupmenu_show(items, selected, row, col, grid)
1379  self.popupmenu = { items = items, pos = selected, anchor = { grid, row, col } }
1380end
1381
1382function Screen:_handle_popupmenu_select(selected)
1383  self.popupmenu.pos = selected
1384end
1385
1386function Screen:_handle_popupmenu_hide()
1387  self.popupmenu = nil
1388end
1389
1390function Screen:_handle_cmdline_show(content, pos, firstc, prompt, indent, level, hl_id)
1391  if firstc == '' then
1392    firstc = nil
1393  end
1394  if hl_id == -1 then
1395    prompt = nil
1396  end
1397  if indent == 0 then
1398    indent = nil
1399  end
1400
1401  -- check position is valid #10000
1402  local len = 0
1403  for _, chunk in ipairs(content) do
1404    len = len + string.len(chunk[2])
1405  end
1406  assert(pos <= len)
1407
1408  self.cmdline[level] = {
1409    content = content,
1410    pos = pos,
1411    firstc = firstc,
1412    prompt = prompt,
1413    indent = indent,
1414    hl = hl_id,
1415  }
1416end
1417
1418function Screen:_handle_cmdline_hide(level, abort)
1419  self.cmdline[level] = abort and { abort = abort } or nil
1420  self.cmdline_hide_level = level
1421end
1422
1423function Screen:_handle_cmdline_special_char(char, shift, level)
1424  -- cleared by next cmdline_show on the same level
1425  self.cmdline[level].special = { char, shift }
1426end
1427
1428function Screen:_handle_cmdline_pos(pos, level)
1429  self.cmdline[level].pos = pos
1430end
1431
1432function Screen:_handle_cmdline_block_show(block)
1433  self.cmdline_block = block
1434end
1435
1436function Screen:_handle_cmdline_block_append(item)
1437  self.cmdline_block[#self.cmdline_block + 1] = item
1438end
1439
1440function Screen:_handle_cmdline_block_hide()
1441  self.cmdline_block = {}
1442end
1443
1444function Screen:_handle_wildmenu_show(items)
1445  self.wildmenu_items = items
1446end
1447
1448function Screen:_handle_wildmenu_select(pos)
1449  self.wildmenu_pos = pos
1450end
1451
1452function Screen:_handle_wildmenu_hide()
1453  self.wildmenu_items, self.wildmenu_pos = nil, nil
1454end
1455
1456function Screen:_handle_msg_show(kind, chunks, replace_last, history, append, id, trigger)
1457  local pos = #self.messages
1458  if not replace_last or pos == 0 then
1459    pos = pos + 1
1460  end
1461  for i, msg in pairs(self.messages) do
1462    if id ~= -1 and msg.id == id then
1463      pos = i
1464      break
1465    end
1466  end
1467  self.messages[pos] = {
1468    kind = kind,
1469    content = chunks,
1470    history = history,
1471    append = append,
1472    id = id,
1473    trigger = trigger,
1474  }
1475end
1476
1477function Screen:_handle_msg_clear()
1478  self.messages = {}
1479end
1480
1481function Screen:_handle_msg_showcmd(msg)
1482  self.showcmd = msg
1483end
1484
1485function Screen:_handle_msg_showmode(msg)
1486  self.showmode = msg
1487end
1488
1489function Screen:_handle_msg_ruler(msg)
1490  self.ruler = msg
1491end
1492
1493function Screen:_handle_msg_history_show(entries, prev_cmd)
1494  self.msg_history = { entries, prev_cmd }
1495end
1496
1497function Screen:_handle_ui_send(content)
1498  if self._stdout then
1499    self._stdout:write(content)
1500  end
1501end
1502
1503function Screen:_clear_block(grid, top, bot, left, right)
1504  for i = top, bot do
1505    self:_clear_row_section(grid, i, left, right)
1506  end
1507end
1508
1509function Screen:_clear_row_section(grid, rownum, startcol, stopcol, invalid)
1510  local row = grid.rows[rownum]
1511  for i = startcol, stopcol do
1512    row[i].text = (invalid and '�' or ' ')
1513    row[i].attrs = self._clear_attrs
1514    row[i].hl_id = 0
1515  end
1516end
1517
1518function Screen:_row_repr(gridnr, rownr, attr_state, cursor)
1519  local rv = {}
1520  local current_attr_id
1521  local i = 1
1522  local has_windows = self._options.ext_multigrid and gridnr == 1
1523  local row = self._grids[gridnr].rows[rownr]
1524  if has_windows and self.msg_grid and self.msg_grid_pos < rownr then
1525    return '[' .. self.msg_grid .. ':' .. string.rep('-', #row) .. ']'
1526  end
1527  while i <= #row do
1528    local did_window = false
1529    if has_windows then
1530      for id, pos in pairs(self.win_position) do
1531        if
1532          i - 1 == pos.startcol
1533          and pos.startrow <= rownr - 1
1534          and rownr - 1 < pos.startrow + pos.height
1535        then
1536          if current_attr_id then
1537            -- close current attribute bracket
1538            table.insert(rv, '}')
1539            current_attr_id = nil
1540          end
1541          table.insert(rv, '[' .. id .. ':' .. string.rep('-', pos.width) .. ']')
1542          i = i + pos.width
1543          did_window = true
1544        end
1545      end
1546    end
1547
1548    if not did_window then
1549      local attr_id = self:_get_attr_id(attr_state, row[i].attrs, row[i].hl_id)
1550      if current_attr_id and attr_id ~= current_attr_id then
1551        -- close current attribute bracket
1552        table.insert(rv, '}')
1553        current_attr_id = nil
1554      end
1555      if not current_attr_id and attr_id then
1556        -- open a new attribute bracket
1557        table.insert(rv, '{' .. attr_id .. ':')
1558        current_attr_id = attr_id
1559      end
1560      if not self._busy and cursor and self._cursor.col == i then
1561        table.insert(rv, '^')
1562      end
1563      table.insert(rv, row[i].text)
1564      i = i + 1
1565    end
1566  end
1567  if current_attr_id then
1568    table.insert(rv, '}')
1569  end
1570  -- return the line representation, but remove empty attribute brackets and
1571  -- trailing whitespace
1572  return table.concat(rv, '') --:gsub('%s+$', '')
1573end
1574
1575local function hl_id_to_name(self, id)
1576  if id and id > 0 and not self.hl_names[id] then
1577    self.hl_names[id] = n.fn.synIDattr(id, 'name')
1578  end
1579  return id and self.hl_names[id] or nil
1580end
1581
1582function Screen:_extstate_repr(attr_state, exp)
1583  local cmdline = {}
1584  for i, entry in pairs(self.cmdline) do
1585    entry = shallowcopy(entry)
1586    if entry.content ~= nil then
1587      entry.content = self:_chunks_repr(entry.content, attr_state)
1588    end
1589    entry.hl = hl_id_to_name(self, entry.hl)
1590    cmdline[i] = entry
1591  end
1592
1593  local cmdline_block = {}
1594  for i, entry in ipairs(self.cmdline_block) do
1595    cmdline_block[i] = self:_chunks_repr(entry, attr_state)
1596  end
1597
1598  local messages = {}
1599  for i, entry in ipairs(self.messages) do
1600    local exp_msg = exp and exp.messages and exp.messages[i]
1601    -- Late addition, only include when expected state includes it.
1602    local trigger = nil
1603    if exp_msg and exp_msg.trigger ~= nil then
1604      trigger = entry.trigger
1605    end
1606    -- Progress messages are identified by their id, so always show it for them.
1607    local id = nil
1608    if entry.kind == 'progress' or (exp_msg and exp_msg.id ~= nil) then
1609      id = entry.id
1610    end
1611    messages[i] = {
1612      kind = entry.kind,
1613      content = self:_chunks_repr(entry.content, attr_state),
1614      history = entry.history or nil,
1615      append = entry.append or nil,
1616      id = id,
1617      trigger = trigger,
1618    }
1619  end
1620
1621  local msg_history = { prev_cmd = self.msg_history[2] or nil }
1622  for i, entry in ipairs(self.msg_history[1] or {}) do
1623    msg_history[i] = {
1624      kind = entry[1],
1625      content = self:_chunks_repr(entry[2], attr_state),
1626      append = entry[3] or nil,
1627    }
1628  end
1629
1630  local win_viewport = (next(self.win_viewport) and self.win_viewport) or nil
1631  local win_viewport_margins = (next(self.win_viewport_margins) and self.win_viewport_margins)
1632    or nil
1633
1634  return {
1635    popupmenu = self.popupmenu,
1636    cmdline = cmdline,
1637    cmdline_block = cmdline_block,
1638    wildmenu_items = self.wildmenu_items,
1639    wildmenu_pos = self.wildmenu_pos,
1640    messages = messages,
1641    showmode = self:_chunks_repr(self.showmode, attr_state),
1642    showcmd = self:_chunks_repr(self.showcmd, attr_state),
1643    ruler = self:_chunks_repr(self.ruler, attr_state),
1644    msg_history = msg_history,
1645    float_pos = self.float_pos,
1646    win_viewport = win_viewport,
1647    win_viewport_margins = win_viewport_margins,
1648    win_pos = self.win_position,
1649  }
1650end
1651
1652function Screen:_chunks_repr(chunks, attr_state)
1653  local repr_chunks = {}
1654  for i, chunk in ipairs(chunks) do
1655    local hl, text, id = unpack(chunk)
1656    local attrs
1657    if self._options.ext_linegrid then
1658      attrs = (self._attr_table[hl] or {})[1] -- Tolerate undefined hl_id in a snapshot render.
1659    else
1660      attrs = hl
1661    end
1662    local attr_id = self:_get_attr_id(attr_state, attrs, hl)
1663    repr_chunks[i] = { text, attr_id }
1664    repr_chunks[i][#repr_chunks[i] + 1] = hl_id_to_name(self, id)
1665  end
1666  return repr_chunks
1667end
1668
1669-- Generates tests. Call it where Screen:expect() would be. Waits briefly, then
1670-- dumps the current screen state in the form of Screen:expect().
1671-- Use snapshot_util({}) to generate a text-only (no attributes) test.
1672--
1673-- @see Screen:redraw_debug()
1674function Screen:snapshot_util(request_cb)
1675  -- TODO: simplify this later when existing tests have been updated
1676  self:sleep(250, request_cb)
1677  self:print_snapshot()
1678end
1679
1680function Screen:redraw_debug(timeout)
1681  self:print_snapshot()
1682  local function notification_cb(method, args)
1683    assert(method == 'redraw')
1684    for _, update in ipairs(args) do
1685      -- mode_info_set is quite verbose, comment out the condition to debug it.
1686      if update[1] ~= 'mode_info_set' then
1687        print(inspect(update))
1688      end
1689    end
1690    self:_redraw(args)
1691    self:print_snapshot()
1692    return true
1693  end
1694  if timeout == nil then
1695    timeout = 250
1696  end
1697  run_session(self._session, nil, notification_cb, nil, timeout)
1698end
1699
1700--- @param headers boolean
1701--- @param attr_state any
1702--- @param preview? boolean
1703--- @return string[]
1704function Screen:render(headers, attr_state, preview)
1705  headers = headers and (self._options.ext_multigrid or self._options._debug_float)
1706  local rv = {}
1707  for igrid, grid in vim.spairs(self._grids) do
1708    if headers then
1709      local suffix = ''
1710      if
1711        igrid > 1
1712        and self.win_position[igrid] == nil
1713        and self.float_pos[igrid] == nil
1714        and self.msg_grid ~= igrid
1715      then
1716        suffix = ' (hidden)'
1717      end
1718      table.insert(rv, '## grid ' .. igrid .. suffix)
1719    end
1720    local height = grid.height
1721    if igrid == self.msg_grid then
1722      height = self._grids[1].height - self.msg_grid_pos
1723    end
1724    for i = 1, height do
1725      local cursor = self._cursor.grid == igrid and self._cursor.row == i
1726      local prefix = (headers or preview) and '  ' or ''
1727      table.insert(rv, prefix .. self:_row_repr(igrid, i, attr_state, cursor) .. '|')
1728    end
1729  end
1730  return rv
1731end
1732
1733-- Returns the current screen state in the form of a screen:expect()
1734-- keyword-args map.
1735function Screen:get_snapshot()
1736  local attr_state = {
1737    ids = {},
1738    mutable = true, -- allow _row_repr to add missing highlights
1739  }
1740  local attrs = self._default_attr_ids
1741
1742  if attrs ~= nil then
1743    for i, a in pairs(attrs) do
1744      attr_state.ids[i] = a
1745    end
1746  end
1747  if self._options.ext_linegrid then
1748    attr_state.id_to_index = self:linegrid_check_attrs(attr_state.ids or {})
1749  end
1750
1751  local lines = self:render(true, attr_state, true)
1752
1753  for i, row in ipairs(lines) do
1754    local count = 1
1755    while i < #lines and lines[i + 1] == row do
1756      count = count + 1
1757      table.remove(lines, i + 1)
1758    end
1759    if count > 1 then
1760      lines[i] = lines[i] .. '*' .. count
1761    end
1762  end
1763
1764  local ext_state = self:_extstate_repr(attr_state)
1765  for k, v in pairs(ext_state) do
1766    if isempty(v) then
1767      ext_state[k] = nil -- deleting keys while iterating is ok
1768    end
1769  end
1770
1771  -- Build keyword-args for screen:expect().
1772  local kwargs = {}
1773  if attr_state.modified then
1774    kwargs['attr_ids'] = {}
1775    for i, a in pairs(attr_state.ids) do
1776      kwargs['attr_ids'][i] = a
1777    end
1778  end
1779  kwargs['grid'] = table.concat(lines, '\n')
1780  for _, k in ipairs(ext_keys) do
1781    if ext_state[k] ~= nil then
1782      kwargs[k] = ext_state[k]
1783    end
1784  end
1785
1786  return kwargs, ext_state, attr_state
1787end
1788
1789local function fmt_ext_state(name, state)
1790  local function remove_all_metatables(item, path)
1791    if path[#path] ~= inspect.METATABLE then
1792      return item
1793    end
1794  end
1795  if name == 'win_viewport' then
1796    local str = '{\n'
1797    for k, v in pairs(state) do
1798      str = (
1799        str
1800        .. '  ['
1801        .. k
1802        .. '] = {win = '
1803        .. v.win
1804        .. ', topline = '
1805        .. v.topline
1806        .. ', botline = '
1807        .. v.botline
1808        .. ', curline = '
1809        .. v.curline
1810        .. ', curcol = '
1811        .. v.curcol
1812        .. ', linecount = '
1813        .. v.linecount
1814        .. ', sum_scroll_delta = '
1815        .. v.sum_scroll_delta
1816        .. '};\n'
1817      )
1818    end
1819    return str .. '}'
1820  elseif name == 'float_pos' then
1821    local str = '{\n'
1822    for k, v in pairs(state) do
1823      str = str .. '  [' .. k .. '] = {'
1824      if v.external then
1825        str = str .. ' external = true '
1826      else
1827        str = str .. v[1]
1828        for i = 2, #v do
1829          str = str .. ', ' .. inspect(v[i])
1830        end
1831      end
1832      str = str .. '};\n'
1833    end
1834    return str .. '}'
1835  else
1836    -- TODO(bfredl): improve formatting of more states
1837    return inspect(state, { process = remove_all_metatables })
1838  end
1839end
1840
1841function Screen:_print_snapshot()
1842  local kwargs, ext_state, attr_state = self:get_snapshot()
1843  local attrstr = ''
1844  local modify_attrs = not self._attrs_overridden
1845  if attr_state.modified then
1846    local attrstrs = {}
1847    for i, a in pairs(attr_state.ids) do
1848      local dict
1849      if self._options.ext_linegrid then
1850        dict = self:_pprint_hlitem(a)
1851      else
1852        dict = '{ ' .. self:_pprint_attrs(a) .. ' }'
1853      end
1854      local keyval = (type(i) == 'number') and '[' .. tostring(i) .. ']' or i
1855      if not (type(i) == 'number' and modify_attrs and i <= 31) then
1856        table.insert(attrstrs, '  ' .. keyval .. ' = ' .. dict .. ',')
1857      end
1858      if modify_attrs then
1859        self._default_attr_ids = attr_state.ids
1860      end
1861    end
1862    local fn_name = modify_attrs and 'add_extra_attr_ids' or 'set_default_attr_ids'
1863    attrstr = ('screen:' .. fn_name .. '({\n' .. table.concat(attrstrs, '\n') .. '\n})\n\n')
1864  end
1865
1866  local extstr = ''
1867  for _, k in ipairs(ext_keys) do
1868    if ext_state[k] ~= nil and not (k == 'win_viewport' and not self.options.ext_multigrid) then
1869      extstr = extstr .. '\n  ' .. k .. ' = ' .. fmt_ext_state(k, ext_state[k]) .. ','
1870    end
1871  end
1872
1873  return ('%sscreen:expect(%s%s%s%s%s'):format(
1874    attrstr,
1875    #extstr > 0 and '{\n  grid = [[\n  ' or '[[\n',
1876    #extstr > 0 and kwargs.grid:gsub('\n', '\n  ') or kwargs.grid,
1877    #extstr > 0 and '\n  ]],' or '\n]]',
1878    extstr,
1879    #extstr > 0 and '\n})' or ')'
1880  )
1881end
1882
1883function Screen:print_snapshot()
1884  print('\n' .. self:_print_snapshot() .. '\n')
1885  io.stdout:flush()
1886end
1887
1888function Screen:_insert_hl_id(attr_state, hl_id)
1889  if attr_state.id_to_index[hl_id] ~= nil then
1890    return attr_state.id_to_index[hl_id]
1891  end
1892  local raw_info = self._hl_info[hl_id]
1893  local info = nil
1894  if self._options.ext_hlstate then
1895    info = {}
1896    if #raw_info > 1 then
1897      for i, item in ipairs(raw_info) do
1898        info[i] = self:_insert_hl_id(attr_state, item.id)
1899      end
1900    else
1901      info[1] = {}
1902      for k, v in pairs(raw_info[1]) do
1903        if k ~= 'id' then
1904          info[1][k] = v
1905        end
1906      end
1907    end
1908  end
1909
1910  local entry = self._attr_table[hl_id]
1911  local attrval
1912  if self._rgb_cterm then
1913    attrval = { entry[1], entry[2], info } -- unpack() doesn't work
1914  elseif self._options.ext_hlstate then
1915    attrval = { entry[1], info }
1916  else
1917    attrval = self._options.rgb and entry[1] or entry[2]
1918  end
1919
1920  table.insert(attr_state.ids, attrval)
1921  attr_state.id_to_index[hl_id] = #attr_state.ids
1922  return #attr_state.ids
1923end
1924
1925function Screen:linegrid_check_attrs(attrs)
1926  local id_to_index = {}
1927  for i, def_attr in pairs(self._attr_table) do
1928    local iinfo = self._hl_info[i]
1929    local matchinfo = {}
1930    if #iinfo > 1 then
1931      for k, item in ipairs(iinfo) do
1932        matchinfo[k] = id_to_index[item.id]
1933      end
1934    else
1935      matchinfo = iinfo
1936    end
1937    for k, v in pairs(attrs) do
1938      local attr, info, attr_rgb, attr_cterm
1939      if self._rgb_cterm then
1940        attr_rgb, attr_cterm, info = unpack(v)
1941        attr = { attr_rgb, attr_cterm }
1942        info = info or {}
1943      elseif self._options.ext_hlstate then
1944        attr, info = unpack(v)
1945      else
1946        attr = v
1947        info = {}
1948      end
1949      if self:_equal_attr_def(attr, def_attr) then
1950        if #info == #matchinfo then
1951          local match = false
1952          if #info == 1 then
1953            if self:_equal_info(info[1], matchinfo[1]) then
1954              match = true
1955            end
1956          else
1957            match = true
1958            for j = 1, #info do
1959              if info[j] ~= matchinfo[j] then
1960                match = false
1961              end
1962            end
1963          end
1964          if match then
1965            id_to_index[i] = k
1966          end
1967        end
1968      end
1969    end
1970    if
1971      self:_equal_attr_def(self._rgb_cterm and { {}, {} } or {}, def_attr)
1972      and #self._hl_info[i] == 0
1973    then
1974      id_to_index[i] = ''
1975    end
1976  end
1977  return id_to_index
1978end
1979
1980function Screen:_pprint_hlitem(item)
1981  -- print(inspect(item))
1982  local multi = self._rgb_cterm or self._options.ext_hlstate
1983  local cterm = (not self._rgb_cterm and not self._options.rgb)
1984  local attrdict = '{ ' .. self:_pprint_attrs(multi and item[1] or item, cterm) .. ' }'
1985  local attrdict2, hlinfo
1986  local descdict = ''
1987  if self._rgb_cterm then
1988    attrdict2 = ', { ' .. self:_pprint_attrs(item[2], true) .. ' }'
1989    hlinfo = item[3]
1990  else
1991    attrdict2 = ''
1992    hlinfo = item[2]
1993  end
1994  if self._options.ext_hlstate then
1995    descdict = ', { ' .. self:_pprint_hlinfo(hlinfo) .. ' }'
1996  end
1997  return (multi and '{ ' or '') .. attrdict .. attrdict2 .. descdict .. (multi and ' }' or '')
1998end
1999
2000function Screen:_pprint_hlinfo(states)
2001  if #states == 1 then
2002    local items = {}
2003    for f, v in pairs(states[1]) do
2004      local desc = tostring(v)
2005      if type(v) == type('') then
2006        desc = '"' .. desc .. '"'
2007      end
2008      table.insert(items, f .. ' = ' .. desc)
2009    end
2010    return '{' .. table.concat(items, ', ') .. '}'
2011  else
2012    return table.concat(states, ', ')
2013  end
2014end
2015
2016function Screen:_pprint_attrs(attrs, cterm)
2017  local items = {}
2018  for f, v in pairs(attrs) do
2019    local desc = tostring(v)
2020    if f == 'foreground' or f == 'background' or f == 'special' then
2021      if Screen.colornames[v] ~= nil then
2022        desc = 'Screen.colors.' .. Screen.colornames[v]
2023      elseif cterm then
2024        desc = tostring(v)
2025      else
2026        desc = string.format("tonumber('0x%06x')", v)
2027      end
2028    end
2029    table.insert(items, f .. ' = ' .. desc)
2030  end
2031  return table.concat(items, ', ')
2032end
2033
2034---@diagnostic disable-next-line: unused-local, unused-function
2035local function backward_find_meaningful(tbl, from) -- luacheck: no unused
2036  for i = from or #tbl, 1, -1 do
2037    if tbl[i] ~= ' ' then
2038      return i + 1
2039    end
2040  end
2041  return from
2042end
2043
2044function Screen:_get_attr_id(attr_state, attrs, hl_id)
2045  if not attr_state.ids then
2046    return
2047  end
2048
2049  if self._options.ext_linegrid then
2050    local id = attr_state.id_to_index[hl_id]
2051    if id == '' then -- sentinel for empty it
2052      return nil
2053    elseif id ~= nil then
2054      return id
2055    end
2056    if self._attr_table[hl_id] == nil then
2057      -- Grid references a hl_id that was never defined via "hl_attr_define".
2058      -- TODO(justinmk): maybe an Nvim core bug. https://github.com/neovim/neovim/issues/36250
2059      return ('UNKNOWN_HL_ID(%d)'):format(hl_id)
2060    end
2061    if attr_state.mutable then
2062      id = self:_insert_hl_id(attr_state, hl_id)
2063      attr_state.modified = true
2064      return id
2065    end
2066    local kind = self._options.rgb and 1 or 2
2067    return 'UNEXPECTED ' .. self:_pprint_attrs(self._attr_table[hl_id][kind])
2068  else
2069    if self:_equal_attrs(attrs, {}) then
2070      -- ignore this attrs
2071      return nil
2072    end
2073    for id, a in pairs(attr_state.ids) do
2074      if self:_equal_attrs(a, attrs) then
2075        return id
2076      end
2077    end
2078    if attr_state.mutable then
2079      table.insert(attr_state.ids, attrs)
2080      attr_state.modified = true
2081      return #attr_state.ids
2082    end
2083    return 'UNEXPECTED ' .. self:_pprint_attrs(attrs)
2084  end
2085end
2086
2087function Screen:_equal_attr_def(a, b)
2088  if self._rgb_cterm then
2089    return self:_equal_attrs(a[1], b[1]) and self:_equal_attrs(a[2], b[2])
2090  elseif self._options.rgb then
2091    return self:_equal_attrs(a, b[1])
2092  else
2093    return self:_equal_attrs(a, b[2])
2094  end
2095end
2096
2097function Screen:_equal_attrs(a, b)
2098  return a.bold == b.bold
2099    and a.standout == b.standout
2100    and a.underline == b.underline
2101    and a.undercurl == b.undercurl
2102    and a.underdouble == b.underdouble
2103    and a.underdotted == b.underdotted
2104    and a.underdashed == b.underdashed
2105    and a.italic == b.italic
2106    and a.reverse == b.reverse
2107    and a.foreground == b.foreground
2108    and a.background == b.background
2109    and a.special == b.special
2110    and a.blend == b.blend
2111    and a.strikethrough == b.strikethrough
2112    and a.fg_indexed == b.fg_indexed
2113    and a.bg_indexed == b.bg_indexed
2114    and a.url == b.url
2115end
2116
2117function Screen:_equal_info(a, b)
2118  return a.kind == b.kind and a.hi_name == b.hi_name and a.ui_name == b.ui_name
2119end
2120
2121function Screen:_attr_index(attrs, attr)
2122  if not attrs then
2123    return nil
2124  end
2125  for i, a in pairs(attrs) do
2126    if self:_equal_attrs(a, attr) then
2127      return i
2128    end
2129  end
2130  return nil
2131end
2132
2133return Screen