-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscreen.lua
More file actions
2093 lines (1901 loc) · 58.2 KB
/
screen.lua
File metadata and controls
2093 lines (1901 loc) · 58.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- This module contains the Screen class, a complete Nvim UI implementation
-- designed for functional testing (verifying screen state, in particular).
--
-- Screen:expect() takes a string representing the expected screen state and an
-- optional set of attribute identifiers for checking highlighted characters.
--
-- Example usage:
--
-- -- Attach a screen to the current Nvim instance.
-- local screen = Screen.new(25, 10)
-- -- Enter insert-mode and type some text.
-- feed('ihello screen')
-- -- Assert the expected screen state.
-- screen:expect([[
-- hello screen^ |
-- {1:~ }|*8
-- {5:-- INSERT --} |
-- ]]) -- <- Last line is stripped
--
-- Since screen updates are received asynchronously, expect() actually specifies
-- the _eventual_ screen state.
--
-- This is how expect() works:
-- * It starts the event loop with a timeout.
-- * Each time it receives an update it checks that against the expected state.
-- * If the expected state matches the current state, the event loop will be
-- stopped and expect() will return.
-- * If the timeout expires, the last match error will be reported and the
-- test will fail.
--
-- The 30 most common highlight groups are predefined, see init_colors() below.
-- In this case "5" is a predefined highlight associated with the set composed of one
-- attribute: bold. Note that since the {5:} markup is not a real part of the
-- screen, the delimiter "|" moved to the right. Also, the highlighting of the
-- NonText markers "~" is visible.
--
-- Tests will often share a group of extra attribute sets to expect(). Those can be
-- defined at the beginning of a test:
--
-- screen:add_extra_attr_ids({
-- [100] = { background = Screen.colors.Plum1, underline = true },
-- [101] = { background = Screen.colors.Red1, bold = true, underline = true },
-- })
--
-- To help write screen tests, see Screen:snapshot_util().
-- To debug screen tests, see Screen:redraw_debug().
local t = require('util')
local n = require('nvim')()
-- local busted = require('busted')
local uv = vim.uv
local deepcopy = vim.deepcopy
local shallowcopy = t.shallowcopy
local concat_tables = t.concat_tables
local pesc = vim.pesc
local run_session = n.run_session
local eq = t.eq
local dedent = t.dedent
local get_session = n.get_session
local create_callindex = n.create_callindex
local inspect = vim.inspect
local function isempty(v)
return type(v) == 'table' and next(v) == nil
end
--- @class test.functional.ui.screen.Grid
--- @field rows table[][]
--- @field width integer
--- @field height integer
--- @class test.functional.ui.screen
--- @field colors table<string,integer>
--- @field colornames table<integer,string>
--- @field uimeths table<string,function>
--- @field options? table<string,any>
--- @field timeout integer
--- @field win_position table<integer,table<string,integer>>
--- @field float_pos table<integer,table>
--- @field cmdline table<integer,table>
--- @field cmdline_hide_level integer?
--- @field cmdline_block table[]
--- @field hl_groups table<string,integer> Highlight group to attr ID map
--- @field hl_names table<integer,string> Highlight ID to group map
--- @field messages table<integer,table>
--- @field private _cursor {grid:integer,row:integer,col:integer}
--- @field private _grids table<integer,test.functional.ui.screen.Grid>
--- @field private _grid_win_extmarks table<integer,table>
--- @field private _attr_table table<integer,table>
--- @field private _hl_info table<integer,table>
--- @field private _stdout uv.uv_pipe_t?
local Screen = {}
Screen.__index = Screen
local default_timeout_factor = 1
if os.getenv('VALGRIND') then
default_timeout_factor = default_timeout_factor * 3
end
if os.getenv('CI') then
default_timeout_factor = default_timeout_factor * 3
end
local default_screen_timeout = default_timeout_factor * 3500
local function _init_colors()
local session = get_session()
local status, rv = session:request('nvim_get_color_map')
if not status then
error('failed to get color map')
end
-- vim.print(rv)
local colors = rv --- @type table<string,integer>
local colornames = {} --- @type table<integer,string>
for name, rgb in pairs(colors) do
-- we disregard the case that colornames might not be unique, as
-- this is just a helper to get any canonical name of a color
colornames[rgb] = name
end
Screen.colors = colors
Screen.colornames = colornames
Screen._global_default_attr_ids = {
[1] = { foreground = Screen.colors.Blue1, bold = true },
[2] = { reverse = true },
[3] = { bold = true, reverse = true },
[4] = { background = Screen.colors.LightMagenta },
[5] = { bold = true },
[6] = { foreground = Screen.colors.SeaGreen, bold = true },
[7] = { background = Screen.colors.Gray, foreground = Screen.colors.DarkBlue },
[8] = { foreground = Screen.colors.Brown },
[9] = { background = Screen.colors.Red, foreground = Screen.colors.Grey100 },
[10] = { background = Screen.colors.Yellow },
[11] = {
foreground = Screen.colors.Blue1,
background = Screen.colors.LightMagenta,
bold = true,
},
[12] = { background = Screen.colors.Gray },
[13] = { background = Screen.colors.LightGrey, foreground = Screen.colors.DarkBlue },
[14] = { background = Screen.colors.DarkGray, foreground = Screen.colors.LightGrey },
[15] = { foreground = Screen.colors.Brown, bold = true },
[16] = { foreground = Screen.colors.SlateBlue },
[17] = { background = Screen.colors.LightGrey, foreground = Screen.colors.Black },
[18] = { foreground = Screen.colors.Blue1 },
[19] = { foreground = Screen.colors.Red },
[20] = { background = Screen.colors.Yellow, foreground = Screen.colors.Red },
[21] = { background = Screen.colors.Grey90 },
[22] = { background = Screen.colors.LightBlue },
[23] = { foreground = Screen.colors.Blue1, background = Screen.colors.LightCyan, bold = true },
[24] = { background = Screen.colors.LightGrey, underline = true },
[25] = { foreground = Screen.colors.Cyan4 },
[26] = { foreground = Screen.colors.Fuchsia },
[27] = { background = Screen.colors.Red, bold = true },
[28] = { foreground = Screen.colors.SlateBlue, underline = true },
[29] = { foreground = Screen.colors.SlateBlue, bold = true },
[30] = { background = Screen.colors.Red },
}
Screen._global_hl_names = {}
for group in pairs(n.api.nvim_get_hl(0, {})) do
Screen._global_hl_names[n.api.nvim_get_hl_id_by_name(group)] = group
end
end
--- @class test.functional.ui.screen.Opts
--- @field ext_linegrid? boolean
--- @field ext_multigrid? boolean
--- @field ext_newgrid? boolean
--- @field ext_popupmenu? boolean
--- @field ext_wildmenu? boolean
--- @field rgb? boolean
--- @field _debug_float? boolean
--- @param width? integer
--- @param height? integer
--- @param options? test.functional.ui.screen.Opts
--- @param session? test.Session|false
--- @return test.functional.ui.screen
function Screen.new(width, height, options, session)
if not Screen.colors then
_init_colors()
end
options = options or {}
if options.ext_linegrid == nil then
options.ext_linegrid = true
end
local self = setmetatable({
timeout = default_screen_timeout,
title = '',
icon = '',
bell = false,
update_menu = false,
visual_bell = false,
suspended = false,
mode = 'normal',
options = {},
pwd = '',
popupmenu = nil,
cmdline = {},
cmdline_block = {},
wildmenu_items = nil,
wildmenu_selected = nil,
win_position = {},
win_viewport = {},
win_viewport_margins = {},
float_pos = {},
msg_grid = nil,
msg_grid_pos = nil,
_session = nil,
rpc_async = false,
messages = {},
msg_history = {},
showmode = {},
showcmd = {},
ruler = {},
hl_groups = {},
hl_names = vim.deepcopy(Screen._global_hl_names),
_default_attr_ids = nil,
mouse_enabled = true,
_attrs = {},
_hl_info = { [0] = {} },
_attr_table = { [0] = { {}, {} } },
_clear_attrs = nil,
_new_attrs = false,
_width = width or 53,
_height = height or 14,
_options = options,
_grids = {},
_grid_win_extmarks = {},
_cursor = {
grid = 1,
row = 1,
col = 1,
},
_busy = false,
_stdout = nil,
}, Screen)
local function ui(method, ...)
if self.rpc_async then
self._session:notify('nvim_ui_' .. method, ...)
else
local status, rv = self._session:request('nvim_ui_' .. method, ...)
if not status then
error(rv[2])
end
end
end
self.uimeths = create_callindex(ui)
-- session is often nil, which implies the default session
if session ~= false then
self:attach(session)
end
return self
end
function Screen:set_default_attr_ids(attr_ids)
self._default_attr_ids = attr_ids
self._attrs_overridden = true
end
function Screen:add_extra_attr_ids(extra_attr_ids)
local attr_ids = vim.deepcopy(Screen._global_default_attr_ids)
for id, attr in pairs(extra_attr_ids) do
if type(id) == 'number' and id < 100 then
error('extra attr ids should be at least 100 or be strings')
end
attr_ids[id] = attr
end
self._default_attr_ids = attr_ids
end
function Screen:set_rgb_cterm(val)
self._rgb_cterm = val
end
--- @param fd number
function Screen:set_stdout(fd)
self._stdout = assert(uv.new_pipe())
self._stdout:open(fd)
end
--- @param session? test.Session
function Screen:attach(session)
session = session or get_session()
local options = self._options
if options.ext_linegrid == nil then
options.ext_linegrid = true
end
self._session = session
self._options = options
self._clear_attrs = (not options.ext_linegrid) and {} or nil
self:_handle_resize(self._width, self._height)
self.uimeths.attach(self._width, self._height, options)
if self._options.rgb == nil then
-- nvim defaults to rgb=true internally,
-- simplify test code by doing the same.
self._options.rgb = true
end
if self._options.ext_multigrid then
self._options.ext_linegrid = true
end
if self._default_attr_ids == nil then
self._default_attr_ids = Screen._global_default_attr_ids
end
end
function Screen:detach()
self.uimeths.detach()
self._session = nil
end
function Screen:try_resize(columns, rows)
self._width = columns
self._height = rows
self.uimeths.try_resize(columns, rows)
end
function Screen:try_resize_grid(grid, columns, rows)
self.uimeths.try_resize_grid(grid, columns, rows)
end
--- @param option 'ext_linegrid'|'ext_multigrid'|'ext_popupmenu'|'ext_wildmenu'|'rgb'
--- @param value boolean
function Screen:set_option(option, value)
self.uimeths.set_option(option, value)
--- @diagnostic disable-next-line:no-unknown
self._options[option] = value
end
-- canonical order of ext keys, used to generate asserts
local ext_keys = {
'popupmenu',
'cmdline',
'cmdline_block',
'wildmenu_items',
'wildmenu_pos',
'messages',
'msg_history',
'showmode',
'showcmd',
'ruler',
'win_pos',
'float_pos',
'win_viewport',
'win_viewport_margins',
}
local expect_keys = {
grid = true,
attr_ids = true,
condition = true,
mouse_enabled = true,
any = true,
none = true,
mode = true,
unchanged = true,
intermediate = true,
reset = true,
timeout = true,
request_cb = true,
hl_groups = true,
extmarks = true,
win_pos = true,
}
for _, v in ipairs(ext_keys) do
expect_keys[v] = true
end
--- @class test.functional.ui.screen.Expect
---
--- Expected screen state (string). Each line represents a screen
--- row. Last character of each row (typically "|") is stripped.
--- Common indentation is stripped.
--- "{MATCH:x}" in a line is matched against Lua pattern `x`.
--- "*n" at the end of a line means it repeats `n` times.
--- @field grid? string
---
--- Expected text attributes. Screen rows are transformed according
--- to this table, as follows: each substring S composed of
--- characters having the same attributes will be substituted by
--- "{K:S}", where K is a key in `attr_ids`. Any unexpected
--- attributes in the final state are an error.
--- Use an empty table for a text-only (no attributes) expectation.
--- Use screen:set_default_attr_ids() to define attributes for many
--- expect() calls.
--- @field attr_ids? table<integer,table<string,any>>
---
--- Expected win_extmarks accumulated for the grids. For each grid,
--- the win_extmark messages are accumulated into an array.
--- @field extmarks? table<integer,table>
---
--- Function asserting some arbitrary condition. Return value is
--- ignored, throw an error (use eq() or similar) to signal failure.
--- @field condition? fun()
---
--- Lua pattern string expected to match a screen line. NB: the
--- following chars are magic characters
--- ( ) . % + - * ? [ ^ $
--- and must be escaped with a preceding % for a literal match.
--- @field any? string|table<string>
---
--- Lua pattern string expected to not match a screen line. NB: the
--- following chars are magic characters
--- ( ) . % + - * ? [ ^ $
--- and must be escaped with a preceding % for a literal match.
--- @field none? string|table<string>
---
--- Expected mode as signaled by "mode_change" event
--- @field mode? string
---
--- Test that the screen state is unchanged since the previous
--- expect(...). Any flush event resulting in a different state is
--- considered an error. Not observing any events until timeout
--- is acceptable.
--- @field unchanged? boolean
---
--- Test that the final state is the same as the previous expect,
--- but expect an intermediate state that is different. If possible
--- it is better to use an explicit screen:expect(...) for this
--- intermediate state.
--- @field intermediate? boolean
---
--- Reset the state internal to the test Screen before starting to
--- receive updates. This should be used after command("redraw!")
--- or some other mechanism that will invoke "redraw!", to check
--- that all screen state is transmitted again. This includes
--- state related to ext_ features as mentioned below.
--- @field reset? boolean
---
--- maximum time that will be waited until the expected state is
--- seen (or maximum time to observe an incorrect change when
--- `unchanged` flag is used)
--- @field timeout? integer
---
--- @field mouse_enabled? boolean
---
--- @field win_viewport? table<integer,table<string,integer>>
--- @field win_pos? table<integer,table<string,integer>>
--- @field float_pos? [integer,integer]
--- @field hl_groups? table<string,integer>
---
--- The following keys should be used to expect the state of various ext_
--- features. Note that an absent key will assert that the item is currently
--- NOT present on the screen, also when positional form is used.
---
--- Expected ext_popupmenu state,
--- @field popupmenu? table
---
--- Expected ext_cmdline state, as an array of cmdlines of
--- different level.
--- @field cmdline? table
---
--- Expected ext_cmdline block (for function definitions)
--- @field cmdline_block? table
---
--- items for ext_wildmenu
--- @field wildmenu_items? table
---
--- position for ext_wildmenu
--- @field wildmenu_pos? table
--- Asserts that the screen state eventually matches an expected state.
---
--- Can be called with positional args:
--- screen:expect(grid, [attr_ids])
--- screen:expect(condition)
--- or keyword args (supports more options):
--- screen:expect({ grid=[[...]], cmdline={...}, condition=function() ... end })
---
--- @param expected string|function|test.functional.ui.screen.Expect
--- @param attr_ids? table<integer,table<string,any>>
function Screen:expect(expected, attr_ids, ...)
--- @type string, fun()
local grid, condition
assert(next({ ... }) == nil, 'invalid args to expect()')
if type(expected) == 'table' then
assert(attr_ids == nil)
for k, _ in
pairs(expected --[[@as table<string,any>]])
do
if not expect_keys[k] then
error("Screen:expect: Unknown keyword argument '" .. k .. "'")
end
end
grid = expected.grid
attr_ids = expected.attr_ids
condition = expected.condition
assert((expected.any == nil and expected.none == nil) or grid == nil)
elseif type(expected) == 'string' then
grid = expected
expected = {}
elseif type(expected) == 'function' then
assert(attr_ids == nil)
condition = expected
expected = {}
else
assert(false)
end
local expected_rows = {} --- @type string[]
if grid then
-- Dedent (ignores last line if it is blank).
grid = dedent(grid, 0)
for row in grid:gmatch('[^\n]+') do
table.insert(expected_rows, row)
end
end
local attr_state = {
ids = attr_ids or self._default_attr_ids,
}
if isempty(attr_ids) then
attr_state.ids = nil
end
if self._options.ext_linegrid then
attr_state.id_to_index = self:linegrid_check_attrs(attr_state.ids or {})
end
self._new_attrs = false
self:_wait(function()
if condition then
--- @type boolean, string
local status, res = pcall(condition)
if not status then
return tostring(res)
end
end
if self._options.ext_linegrid and self._new_attrs then
attr_state.id_to_index = self:linegrid_check_attrs(attr_state.ids or {})
end
local actual_rows
if expected.any or grid then
actual_rows = self:render(not (expected.any or expected.none), attr_state)
end
local any_or_none = function(screen_str, value, is_any)
if value then
local v = value
if type(v) == 'string' then
v = { v }
end
local msg
if is_any then
msg = 'Expected (anywhere): "'
else
msg = 'Expected (nowhere): "'
end
for _, v2 in ipairs(v) do
local test = screen_str:find(v2)
if is_any then
test = not test
end
-- Search for `any` anywhere in the screen lines.
if test then
return (
'Failed to match any screen lines.\n'
.. msg
.. v2
.. '"\n'
.. 'Actual:\n |'
.. table.concat(actual_rows, '\n |')
.. '\n\n'
)
end
end
end
return nil
end
if expected.any or expected.none then
local actual_screen_str = table.concat(actual_rows, '\n')
if expected.any then
local res = any_or_none(actual_screen_str, expected.any, true)
if res then
return res
end
end
if expected.none then
local res = any_or_none(actual_screen_str, expected.none, false)
if res then
return res
end
end
end
if grid then
for i, row in ipairs(expected_rows) do
local count --- @type integer?
row, count = row:match('^(.*%|)%*(%d+)$')
if row then
count = tonumber(count)
table.remove(expected_rows, i)
for _ = 1, count do
table.insert(expected_rows, i, row)
end
end
end
local err_msg = nil
-- `expected` must match the screen lines exactly.
if #actual_rows ~= #expected_rows then
err_msg = 'Expected screen height '
.. #expected_rows
.. ' differs from actual height '
.. #actual_rows
.. '.'
end
local msg_expected_rows = shallowcopy(expected_rows)
local msg_actual_rows = shallowcopy(actual_rows)
for i, row in ipairs(expected_rows) do
local pat = nil --- @type string?
if actual_rows[i] and row ~= actual_rows[i] then
local after = row
while true do
local s, e, m = after:find('{MATCH:(.-)}')
if not s then
pat = pat and (pat .. pesc(after))
break
end
--- @type string
pat = (pat or '') .. pesc(after:sub(1, s - 1)) .. m
after = after:sub(e + 1)
end
end
pat = pat and '^' .. pat .. '$'
if row ~= actual_rows[i] and (not pat or not actual_rows[i]:match(pat)) then
msg_expected_rows[i] = '*' .. msg_expected_rows[i]
if i <= #actual_rows then
msg_actual_rows[i] = '*' .. msg_actual_rows[i]
end
if err_msg == nil then
err_msg = 'Row ' .. tostring(i) .. ' did not match.'
end
end
end
if err_msg ~= nil then
return (
err_msg
.. '\nExpected:\n |'
.. table.concat(msg_expected_rows, '\n |')
.. '\n'
.. 'Actual:\n |'
.. table.concat(msg_actual_rows, '\n |')
.. '\n\n'
.. [[
To print the expect() call that would assert the current screen state, use
screen:snapshot_util(). In case of non-deterministic failures, use
screen:redraw_debug() to show all intermediate screen states.]]
)
end
end
-- UI extensions. The default expectations should cover the case of
-- the ext_ feature being disabled, or the feature currently not activated
-- (e.g. no external cmdline visible). Some extensions require
-- preprocessing to represent highlights in a reproducible way.
local extstate = self:_extstate_repr(attr_state)
if expected.mode ~= nil then
extstate.mode = self.mode
end
if expected.mouse_enabled ~= nil then
extstate.mouse_enabled = self.mouse_enabled
end
if expected.win_viewport == nil then
extstate.win_viewport = nil
end
if expected.win_viewport_margins == nil then
extstate.win_viewport_margins = nil
end
if expected.win_pos == nil then
extstate.win_pos = nil
end
if expected.cmdline == nil then
extstate.cmdline = nil
end
if expected.float_pos then
expected.float_pos = deepcopy(expected.float_pos)
for _, v in pairs(expected.float_pos) do
if not v.external and v[7] == nil then
v[7] = 50
end
end
end
-- Convert assertion errors into invalid screen state descriptions.
for _, k in ipairs(concat_tables(ext_keys, { 'mode', 'mouse_enabled' })) do
-- Empty states are considered the default and need not be mentioned.
if not (expected[k] == nil and isempty(extstate[k])) then
local status, res = pcall(eq, expected[k], extstate[k], k)
if not status then
return (
tostring(res)
.. '\nHint: full state of "'
.. k
.. '":\n '
.. inspect(extstate[k])
)
end
end
end
if expected.hl_groups ~= nil then
for name, id in pairs(expected.hl_groups) do
local expected_hl = attr_state.ids[id]
local actual_hl = self._attr_table[self.hl_groups[name]][(self._options.rgb and 1) or 2]
local status, res = pcall(eq, expected_hl, actual_hl, 'highlight ' .. name)
if not status then
return tostring(res)
end
end
end
if expected.extmarks ~= nil then
for gridid, expected_marks in pairs(expected.extmarks) do
local stored_marks = self._grid_win_extmarks[gridid]
if stored_marks == nil then
return 'no win_extmark for grid ' .. tostring(gridid)
end
local status, res =
pcall(eq, expected_marks, stored_marks, 'extmarks for grid ' .. tostring(gridid))
if not status then
return tostring(res)
end
end
for gridid, _ in pairs(self._grid_win_extmarks) do
local expected_marks = expected.extmarks[gridid]
if expected_marks == nil then
return 'unexpected win_extmark for grid ' .. tostring(gridid)
end
end
end
end, expected)
-- Only test the abort state of a cmdline level once.
if self.cmdline_hide_level ~= nil then
self.cmdline[self.cmdline_hide_level] = nil
self.cmdline_hide_level = nil
end
self.messages, self.msg_history = {}, {}
end
function Screen:expect_unchanged(intermediate, waittime_ms)
-- Collect the current screen state.
local kwargs = self:get_snapshot()
if intermediate then
kwargs.intermediate = true
else
kwargs.unchanged = true
end
kwargs.timeout = waittime_ms
-- Check that screen state does not change.
self:expect(kwargs)
end
--- @private
--- @param check fun(): string
--- @param flags table<string,any>
function Screen:_wait(check, flags)
local err --- @type string?
local checked = false
local success_seen = false
local failure_after_success = false
local did_flush = true
local warn_immediate = not (flags.unchanged or flags.intermediate)
if flags.intermediate and flags.unchanged then
error("Choose only one of 'intermediate' and 'unchanged', not both")
end
if flags.reset then
-- throw away all state, we expect it to be retransmitted
self:_reset()
end
-- Maximum timeout, after which a incorrect state will be regarded as a
-- failure
local timeout = flags.timeout or self.timeout
-- Minimal timeout before the loop is allowed to be stopped so we
-- always do some check for failure after success.
local minimal_timeout = default_timeout_factor * 2
local immediate_seen, intermediate_seen = false, false
if not check() then
minimal_timeout = default_timeout_factor * 20
immediate_seen = true
end
-- For an "unchanged" test, flags.timeout is the time during which the state
-- must not change, so always wait this full time.
if flags.unchanged then
minimal_timeout = flags.timeout or default_timeout_factor * 20
end
assert(timeout >= minimal_timeout)
local did_minimal_timeout = false
local function notification_cb(method, args)
assert(
method == 'redraw',
string.format('notification_cb: unexpected method (%s, args=%s)', method, inspect(args))
)
did_flush = self:_redraw(args)
if not did_flush then
return
end
err = check()
checked = true
if err and immediate_seen then
intermediate_seen = true
end
if not err and (not flags.intermediate or intermediate_seen) then
success_seen = true
if did_minimal_timeout then
self._session:stop()
end
elseif err and success_seen and #args > 0 then
success_seen = false
failure_after_success = true
-- print(inspect(args))
end
return true
end
local eof = run_session(self._session, flags.request_cb, notification_cb, nil, minimal_timeout)
if not did_flush then
if eof then
err = 'no flush received'
end
elseif not checked then
err = check()
if not err and flags.unchanged then
-- expecting NO screen change: use a shorter timeout
success_seen = true
end
end
if not success_seen and not eof then
did_minimal_timeout = true
eof =
run_session(self._session, flags.request_cb, notification_cb, nil, timeout - minimal_timeout)
if not did_flush then
err = 'no flush received'
end
end
local did_warn = false
if warn_immediate and immediate_seen then
print([[
warning: Screen test succeeded immediately. Try to avoid this unless the
purpose of the test really requires it.]])
if intermediate_seen then
print([[
There are intermediate states between the two identical expects.
Use screen:snapshot_util() or screen:redraw_debug() to find them, and add them
to the test if they make sense.
]])
else
print([[If necessary, silence this warning with 'unchanged' argument of screen:expect.]])
end
did_warn = true
end
if failure_after_success then
print([[
warning: Screen changes were received after the expected state. This indicates
indeterminism in the test. Try adding screen:expect(...) (or poke_eventloop())
between asynchronous (feed(), nvim_input()) and synchronous API calls.
- Use screen:redraw_debug() to investigate; it may find relevant intermediate
states that should be added to the test to make it more robust.
- If the purpose of the test is to assert state after some user input sent
with feed(), adding screen:expect() before the feed() will help to ensure
the input is sent when Nvim is in a predictable state. This is preferable
to poke_eventloop(), for being closer to real user interaction.
- poke_eventloop() can trigger redraws and thus generate more indeterminism.
Try removing poke_eventloop().
]])
did_warn = true
end
if err then
if eof then
err = err .. '\n\n' .. eof[2]
end
busted.fail(err .. '\n\nSnapshot:\n' .. self:_print_snapshot(), 3)
elseif did_warn then
if eof then
print(eof[2])
end
local tb = debug.traceback()
local index = string.find(tb, '\n%s*%[C]')
print(string.sub(tb, 1, index))
end
if flags.intermediate then
assert(intermediate_seen, 'expected intermediate screen state before final screen state')
elseif flags.unchanged then
assert(not intermediate_seen, 'expected screen state to be unchanged')
end
end
function Screen:sleep(ms, request_cb)
local function notification_cb(method, args)
assert(method == 'redraw')
self:_redraw(args)
end
run_session(self._session, request_cb, notification_cb, nil, ms)
end
--- @private
--- @param updates {[1]:string, [integer]:any[]}[]
function Screen:_redraw(updates)
local did_flush = false
for k, update in ipairs(updates) do
-- print('--', inspect(update))
local method = update[1]
for i = 2, #update do
local handler_name = '_handle_' .. method
--- @type function
local handler = self[handler_name]
assert(handler ~= nil, 'missing handler: Screen:' .. handler_name)
local status, res = pcall(handler, self, unpack(update[i]))
if not status then
error(
handler_name
.. ' failed'
.. '\n payload: '
.. inspect(update)
.. '\n error: '
.. tostring(res)
)
end
end
if k == #updates and method == 'flush' then
did_flush = true
end
end
return did_flush
end
function Screen:_handle_resize(width, height)
self:_handle_grid_resize(1, width, height)
self._scroll_region = {
top = 1,
bot = height,
left = 1,
right = width,
}
self._grid = self._grids[1]
end
local function min(x, y)
if x < y then
return x
else
return y
end
end
function Screen:_handle_grid_resize(grid, width, height)
local rows = {}
for _ = 1, height do
local cols = {}
for _ = 1, width do
table.insert(cols, { text = ' ', attrs = self._clear_attrs, hl_id = 0 })
end
table.insert(rows, cols)
end
if grid > 1 and self._grids[grid] ~= nil then
local old = self._grids[grid]
for i = 1, min(height, old.height) do
for j = 1, min(width, old.width) do
rows[i][j] = old.rows[i][j]
end
end
end
if self._cursor.grid == grid then