robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
b296666e41
master
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 ) 65return 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 98default_timeout_factor =default_timeout_factor * 3 99end 100 101if os . getenv ( 'CI' ) then 102default_timeout_factor =default_timeout_factor * 3 103end 104 105local default_screen_timeout =default_timeout_factor * 3500 106 107local function _init_colors () 108local session =get_session () 109local status , rv =session : request ( 'nvim_get_color_map' ) 110if not status then 111error ( 'failed to get color map' ) 112end 113local colors =rv --- @type table<string,integer> 114local colornames ={} --- @type table<integer,string> 115for 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 118colornames [ rgb ] =name 119end 120Screen . colors =colors 121Screen . colornames =colornames 122 123Screen . _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 ] ={ 135foreground =Screen . colors . Blue1 , 136background =Screen . colors . LightMagenta , 137bold =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 161Screen . _global_hl_names ={} 162for group in pairs ( n . api . nvim_get_hl ( 0 , {} )) do 163Screen . _global_hl_names [ n . api . nvim_get_hl_id_by_name ( group )] =group 164end 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 ) 182if not Screen . colors then 183_init_colors () 184end 185 186options =options or {} 187if options . ext_linegrid == nil then 188options . ext_linegrid =true 189end 190 191local self =setmetatable ( { 192timeout =default_screen_timeout , 193title ='' , 194icon ='' , 195bell =false , 196update_menu =false , 197visual_bell =false , 198suspended =false , 199mode ='normal' , 200options ={} , 201pwd ='' , 202popupmenu =nil , 203cmdline ={} , 204cmdline_block ={} , 205wildmenu_items =nil , 206wildmenu_selected =nil , 207win_position ={} , 208win_viewport ={} , 209win_viewport_margins ={} , 210float_pos ={} , 211msg_grid =nil , 212msg_grid_pos =nil , 213_session =nil , 214rpc_async =false , 215messages ={} , 216msg_history ={} , 217showmode ={} , 218showcmd ={} , 219ruler ={} , 220hl_groups ={} , 221hl_names =vim . deepcopy ( Screen . _global_hl_names ), 222_default_attr_ids =nil , 223mouse_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 ={ 235grid =1 , 236row =1 , 237col =1 , 238} , 239_busy =false , 240_stdout =nil , 241} , Screen ) 242 243local function ui ( method , ... ) 244if self . rpc_async then 245self . _session : notify ( 'nvim_ui_' .. method , ... ) 246else 247local status , rv =self . _session : request ( 'nvim_ui_' .. method , ... ) 248if not status then 249error ( rv [ 2 ]) 250end 251end 252end 253 254self . uimeths =create_callindex ( ui ) 255 256-- session is often nil, which implies the default session 257if session ~= false then 258self : attach ( session ) 259end 260 261return self 262end 263 264function Screen : set_default_attr_ids ( attr_ids ) 265self . _default_attr_ids =attr_ids 266self . _attrs_overridden =true 267end 268 269function Screen : add_extra_attr_ids ( extra_attr_ids ) 270local attr_ids =vim . deepcopy ( Screen . _global_default_attr_ids ) 271for id , attr in pairs ( extra_attr_ids ) do 272if type ( id ) == 'number' and id < 100 then 273error ( 'extra attr ids should be at least 100 or be strings' ) 274end 275attr_ids [ id ] =attr 276end 277self . _default_attr_ids =attr_ids 278end 279 280function Screen : set_rgb_cterm ( val ) 281self . _rgb_cterm =val 282end 283 284--- @param fd number 285function Screen : set_stdout ( fd ) 286self . _stdout =assert ( uv . new_pipe ()) 287self . _stdout : open ( fd ) 288end 289 290--- @param session? test.Session 291function Screen : attach ( session ) 292session =session or get_session () 293local options =self . _options 294 295if options . ext_linegrid == nil then 296options . ext_linegrid =true 297end 298 299self . _session =session 300self . _options =options 301self . _clear_attrs =( not options . ext_linegrid ) and {} or nil 302self : _handle_resize ( self . _width , self . _height ) 303self . uimeths . attach ( self . _width , self . _height , options ) 304if self . _options . rgb == nil then 305-- nvim defaults to rgb=true internally, 306-- simplify test code by doing the same. 307self . _options . rgb =true 308end 309if self . _options . ext_multigrid then 310self . _options . ext_linegrid =true 311end 312 313if self . _default_attr_ids == nil then 314self . _default_attr_ids =Screen . _global_default_attr_ids 315end 316end 317 318function Screen : detach () 319if self . _stdout and not self . _stdout : is_closing () then 320self . _stdout : close () 321end 322self . _stdout =nil 323self . uimeths . detach () 324self . _session =nil 325end 326 327function Screen : try_resize ( columns , rows ) 328self . _width =columns 329self . _height =rows 330self . uimeths . try_resize ( columns , rows ) 331end 332 333function Screen : try_resize_grid ( grid , columns , rows ) 334self . 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 ) 340self . uimeths . set_option ( option , value ) 341--- @diagnostic disable-next-line:no-unknown 342self . _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 ={ 364grid =true , 365attr_ids =true , 366condition =true , 367mouse_enabled =true , 368any =true , 369none =true , 370mode =true , 371unchanged =true , 372intermediate =true , 373reset =true , 374timeout =true , 375request_cb =true , 376hl_groups =true , 377extmarks =true , 378win_pos =true , 379} 380 381for _ , v in ipairs ( ext_keys ) do 382expect_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() 491local grid , condition 492 493assert ( next ( { ... } ) == nil , 'invalid args to expect()' ) 494 495if type ( expected ) == 'table' then 496assert ( attr_ids == nil ) 497for k , _ in 498pairs ( expected --[[@as table<string,any>]] ) 499do 500if not expect_keys [ k ] then 501error ( "Screen:expect: Unknown keyword argument '" .. k .. "'" ) 502end 503end 504grid =expected . grid 505attr_ids =expected . attr_ids 506condition =expected . condition 507assert (( expected . any == nil and expected . none == nil ) or grid == nil ) 508elseif type ( expected ) == 'string' then 509grid =expected 510expected ={} 511elseif type ( expected ) == 'function' then 512assert ( attr_ids == nil ) 513condition =expected 514expected ={} 515else 516assert ( false ) 517end 518 519local expected_rows ={} --- @type string[] 520if grid then 521-- Dedent (ignores last line if it is blank). 522grid =dedent ( grid , 0 ) 523for row in grid : gmatch ( '[^\n]+' ) do 524table . insert ( expected_rows , row ) 525end 526end 527 528local attr_state ={ 529ids =attr_ids or self . _default_attr_ids , 530} 531 532if isempty ( attr_ids ) then 533attr_state . ids =nil 534end 535 536if self . _options . ext_linegrid then 537attr_state . id_to_index =self : linegrid_check_attrs ( attr_state . ids or {} ) 538end 539 540self . _new_attrs =false 541self : _wait ( function () 542if condition then 543--- @type boolean, string 544local status , res =pcall ( condition ) 545if not status then 546return tostring ( res ) 547end 548end 549 550if self . _options . ext_linegrid and self . _new_attrs then 551attr_state . id_to_index =self : linegrid_check_attrs ( attr_state . ids or {} ) 552end 553 554local actual_rows 555if expected . any or expected . none or grid then 556actual_rows =self : render ( not ( expected . any or expected . none ), attr_state ) 557end 558 559local any_or_none =function ( screen_str , value , is_any ) 560if value then 561local v =value 562if type ( v ) == 'string' then 563v ={ v } 564end 565local msg 566if is_any then 567msg ='Expected (anywhere): "' 568else 569msg ='Expected (nowhere): "' 570end 571for _ , v2 in ipairs ( v ) do 572local test =screen_str : find ( v2 ) 573if is_any then 574test =not test 575end 576-- Search for `any` anywhere in the screen lines. 577if test then 578return ( 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) 587end 588end 589end 590return nil 591end 592if expected . any or expected . none then 593local actual_screen_str =table . concat ( actual_rows , '\n' ) 594if expected . any then 595local res =any_or_none ( actual_screen_str , expected . any , true ) 596if res then 597return res 598end 599end 600if expected . none then 601local res =any_or_none ( actual_screen_str , expected . none , false ) 602if res then 603return res 604end 605end 606end 607 608if grid then 609for i , row in ipairs ( expected_rows ) do 610local count --- @type integer? 611row , count =row : match ( '^(.*%|)%*(%d+)$' ) 612if row then 613count =tonumber ( count ) 614table . remove ( expected_rows , i ) 615for _ =1 , count do 616table . insert ( expected_rows , i , row ) 617end 618end 619end 620local err_msg =nil 621-- `expected` must match the screen lines exactly. 622if # actual_rows ~= # expected_rows then 623err_msg ='Expected screen height ' 624.. # expected_rows 625.. ' differs from actual height ' 626.. # actual_rows 627.. '.' 628end 629local msg_expected_rows =shallowcopy ( expected_rows ) 630local msg_actual_rows =shallowcopy ( actual_rows ) 631for i , row in ipairs ( expected_rows ) do 632local pat =nil --- @type string? 633if actual_rows [ i ] and row ~= actual_rows [ i ] then 634local after =row 635while true do 636local s , e , m =after : find ( '{MATCH:(.-)}' ) 637if not s then 638pat =pat and ( pat .. pesc ( after )) 639break 640end 641--- @type string 642pat =( pat or '' ) .. pesc ( after : sub ( 1 , s - 1 )) .. m 643after =after : sub ( e + 1 ) 644end 645end 646pat =pat and '^' .. pat .. '$' 647if row ~= actual_rows [ i ] and ( not pat or not actual_rows [ i ]: match ( pat )) then 648msg_expected_rows [ i ] ='*' .. msg_expected_rows [ i ] 649if i <= # actual_rows then 650msg_actual_rows [ i ] ='*' .. msg_actual_rows [ i ] 651end 652if err_msg == nil then 653err_msg ='Row ' .. tostring ( i ) .. ' did not match.' 654end 655end 656end 657if err_msg ~= nil then 658return ( 659err_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) 671end 672end 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. 678local extstate =self : _extstate_repr ( attr_state , expected ) 679if expected . mode ~= nil then 680extstate . mode =self . mode 681end 682if expected . mouse_enabled ~= nil then 683extstate . mouse_enabled =self . mouse_enabled 684end 685if expected . win_viewport == nil then 686extstate . win_viewport =nil 687end 688if expected . win_viewport_margins == nil then 689extstate . win_viewport_margins =nil 690end 691if expected . win_pos == nil then 692extstate . win_pos =nil 693end 694if expected . cmdline == nil then 695extstate . cmdline =nil 696end 697 698if expected . float_pos then 699expected . float_pos =deepcopy ( expected . float_pos ) 700for _ , v in pairs ( expected . float_pos ) do 701if not v . external and v [ 7 ] == nil then 702v [ 7 ] =50 703end 704end 705end 706 707-- Convert assertion errors into invalid screen state descriptions. 708for _ , k in ipairs ( concat_tables ( ext_keys , { 'mode' , 'mouse_enabled' } )) do 709-- Empty states are considered the default and need not be mentioned. 710if not ( expected [ k ] == nil and isempty ( extstate [ k ])) then 711local status , res =pcall ( eq , expected [ k ], extstate [ k ], k ) 712if not status then 713return ( 714tostring ( res ) 715.. '\nHint: full state of "' 716.. k 717.. '":\n ' 718.. inspect ( extstate [ k ]) 719) 720end 721end 722end 723 724if expected . hl_groups ~= nil then 725for name , id in pairs ( expected . hl_groups ) do 726local expected_hl =attr_state . ids [ id ] 727local actual_hl =self . _attr_table [ self . hl_groups [ name ]][( self . _options . rgb and 1 ) or 2 ] 728local status , res =pcall ( eq , expected_hl , actual_hl , 'highlight ' .. name ) 729if not status then 730return tostring ( res ) 731end 732end 733end 734 735if expected . extmarks ~= nil then 736for gridid , expected_marks in pairs ( expected . extmarks ) do 737local stored_marks =self . _grid_win_extmarks [ gridid ] 738if stored_marks == nil then 739return 'no win_extmark for grid ' .. tostring ( gridid ) 740end 741local status , res = 742pcall ( eq , expected_marks , stored_marks , 'extmarks for grid ' .. tostring ( gridid )) 743if not status then 744return tostring ( res ) 745end 746end 747for gridid , _ in pairs ( self . _grid_win_extmarks ) do 748local expected_marks =expected . extmarks [ gridid ] 749if expected_marks == nil then 750return 'unexpected win_extmark for grid ' .. tostring ( gridid ) 751end 752end 753end 754end , expected ) 755-- Only test the abort state of a cmdline level once. 756if self . cmdline_hide_level ~= nil then 757self . cmdline [ self . cmdline_hide_level ] =nil 758self . cmdline_hide_level =nil 759end 760self . messages , self . msg_history ={} , {} 761end 762 763function Screen : expect_unchanged ( intermediate , waittime_ms ) 764-- Collect the current screen state. 765local kwargs =self : get_snapshot () 766 767if intermediate then 768kwargs . intermediate =true 769else 770kwargs . unchanged =true 771end 772 773kwargs . timeout =waittime_ms 774-- Check that screen state does not change. 775self : expect ( kwargs ) 776end 777 778--- @private 779--- @param check fun(): string 780--- @param flags table<string,any> 781function Screen : _wait ( check , flags ) 782local err --- @type string? 783local checked =false 784local success_seen =false 785local failure_after_success =false 786local did_flush =true 787local warn_immediate =not ( flags . unchanged or flags . intermediate ) 788 789if flags . intermediate and flags . unchanged then 790error ( "Choose only one of 'intermediate' and 'unchanged', not both" ) 791end 792 793if flags . reset then 794-- throw away all state, we expect it to be retransmitted 795self : _reset () 796end 797 798-- Maximum timeout, after which a incorrect state will be regarded as a 799-- failure 800local 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. 804local minimal_timeout =default_timeout_factor * 2 805 806local immediate_seen , intermediate_seen =false , false 807local intermediate_state_snapshot ='' 808if not check () then 809minimal_timeout =default_timeout_factor * 20 810immediate_seen =true 811end 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. 815if flags . unchanged then 816minimal_timeout =flags . timeout or default_timeout_factor * 20 817elseif flags . intermediate then 818minimal_timeout =default_timeout_factor * 20 819end 820 821assert ( timeout >= minimal_timeout ) 822local did_minimal_timeout =false 823 824local function notification_cb ( method , args ) 825assert ( 826method == 'redraw' , 827string . format ( 'notification_cb: unexpected method (%s, args=%s)' , method , inspect ( args )) 828) 829did_flush =self : _redraw ( args ) 830if not did_flush then 831return 832end 833err =check () 834checked =true 835if err and immediate_seen then 836if not intermediate_seen and flags . unchanged then 837-- Save the first intermediate state for the error message. 838intermediate_state_snapshot =self : _print_snapshot () 839end 840intermediate_seen =true 841end 842 843if not err and ( not flags . intermediate or intermediate_seen ) then 844success_seen =true 845if did_minimal_timeout then 846self . _session : stop () 847end 848elseif err and success_seen and # args > 0 then 849success_seen =false 850failure_after_success =true 851-- print(inspect(args)) 852end 853 854return true 855end 856local eof =run_session ( self . _session , flags . request_cb , notification_cb , nil , minimal_timeout ) 857if not did_flush then 858if eof then 859err ='no flush received' 860end 861elseif not checked then 862err =check () 863if not err and flags . unchanged then 864-- expecting NO screen change: use a shorter timeout 865success_seen =true 866end 867end 868 869if not success_seen and not eof then 870did_minimal_timeout =true 871eof = 872run_session ( self . _session , flags . request_cb , notification_cb , nil , timeout - minimal_timeout ) 873if not did_flush then 874err ='no flush received' 875end 876end 877 878local did_warn =false 879if warn_immediate and immediate_seen then 880( [[ 881 882warning: Screen test succeeded immediately. Try to avoid this unless the 883purpose of the test really requires it.]] ) 884if intermediate_seen then 885( [[ 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]] ) 890else 891( [[If necessary, silence this warning with 'unchanged' argument of screen:expect.]] ) 892end 893did_warn =true 894end 895 896if failure_after_success then 897( [[ 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 903states 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 905with feed(), adding screen:expect() before the feed() will help to ensure 906the input is sent when Nvim is in a predictable state. This is preferable 907to poke_eventloop(), for being closer to real user interaction. 908- poke_eventloop() can trigger redraws and thus generate more indeterminism. 909Try removing poke_eventloop(). 910]] ) 911did_warn =true 912end 913 914if err then 915if eof then 916err =err .. '\n\n' .. eof [ 2 ] 917end 918error ( err .. '\n\nSnapshot:\n' .. self : _print_snapshot (), 3 ) 919elseif did_warn then 920if eof then 921( eof [ 2 ]) 922end 923local tb =debug . traceback () 924local index =string . find ( tb , '\n%s*%[C]' ) 925( string . sub ( tb , 1 , index )) 926end 927 928if flags . intermediate and not intermediate_seen then 929error ( 'Expected intermediate screen state before final screen state' , 3 ) 930elseif flags . unchanged and intermediate_seen then 931error ( 932'Expected screen state to be unchanged.\nIntermediate screen state:\n' 933.. intermediate_state_snapshot , 9343 935) 936end 937end 938 939function Screen : sleep ( ms , request_cb ) 940local function notification_cb ( method , args ) 941assert ( method == 'redraw' ) 942self : _redraw ( args ) 943end 944run_session ( self . _session , request_cb , notification_cb , nil , ms ) 945end 946 947--- @private 948--- @param updates {[1]:string, [integer]:any[]}[] 949function Screen : _redraw ( updates ) 950local did_flush =false 951for k , update in ipairs ( updates ) do 952-- print('--', inspect(update)) 953local method =update [ 1 ] 954for i =2 , # update do 955local handler_name ='_handle_' .. method 956--- @type function 957local handler =self [ handler_name ] 958assert ( handler ~= nil , 'missing handler: Screen:' .. handler_name ) 959local status , res =pcall ( handler , self , unpack ( update [ i ])) 960if not status then 961error ( 962handler_name 963.. ' failed' 964.. '\n payload: ' 965.. inspect ( update ) 966.. '\n error: ' 967.. tostring ( res ) 968) 969end 970end 971if k == # updates and method == 'flush' then 972did_flush =true 973end 974end 975return did_flush 976end 977 978function Screen : _handle_resize ( width , height ) 979self : _handle_grid_resize ( 1 , width , height ) 980self . _scroll_region ={ 981top =1 , 982bot =height , 983left =1 , 984right =width , 985} 986self . _grid =self . _grids [ 1 ] 987end 988 989local function min ( x , y ) 990if x < y then 991return x 992else 993return y 994end 995end 996 997function Screen : _handle_grid_resize ( grid , width , height ) 998local rows ={} 999for _ =1 , height do 1000local cols ={} 1001for _ =1 , width do 1002table . insert ( cols , { text =' ' , attrs =self . _clear_attrs , hl_id =0 } ) 1003end 1004table . insert ( rows , cols ) 1005end 1006if grid > 1 and self . _grids [ grid ] ~= nil then 1007local old =self . _grids [ grid ] 1008for i =1 , min ( height , old . height ) do 1009for j =1 , min ( width , old . width ) do 1010rows [ i ][ j ] =old . rows [ i ][ j ] 1011end 1012end 1013end 1014 1015if self . _cursor . grid == grid then 1016self . _cursor . row =1 -- -1 ? 1017self . _cursor . col =1 1018end 1019self . _grids [ grid ] ={ 1020rows =rows , 1021width =width , 1022height =height , 1023} 1024end 1025 1026function Screen : _handle_msg_set_pos ( grid , row , scrolled , char , zindex , compindex ) 1027self . msg_grid =grid 1028self . msg_grid_pos =row 1029self . msg_scrolled =scrolled 1030self . msg_sep_char =char 1031self . msg_zindex =zindex 1032self . msg_compindex =compindex 1033end 1034 1035function Screen : _handle_flush () end 1036 1037function Screen : _reset () 1038-- TODO: generalize to multigrid later 1039self : _handle_grid_clear ( 1 ) 1040 1041-- TODO: share with initialization, so it generalizes? 1042self . popupmenu =nil 1043self . cmdline ={} 1044self . cmdline_block ={} 1045self . wildmenu_items =nil 1046self . wildmenu_pos =nil 1047self . _grid_win_extmarks ={} 1048self . msg_grid =nil 1049self . msg_grid_pos =nil 1050self . msg_scrolled =false 1051self . 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 ) 1057self . _cursor_style_enabled =cursor_style_enabled 1058for _ , item in pairs ( mode_info ) do 1059-- attr IDs are not stable, but their value should be 1060if item . attr_id ~= nil and self . _attr_table [ item . attr_id ] ~= nil then 1061item . attr =self . _attr_table [ item . attr_id ][ 1 ] 1062item . attr_id =nil 1063end 1064if item . attr_id_lm ~= nil and self . _attr_table [ item . attr_id_lm ] ~= nil then 1065item . attr_lm =self . _attr_table [ item . attr_id_lm ][ 1 ] 1066item . attr_id_lm =nil 1067end 1068end 1069self . _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. 1078local expected_region ={ 1079top =1 , 1080bot =self . _grid . height , 1081left =1 , 1082right =self . _grid . width , 1083} 1084eq ( expected_region , self . _scroll_region ) 1085self : _handle_grid_clear ( 1 ) 1086end 1087 1088function Screen : _handle_grid_clear ( grid ) 1089self : _clear_block ( self . _grids [ grid ], 1 , self . _grids [ grid ]. height , 1 , self . _grids [ grid ]. width ) 1090end 1091 1092function Screen : _handle_grid_destroy ( grid ) 1093self . _grids [ grid ] =nil 1094if self . _options . ext_multigrid then 1095self . win_position [ grid ] =nil 1096self . win_viewport [ grid ] =nil 1097self . win_viewport_margins [ grid ] =nil 1098end 1099end 1100 1101function Screen : _handle_eol_clear () 1102local row , col =self . _cursor . row , self . _cursor . col 1103self : _clear_block ( self . _grid , row , row , col , self . _grid . width ) 1104end 1105 1106function Screen : _handle_cursor_goto ( row , col ) 1107self . _cursor . row =row + 1 1108self . _cursor . col =col + 1 1109end 1110 1111function Screen : _handle_grid_cursor_goto ( grid , row , col ) 1112self . _cursor . grid =grid 1113assert ( row >= 0 and col >= 0 ) 1114self . _cursor . row =row + 1 1115self . _cursor . col =col + 1 1116end 1117 1118function Screen : _handle_win_pos ( grid , win , startrow , startcol , width , height ) 1119self . win_position [ grid ] ={ 1120win =win , 1121startrow =startrow , 1122startcol =startcol , 1123width =width , 1124height =height , 1125} 1126self . float_pos [ grid ] =nil 1127end 1128 1129function Screen : _handle_win_viewport ( 1130grid , 1131win , 1132topline , 1133botline , 1134curline , 1135curcol , 1136linecount , 1137scroll_delta 1138) 1139-- accumulate scroll delta 1140local last_scroll_delta =self . win_viewport [ grid ] and self . win_viewport [ grid ]. sum_scroll_delta 1141or 0 1142self . win_viewport [ grid ] ={ 1143win =win , 1144topline =topline , 1145botline =botline , 1146curline =curline , 1147curcol =curcol , 1148linecount =linecount , 1149sum_scroll_delta =scroll_delta + last_scroll_delta , 1150} 1151end 1152 1153function Screen : _handle_win_viewport_margins ( grid , win , top , bottom , left , right ) 1154self . win_viewport_margins [ grid ] ={ 1155win =win , 1156top =top , 1157bottom =bottom , 1158left =left , 1159right =right , 1160} 1161end 1162 1163function Screen : _handle_win_float_pos ( grid , ... ) 1164self . win_position [ grid ] =nil 1165self . float_pos [ grid ] ={ ... } 1166end 1167 1168function Screen : _handle_win_external_pos ( grid ) 1169self . win_position [ grid ] =nil 1170self . float_pos [ grid ] ={ external =true } 1171end 1172 1173function Screen : _handle_win_hide ( grid ) 1174self . win_position [ grid ] =nil 1175self . float_pos [ grid ] =nil 1176end 1177 1178function Screen : _handle_win_close ( grid ) 1179self . float_pos [ grid ] =nil 1180end 1181 1182function Screen : _handle_win_extmark ( grid , ... ) 1183if self . _grid_win_extmarks [ grid ] == nil then 1184self . _grid_win_extmarks [ grid ] ={} 1185end 1186table . insert ( self . _grid_win_extmarks [ grid ], { ... } ) 1187end 1188 1189function Screen : _handle_busy_start () 1190self . _busy =true 1191end 1192 1193function Screen : _handle_busy_stop () 1194self . _busy =false 1195end 1196 1197function Screen : _handle_mouse_on () 1198self . mouse_enabled =true 1199end 1200 1201function Screen : _handle_mouse_off () 1202self . mouse_enabled =false 1203end 1204 1205function Screen : _handle_mode_change ( mode , idx ) 1206assert ( mode == self . _mode_info [ idx + 1 ]. name ) 1207self . mode =mode 1208end 1209 1210function Screen : _handle_set_scroll_region ( top , bot , left , right ) 1211self . _scroll_region . top =top + 1 1212self . _scroll_region . bot =bot + 1 1213self . _scroll_region . left =left + 1 1214self . _scroll_region . right =right + 1 1215end 1216 1217function Screen : _handle_scroll ( count ) 1218local top =self . _scroll_region . top 1219local bot =self . _scroll_region . bot 1220local left =self . _scroll_region . left 1221local right =self . _scroll_region . right 1222self : _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 ) 1233top =top + 1 1234left =left + 1 1235assert ( cols == 0 ) 1236local grid =self . _grids [ g ] 1237--- @type integer, integer, integer 1238local start , stop , step 1239 1240if rows > 0 then 1241start =top 1242stop =bot - rows 1243step =1 1244else 1245start =bot 1246stop =top - rows 1247step =- 1 1248end 1249 1250-- shift scroll region 1251for i =start , stop , step do 1252local target =grid . rows [ i ] 1253local source =grid . rows [ i + rows ] 1254for j =left , right do 1255target [ j ]. text =source [ j ]. text 1256target [ j ]. attrs =source [ j ]. attrs 1257target [ j ]. hl_id =source [ j ]. hl_id 1258end 1259end 1260 1261-- clear invalid rows 1262for i =stop + step , stop + rows , step do 1263self : _clear_row_section ( grid , i , left , right , true ) 1264end 1265end 1266 1267function Screen : _handle_hl_attr_define ( id , rgb_attrs , cterm_attrs , info ) 1268self . _attr_table [ id ] ={ rgb_attrs , cterm_attrs } 1269self . _hl_info [ id ] =info 1270self . _new_attrs =true 1271end 1272 1273--- @param name string 1274--- @param id integer 1275function Screen : _handle_hl_group_set ( name , id ) 1276self . hl_groups [ name ] =id 1277end 1278 1279function Screen : get_hl ( val ) 1280if self . _options . ext_newgrid then 1281return self . _attr_table [ val ][ 1 ] 1282end 1283return val 1284end 1285 1286function Screen : _handle_highlight_set ( attrs ) 1287self . _attrs =attrs 1288end 1289 1290function Screen : _handle_put ( str ) 1291assert ( not self . _options . ext_linegrid ) 1292local cell =self . _grid . rows [ self . _cursor . row ][ self . _cursor . col ] 1293cell . text =str 1294cell . attrs =self . _attrs 1295cell . hl_id =- 1 1296self . _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 ) 1304assert ( self . _options . ext_linegrid ) 1305assert ( # items > 0 ) 1306local line =self . _grids [ grid ]. rows [ row + 1 ] 1307local colpos =col + 1 1308local hl_id =0 1309line . wrap =wrap 1310for _ , item in ipairs ( items ) do 1311local text , hl_id_cell , count =item [ 1 ], item [ 2 ], item [ 3 ] 1312if hl_id_cell ~= nil then 1313hl_id =hl_id_cell 1314end 1315for _ =1 , ( count or 1 ) do 1316local cell =line [ colpos ] 1317cell . text =text 1318cell . hl_id =hl_id 1319colpos =colpos + 1 1320end 1321end 1322end 1323 1324function Screen : _handle_bell () 1325self . bell =true 1326end 1327 1328function Screen : _handle_visual_bell () 1329self . visual_bell =true 1330end 1331 1332function Screen : _handle_default_colors_set ( rgb_fg , rgb_bg , rgb_sp , cterm_fg , cterm_bg ) 1333self . default_colors ={ 1334rgb_fg =rgb_fg , 1335rgb_bg =rgb_bg , 1336rgb_sp =rgb_sp , 1337cterm_fg =cterm_fg , 1338cterm_bg =cterm_bg , 1339} 1340end 1341 1342function Screen : _handle_update_fg ( fg ) 1343self . _fg =fg 1344end 1345 1346function Screen : _handle_update_bg ( bg ) 1347self . _bg =bg 1348end 1349 1350function Screen : _handle_update_sp ( sp ) 1351self . _sp =sp 1352end 1353 1354function Screen : _handle_suspend () 1355self . suspended =true 1356end 1357 1358function Screen : _handle_update_menu () 1359self . update_menu =true 1360end 1361 1362function Screen : _handle_set_title ( title ) 1363self . title =title 1364end 1365 1366function Screen : _handle_set_icon ( icon ) 1367self . icon =icon 1368end 1369 1370function Screen : _handle_option_set ( name , value ) 1371self . options [ name ] =value 1372end 1373 1374function Screen : _handle_chdir ( path ) 1375self . pwd =vim . fs . normalize ( path , { plain =true } ) 1376end 1377 1378function Screen : _handle_popupmenu_show ( items , selected , row , col , grid ) 1379self . popupmenu ={ items =items , pos =selected , anchor ={ grid , row , col } } 1380end 1381 1382function Screen : _handle_popupmenu_select ( selected ) 1383self . popupmenu . pos =selected 1384end 1385 1386function Screen : _handle_popupmenu_hide () 1387self . popupmenu =nil 1388end 1389 1390function Screen : _handle_cmdline_show ( content , pos , firstc , prompt , indent , level , hl_id ) 1391if firstc == '' then 1392firstc =nil 1393end 1394if hl_id == - 1 then 1395prompt =nil 1396end 1397if indent == 0 then 1398indent =nil 1399end 1400 1401-- check position is valid #10000 1402local len =0 1403for _ , chunk in ipairs ( content ) do 1404len =len + string . len ( chunk [ 2 ]) 1405end 1406assert ( pos <= len ) 1407 1408self . cmdline [ level ] ={ 1409content =content , 1410pos =pos , 1411firstc =firstc , 1412prompt =prompt , 1413indent =indent , 1414hl =hl_id , 1415} 1416end 1417 1418function Screen : _handle_cmdline_hide ( level , abort ) 1419self . cmdline [ level ] =abort and { abort =abort } or nil 1420self . 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 1425self . cmdline [ level ]. special ={ char , shift } 1426end 1427 1428function Screen : _handle_cmdline_pos ( pos , level ) 1429self . cmdline [ level ]. pos =pos 1430end 1431 1432function Screen : _handle_cmdline_block_show ( block ) 1433self . cmdline_block =block 1434end 1435 1436function Screen : _handle_cmdline_block_append ( item ) 1437self . cmdline_block [ # self . cmdline_block + 1 ] =item 1438end 1439 1440function Screen : _handle_cmdline_block_hide () 1441self . cmdline_block ={} 1442end 1443 1444function Screen : _handle_wildmenu_show ( items ) 1445self . wildmenu_items =items 1446end 1447 1448function Screen : _handle_wildmenu_select ( pos ) 1449self . wildmenu_pos =pos 1450end 1451 1452function Screen : _handle_wildmenu_hide () 1453self . wildmenu_items , self . wildmenu_pos =nil , nil 1454end 1455 1456function Screen : _handle_msg_show ( kind , chunks , replace_last , history , append , id , trigger ) 1457local pos =# self . messages 1458if not replace_last or pos == 0 then 1459pos =pos + 1 1460end 1461for i , msg in pairs ( self . messages ) do 1462if id ~= - 1 and msg . id == id then 1463pos =i 1464break 1465end 1466end 1467self . messages [ pos ] ={ 1468kind =kind , 1469content =chunks , 1470history =history , 1471append =append , 1472id =id , 1473trigger =trigger , 1474} 1475end 1476 1477function Screen : _handle_msg_clear () 1478self . messages ={} 1479end 1480 1481function Screen : _handle_msg_showcmd ( msg ) 1482self . showcmd =msg 1483end 1484 1485function Screen : _handle_msg_showmode ( msg ) 1486self . showmode =msg 1487end 1488 1489function Screen : _handle_msg_ruler ( msg ) 1490self . ruler =msg 1491end 1492 1493function Screen : _handle_msg_history_show ( entries , prev_cmd ) 1494self . msg_history ={ entries , prev_cmd } 1495end 1496 1497function Screen : _handle_ui_send ( content ) 1498if self . _stdout then 1499self . _stdout : write ( content ) 1500end 1501end 1502 1503function Screen : _clear_block ( grid , top , bot , left , right ) 1504for i =top , bot do 1505self : _clear_row_section ( grid , i , left , right ) 1506end 1507end 1508 1509function Screen : _clear_row_section ( grid , rownum , startcol , stopcol , invalid ) 1510local row =grid . rows [ rownum ] 1511for i =startcol , stopcol do 1512row [ i ]. text =( invalid and '�' or ' ' ) 1513row [ i ]. attrs =self . _clear_attrs 1514row [ i ]. hl_id =0 1515end 1516end 1517 1518function Screen : _row_repr ( gridnr , rownr , attr_state , cursor ) 1519local rv ={} 1520local current_attr_id 1521local i =1 1522local has_windows =self . _options . ext_multigrid and gridnr == 1 1523local row =self . _grids [ gridnr ]. rows [ rownr ] 1524if has_windows and self . msg_grid and self . msg_grid_pos < rownr then 1525return '[' .. self . msg_grid .. ':' .. string . rep ( '-' , # row ) .. ']' 1526end 1527while i <= # row do 1528local did_window =false 1529if has_windows then 1530for id , pos in pairs ( self . win_position ) do 1531if 1532i - 1 == pos . startcol 1533and pos . startrow <= rownr - 1 1534and rownr - 1 < pos . startrow + pos . height 1535then 1536if current_attr_id then 1537-- close current attribute bracket 1538table . insert ( rv , '}' ) 1539current_attr_id =nil 1540end 1541table . insert ( rv , '[' .. id .. ':' .. string . rep ( '-' , pos . width ) .. ']' ) 1542i =i + pos . width 1543did_window =true 1544end 1545end 1546end 1547 1548if not did_window then 1549local attr_id =self : _get_attr_id ( attr_state , row [ i ]. attrs , row [ i ]. hl_id ) 1550if current_attr_id and attr_id ~= current_attr_id then 1551-- close current attribute bracket 1552table . insert ( rv , '}' ) 1553current_attr_id =nil 1554end 1555if not current_attr_id and attr_id then 1556-- open a new attribute bracket 1557table . insert ( rv , '{' .. attr_id .. ':' ) 1558current_attr_id =attr_id 1559end 1560if not self . _busy and cursor and self . _cursor . col == i then 1561table . insert ( rv , '^' ) 1562end 1563table . insert ( rv , row [ i ]. text ) 1564i =i + 1 1565end 1566end 1567if current_attr_id then 1568table . insert ( rv , '}' ) 1569end 1570-- return the line representation, but remove empty attribute brackets and 1571-- trailing whitespace 1572return table . concat ( rv , '' ) --:gsub('%s+$', '') 1573end 1574 1575local function hl_id_to_name ( self , id ) 1576if id and id > 0 and not self . hl_names [ id ] then 1577self . hl_names [ id ] =n . fn . synIDattr ( id , 'name' ) 1578end 1579return id and self . hl_names [ id ] or nil 1580end 1581 1582function Screen : _extstate_repr ( attr_state , exp ) 1583local cmdline ={} 1584for i , entry in pairs ( self . cmdline ) do 1585entry =shallowcopy ( entry ) 1586if entry . content ~= nil then 1587entry . content =self : _chunks_repr ( entry . content , attr_state ) 1588end 1589entry . hl =hl_id_to_name ( self , entry . hl ) 1590cmdline [ i ] =entry 1591end 1592 1593local cmdline_block ={} 1594for i , entry in ipairs ( self . cmdline_block ) do 1595cmdline_block [ i ] =self : _chunks_repr ( entry , attr_state ) 1596end 1597 1598local messages ={} 1599for i , entry in ipairs ( self . messages ) do 1600local exp_msg =exp and exp . messages and exp . messages [ i ] 1601-- Late addition, only include when expected state includes it. 1602local trigger =nil 1603if exp_msg and exp_msg . trigger ~= nil then 1604trigger =entry . trigger 1605end 1606-- Progress messages are identified by their id, so always show it for them. 1607local id =nil 1608if entry . kind == 'progress' or ( exp_msg and exp_msg . id ~= nil ) then 1609id =entry . id 1610end 1611messages [ i ] ={ 1612kind =entry . kind , 1613content =self : _chunks_repr ( entry . content , attr_state ), 1614history =entry . history or nil , 1615append =entry . append or nil , 1616id =id , 1617trigger =trigger , 1618} 1619end 1620 1621local msg_history ={ prev_cmd =self . msg_history [ 2 ] or nil } 1622for i , entry in ipairs ( self . msg_history [ 1 ] or {} ) do 1623msg_history [ i ] ={ 1624kind =entry [ 1 ], 1625content =self : _chunks_repr ( entry [ 2 ], attr_state ), 1626append =entry [ 3 ] or nil , 1627} 1628end 1629 1630local win_viewport =( next ( self . win_viewport ) and self . win_viewport ) or nil 1631local win_viewport_margins =( next ( self . win_viewport_margins ) and self . win_viewport_margins ) 1632or nil 1633 1634return { 1635popupmenu =self . popupmenu , 1636cmdline =cmdline , 1637cmdline_block =cmdline_block , 1638wildmenu_items =self . wildmenu_items , 1639wildmenu_pos =self . wildmenu_pos , 1640messages =messages , 1641showmode =self : _chunks_repr ( self . showmode , attr_state ), 1642showcmd =self : _chunks_repr ( self . showcmd , attr_state ), 1643ruler =self : _chunks_repr ( self . ruler , attr_state ), 1644msg_history =msg_history , 1645float_pos =self . float_pos , 1646win_viewport =win_viewport , 1647win_viewport_margins =win_viewport_margins , 1648win_pos =self . win_position , 1649} 1650end 1651 1652function Screen : _chunks_repr ( chunks , attr_state ) 1653local repr_chunks ={} 1654for i , chunk in ipairs ( chunks ) do 1655local hl , text , id =unpack ( chunk ) 1656local attrs 1657if self . _options . ext_linegrid then 1658attrs =( self . _attr_table [ hl ] or {} )[ 1 ] -- Tolerate undefined hl_id in a snapshot render. 1659else 1660attrs =hl 1661end 1662local attr_id =self : _get_attr_id ( attr_state , attrs , hl ) 1663repr_chunks [ i ] ={ text , attr_id } 1664repr_chunks [ i ][ # repr_chunks [ i ] + 1 ] =hl_id_to_name ( self , id ) 1665end 1666return 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 1676self : sleep ( 250 , request_cb ) 1677self : print_snapshot () 1678end 1679 1680function Screen : redraw_debug ( timeout ) 1681self : print_snapshot () 1682local function notification_cb ( method , args ) 1683assert ( method == 'redraw' ) 1684for _ , update in ipairs ( args ) do 1685-- mode_info_set is quite verbose, comment out the condition to debug it. 1686if update [ 1 ] ~= 'mode_info_set' then 1687( inspect ( update )) 1688end 1689end 1690self : _redraw ( args ) 1691self : print_snapshot () 1692return true 1693end 1694if timeout == nil then 1695timeout =250 1696end 1697run_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 ) 1705headers =headers and ( self . _options . ext_multigrid or self . _options . _debug_float ) 1706local rv ={} 1707for igrid , grid in vim . spairs ( self . _grids ) do 1708if headers then 1709local suffix ='' 1710if 1711igrid > 1 1712and self . win_position [ igrid ] == nil 1713and self . float_pos [ igrid ] == nil 1714and self . msg_grid ~= igrid 1715then 1716suffix =' (hidden)' 1717end 1718table . insert ( rv , '## grid ' .. igrid .. suffix ) 1719end 1720local height =grid . height 1721if igrid == self . msg_grid then 1722height =self . _grids [ 1 ]. height - self . msg_grid_pos 1723end 1724for i =1 , height do 1725local cursor =self . _cursor . grid == igrid and self . _cursor . row == i 1726local prefix =( headers or preview ) and ' ' or '' 1727table . insert ( rv , prefix .. self : _row_repr ( igrid , i , attr_state , cursor ) .. '|' ) 1728end 1729end 1730return rv 1731end 1732 1733-- Returns the current screen state in the form of a screen:expect() 1734-- keyword-args map. 1735function Screen : get_snapshot () 1736local attr_state ={ 1737ids ={} , 1738mutable =true , -- allow _row_repr to add missing highlights 1739} 1740local attrs =self . _default_attr_ids 1741 1742if attrs ~= nil then 1743for i , a in pairs ( attrs ) do 1744attr_state . ids [ i ] =a 1745end 1746end 1747if self . _options . ext_linegrid then 1748attr_state . id_to_index =self : linegrid_check_attrs ( attr_state . ids or {} ) 1749end 1750 1751local lines =self : render ( true , attr_state , true ) 1752 1753for i , row in ipairs ( lines ) do 1754local count =1 1755while i < # lines and lines [ i + 1 ] == row do 1756count =count + 1 1757table . remove ( lines , i + 1 ) 1758end 1759if count > 1 then 1760lines [ i ] =lines [ i ] .. '*' .. count 1761end 1762end 1763 1764local ext_state =self : _extstate_repr ( attr_state ) 1765for k , v in pairs ( ext_state ) do 1766if isempty ( v ) then 1767ext_state [ k ] =nil -- deleting keys while iterating is ok 1768end 1769end 1770 1771-- Build keyword-args for screen:expect(). 1772local kwargs ={} 1773if attr_state . modified then 1774kwargs [ 'attr_ids' ] ={} 1775for i , a in pairs ( attr_state . ids ) do 1776kwargs [ 'attr_ids' ][ i ] =a 1777end 1778end 1779kwargs [ 'grid' ] =table . concat ( lines , '\n' ) 1780for _ , k in ipairs ( ext_keys ) do 1781if ext_state [ k ] ~= nil then 1782kwargs [ k ] =ext_state [ k ] 1783end 1784end 1785 1786return kwargs , ext_state , attr_state 1787end 1788 1789local function fmt_ext_state ( name , state ) 1790local function remove_all_metatables ( item , path ) 1791if path [ # path ] ~= inspect . METATABLE then 1792return item 1793end 1794end 1795if name == 'win_viewport' then 1796local str ='{\n' 1797for k , v in pairs ( state ) do 1798str =( 1799str 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) 1818end 1819return str .. '}' 1820elseif name == 'float_pos' then 1821local str ='{\n' 1822for k , v in pairs ( state ) do 1823str =str .. ' [' .. k .. '] = {' 1824if v . external then 1825str =str .. ' external = true ' 1826else 1827str =str .. v [ 1 ] 1828for i =2 , # v do 1829str =str .. ', ' .. inspect ( v [ i ]) 1830end 1831end 1832str =str .. '};\n' 1833end 1834return str .. '}' 1835else 1836-- TODO(bfredl): improve formatting of more states 1837return inspect ( state , { process =remove_all_metatables } ) 1838end 1839end 1840 1841function Screen : _print_snapshot () 1842local kwargs , ext_state , attr_state =self : get_snapshot () 1843local attrstr ='' 1844local modify_attrs =not self . _attrs_overridden 1845if attr_state . modified then 1846local attrstrs ={} 1847for i , a in pairs ( attr_state . ids ) do 1848local dict 1849if self . _options . ext_linegrid then 1850dict =self : _pprint_hlitem ( a ) 1851else 1852dict ='{ ' .. self : _pprint_attrs ( a ) .. ' }' 1853end 1854local keyval =( type ( i ) == 'number' ) and '[' .. tostring ( i ) .. ']' or i 1855if not ( type ( i ) == 'number' and modify_attrs and i <= 31 ) then 1856table . insert ( attrstrs , ' ' .. keyval .. ' = ' .. dict .. ',' ) 1857end 1858if modify_attrs then 1859self . _default_attr_ids =attr_state . ids 1860end 1861end 1862local fn_name =modify_attrs and 'add_extra_attr_ids' or 'set_default_attr_ids' 1863attrstr =( 'screen:' .. fn_name .. '({\n' .. table . concat ( attrstrs , '\n' ) .. '\n})\n\n' ) 1864end 1865 1866local extstr ='' 1867for _ , k in ipairs ( ext_keys ) do 1868if ext_state [ k ] ~= nil and not ( k == 'win_viewport' and not self . options . ext_multigrid ) then 1869extstr =extstr .. '\n ' .. k .. ' = ' .. fmt_ext_state ( k , ext_state [ k ]) .. ',' 1870end 1871end 1872 1873return ( '%sscreen:expect(%s%s%s%s%s' ): format ( 1874attrstr , 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]]' , 1878extstr , 1879# extstr > 0 and '\n})' or ')' 1880) 1881end 1882 1883function Screen : print_snapshot () 1884( '\n' .. self : _print_snapshot () .. '\n' ) 1885io . stdout : flush () 1886end 1887 1888function Screen : _insert_hl_id ( attr_state , hl_id ) 1889if attr_state . id_to_index [ hl_id ] ~= nil then 1890return attr_state . id_to_index [ hl_id ] 1891end 1892local raw_info =self . _hl_info [ hl_id ] 1893local info =nil 1894if self . _options . ext_hlstate then 1895info ={} 1896if # raw_info > 1 then 1897for i , item in ipairs ( raw_info ) do 1898info [ i ] =self : _insert_hl_id ( attr_state , item . id ) 1899end 1900else 1901info [ 1 ] ={} 1902for k , v in pairs ( raw_info [ 1 ]) do 1903if k ~= 'id' then 1904info [ 1 ][ k ] =v 1905end 1906end 1907end 1908end 1909 1910local entry =self . _attr_table [ hl_id ] 1911local attrval 1912if self . _rgb_cterm then 1913attrval ={ entry [ 1 ], entry [ 2 ], info } -- unpack() doesn't work 1914elseif self . _options . ext_hlstate then 1915attrval ={ entry [ 1 ], info } 1916else 1917attrval =self . _options . rgb and entry [ 1 ] or entry [ 2 ] 1918end 1919 1920table . insert ( attr_state . ids , attrval ) 1921attr_state . id_to_index [ hl_id ] =# attr_state . ids 1922return # attr_state . ids 1923end 1924 1925function Screen : linegrid_check_attrs ( attrs ) 1926local id_to_index ={} 1927for i , def_attr in pairs ( self . _attr_table ) do 1928local iinfo =self . _hl_info [ i ] 1929local matchinfo ={} 1930if # iinfo > 1 then 1931for k , item in ipairs ( iinfo ) do 1932matchinfo [ k ] =id_to_index [ item . id ] 1933end 1934else 1935matchinfo =iinfo 1936end 1937for k , v in pairs ( attrs ) do 1938local attr , info , attr_rgb , attr_cterm 1939if self . _rgb_cterm then 1940attr_rgb , attr_cterm , info =unpack ( v ) 1941attr ={ attr_rgb , attr_cterm } 1942info =info or {} 1943elseif self . _options . ext_hlstate then 1944attr , info =unpack ( v ) 1945else 1946attr =v 1947info ={} 1948end 1949if self : _equal_attr_def ( attr , def_attr ) then 1950if # info == # matchinfo then 1951local match =false 1952if # info == 1 then 1953if self : _equal_info ( info [ 1 ], matchinfo [ 1 ]) then 1954match =true 1955end 1956else 1957match =true 1958for j =1 , # info do 1959if info [ j ] ~= matchinfo [ j ] then 1960match =false 1961end 1962end 1963end 1964if match then 1965id_to_index [ i ] =k 1966end 1967end 1968end 1969end 1970if 1971self : _equal_attr_def ( self . _rgb_cterm and { {} , {} } or {} , def_attr ) 1972and # self . _hl_info [ i ] == 0 1973then 1974id_to_index [ i ] ='' 1975end 1976end 1977return id_to_index 1978end 1979 1980function Screen : _pprint_hlitem ( item ) 1981-- print(inspect(item)) 1982local multi =self . _rgb_cterm or self . _options . ext_hlstate 1983local cterm =( not self . _rgb_cterm and not self . _options . rgb ) 1984local attrdict ='{ ' .. self : _pprint_attrs ( multi and item [ 1 ] or item , cterm ) .. ' }' 1985local attrdict2 , hlinfo 1986local descdict ='' 1987if self . _rgb_cterm then 1988attrdict2 =', { ' .. self : _pprint_attrs ( item [ 2 ], true ) .. ' }' 1989hlinfo =item [ 3 ] 1990else 1991attrdict2 ='' 1992hlinfo =item [ 2 ] 1993end 1994if self . _options . ext_hlstate then 1995descdict =', { ' .. self : _pprint_hlinfo ( hlinfo ) .. ' }' 1996end 1997return ( multi and '{ ' or '' ) .. attrdict .. attrdict2 .. descdict .. ( multi and ' }' or '' ) 1998end 1999 2000function Screen : _pprint_hlinfo ( states ) 2001if # states == 1 then 2002local items ={} 2003for f , v in pairs ( states [ 1 ]) do 2004local desc =tostring ( v ) 2005if type ( v ) == type ( '' ) then 2006desc ='"' .. desc .. '"' 2007end 2008table . insert ( items , f .. ' = ' .. desc ) 2009end 2010return '{' .. table . concat ( items , ', ' ) .. '}' 2011else 2012return table . concat ( states , ', ' ) 2013end 2014end 2015 2016function Screen : _pprint_attrs ( attrs , cterm ) 2017local items ={} 2018for f , v in pairs ( attrs ) do 2019local desc =tostring ( v ) 2020if f == 'foreground' or f == 'background' or f == 'special' then 2021if Screen . colornames [ v ] ~= nil then 2022desc ='Screen.colors.' .. Screen . colornames [ v ] 2023elseif cterm then 2024desc =tostring ( v ) 2025else 2026desc =string . format ( "tonumber('0x%06x')" , v ) 2027end 2028end 2029table . insert ( items , f .. ' = ' .. desc ) 2030end 2031return table . concat ( items , ', ' ) 2032end 2033 2034---@diagnostic disable-next-line: unused-local, unused-function 2035local function backward_find_meaningful ( tbl , from ) -- luacheck: no unused 2036for i =from or # tbl , 1 , - 1 do 2037if tbl [ i ] ~= ' ' then 2038return i + 1 2039end 2040end 2041return from 2042end 2043 2044function Screen : _get_attr_id ( attr_state , attrs , hl_id ) 2045if not attr_state . ids then 2046return 2047end 2048 2049if self . _options . ext_linegrid then 2050local id =attr_state . id_to_index [ hl_id ] 2051if id == '' then -- sentinel for empty it 2052return nil 2053elseif id ~= nil then 2054return id 2055end 2056if 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 2059return ( 'UNKNOWN_HL_ID(%d)' ): format ( hl_id ) 2060end 2061if attr_state . mutable then 2062id =self : _insert_hl_id ( attr_state , hl_id ) 2063attr_state . modified =true 2064return id 2065end 2066local kind =self . _options . rgb and 1 or 2 2067return 'UNEXPECTED ' .. self : _pprint_attrs ( self . _attr_table [ hl_id ][ kind ]) 2068else 2069if self : _equal_attrs ( attrs , {} ) then 2070-- ignore this attrs 2071return nil 2072end 2073for id , a in pairs ( attr_state . ids ) do 2074if self : _equal_attrs ( a , attrs ) then 2075return id 2076end 2077end 2078if attr_state . mutable then 2079table . insert ( attr_state . ids , attrs ) 2080attr_state . modified =true 2081return # attr_state . ids 2082end 2083return 'UNEXPECTED ' .. self : _pprint_attrs ( attrs ) 2084end 2085end 2086 2087function Screen : _equal_attr_def ( a , b ) 2088if self . _rgb_cterm then 2089return self : _equal_attrs ( a [ 1 ], b [ 1 ]) and self : _equal_attrs ( a [ 2 ], b [ 2 ]) 2090elseif self . _options . rgb then 2091return self : _equal_attrs ( a , b [ 1 ]) 2092else 2093return self : _equal_attrs ( a , b [ 2 ]) 2094end 2095end 2096 2097function Screen : _equal_attrs ( a , b ) 2098return a . bold == b . bold 2099and a . standout == b . standout 2100and a . underline == b . underline 2101and a . undercurl == b . undercurl 2102and a . underdouble == b . underdouble 2103and a . underdotted == b . underdotted 2104and a . underdashed == b . underdashed 2105and a . italic == b . italic 2106and a . reverse == b . reverse 2107and a . foreground == b . foreground 2108and a . background == b . background 2109and a . special == b . special 2110and a . blend == b . blend 2111and a . strikethrough == b . strikethrough 2112and a . fg_indexed == b . fg_indexed 2113and a . bg_indexed == b . bg_indexed 2114and a . url == b . url 2115end 2116 2117function Screen : _equal_info ( a , b ) 2118return 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 ) 2122if not attrs then 2123return nil 2124end 2125for i , a in pairs ( attrs ) do 2126if self : _equal_attrs ( a , attr ) then 2127return i 2128end 2129end 2130return nil 2131end 2132 2133return Screen