robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
a4a544032a
master
1#include <assert.h> 2#include <lauxlib.h> 3#include <lua.h> 4#include <stdarg.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <string.h> 9#include <uv.h> 10 11#include "nvim/context.h" 12#include "nvim/log.h" 13#ifdef NVIM_VENDOR_BIT 14# include "bit.h" 15#endif 16 17#include "cjson/lua_cjson.h" 18#include "mpack/lmpack.h" 19#include "nvim/api/private/defs.h" 20#include "nvim/api/private/helpers.h" 21#include "nvim/ascii_defs.h" 22#include "nvim/autocmd.h" 23#include "nvim/autocmd_defs.h" 24#include "nvim/buffer_defs.h" 25#include "nvim/eval/typval.h" 26#include "nvim/eval/typval_defs.h" 27#include "nvim/eval/vars.h" 28#include "nvim/eval/window.h" 29#include "nvim/ex_cmds_defs.h" 30#include "nvim/ex_docmd.h" 31#include "nvim/ex_eval.h" 32#include "nvim/fold.h" 33#include "nvim/globals.h" 34#include "nvim/keycodes.h" 35#include "nvim/lua/base64.h" 36#include "nvim/lua/converter.h" 37#include "nvim/lua/spell.h" 38#include "nvim/lua/stdlib.h" 39#include "nvim/lua/xdiff.h" 40#include "nvim/map_defs.h" 41#include "nvim/mbyte.h" 42#include "nvim/mbyte_defs.h" 43#include "nvim/memline.h" 44#include "nvim/memory.h" 45#include "nvim/message.h" 46#include "nvim/pos_defs.h" 47#include "nvim/regexp.h" 48#include "nvim/regexp_defs.h" 49#include "nvim/runtime.h" 50#include "nvim/strings.h" 51#include "nvim/types_defs.h" 52#include "nvim/window.h" 53 54#include "lua/stdlib.c.generated.h" 55 56static int regex_match (lua_State * lstate ,regprog_T ** prog ,char * str ) 57{ 58regmatch_T rm ; 59rm .regprog = * prog ; 60rm .rm_ic = false; 61bool match = vim_regexec (& rm ,str ,0 ); 62* prog = rm .regprog ; 63 64if (match ) { 65lua_pushinteger (lstate , (lua_Integer )(rm .startp [0 ]- str )); 66lua_pushinteger (lstate , (lua_Integer )(rm .endp [0 ]- str )); 67return 2 ; 68 } 69return 0 ; 70} 71 72static int regex_match_str (lua_State * lstate ) 73{ 74regprog_T ** prog = regex_check (lstate ); 75const char * str = luaL_checkstring (lstate ,2 ); 76int nret = regex_match (lstate ,prog , (char * )str ); 77 78if (!* prog ) { 79return luaL_error (lstate ,"regex: internal error" ); 80 } 81 82return nret ; 83} 84 85static int regex_match_line (lua_State * lstate ) 86{ 87regprog_T ** prog = regex_check (lstate ); 88 89int narg = lua_gettop (lstate ); 90if (narg < 3 ) { 91return luaL_error (lstate ,"not enough args" ); 92 } 93 94handle_T bufnr = (handle_T )luaL_checkinteger (lstate ,2 ); 95linenr_T rownr = (linenr_T )luaL_checkinteger (lstate ,3 ); 96int start = 0 ; 97int end = -1 ; 98if (narg >=4 ) { 99start = (int )luaL_checkinteger (lstate ,4 ); 100 } 101if (narg >=5 ) { 102end = (int )luaL_checkinteger (lstate ,5 ); 103if (end < 0 ) { 104return luaL_error (lstate ,"invalid end" ); 105 } 106 } 107 108buf_T * buf = bufnr ?handle_get_buffer (bufnr ) :curbuf ; 109if (!buf || buf -> b_ml .ml_mfp == NULL ) { 110return luaL_error (lstate ,"invalid buffer" ); 111 } 112 113if (rownr >=buf -> b_ml .ml_line_count ) { 114return luaL_error (lstate ,"invalid row" ); 115 } 116 117char * line = ml_get_buf (buf ,rownr + 1 ); 118colnr_T len = ml_get_buf_len (buf ,rownr + 1 ); 119 120if (start < 0 || start > len ) { 121return luaL_error (lstate ,"invalid start" ); 122 } 123 124char save = NUL ; 125if (end >=0 ) { 126if (end > len || end < start ) { 127return luaL_error (lstate ,"invalid end" ); 128 } 129save = line [end ]; 130line [end ]= NUL ; 131 } 132 133int nret = regex_match (lstate ,prog ,line + start ); 134 135if (end >=0 ) { 136line [end ]= save ; 137 } 138 139if (!* prog ) { 140return luaL_error (lstate ,"regex: internal error" ); 141 } 142 143return nret ; 144} 145 146static regprog_T ** regex_check (lua_State * L ) 147{ 148return luaL_checkudata (L ,1 ,"nvim_regex" ); 149} 150 151static int regex_gc (lua_State * lstate ) 152{ 153regprog_T ** prog = regex_check (lstate ); 154vim_regfree (* prog ); 155return 0 ; 156} 157 158static int regex_tostring (lua_State * lstate ) 159{ 160lua_pushstring (lstate ,"<regex>" ); 161return 1 ; 162} 163 164static struct luaL_Reg regex_meta []= { 165 {"__gc" ,regex_gc }, 166 {"__tostring" ,regex_tostring }, 167 {"match_str" ,regex_match_str }, 168 {"match_line" ,regex_match_line }, 169 {NULL ,NULL } 170}; 171 172/// convert byte index to UTF-32 and UTF-16 indices 173/// 174/// Expects a string and an optional index. If no index is supplied, the length 175/// of the string is returned. 176/// 177/// Returns two values: the UTF-32 and UTF-16 indices. 178int nlua_str_utfindex (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 179{ 180size_t s1_len ; 181const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 182intptr_t idx ; 183if (lua_isnoneornil (lstate ,2 )) { 184idx = (intptr_t )s1_len ; 185 }else { 186idx = luaL_checkinteger (lstate ,2 ); 187if (idx < 0 || idx > (intptr_t )s1_len ) { 188lua_pushnil (lstate ); 189lua_pushnil (lstate ); 190return 2 ; 191 } 192 } 193 194size_t codepoints = 0 ; 195size_t codeunits = 0 ; 196mb_utflen (s1 , (size_t )idx ,& codepoints ,& codeunits ); 197 198lua_pushinteger (lstate , (lua_Integer )codepoints ); 199lua_pushinteger (lstate , (lua_Integer )codeunits ); 200 201return 2 ; 202} 203 204/// return byte indices of codepoints in a string (only supports utf-8 currently). 205/// 206/// Expects a string. 207/// 208/// Returns a list of codepoints. 209static int nlua_str_utf_pos (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 210{ 211size_t s1_len ; 212const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 213lua_newtable (lstate ); 214 215size_t idx = 1 ; 216size_t clen ; 217for (size_t i = 0 ;i < s1_len && s1 [i ]!= NUL ;i += clen ) { 218clen = (size_t )utf_ptr2len_len (s1 + i , (int )(s1_len - i )); 219lua_pushinteger (lstate , (lua_Integer )i + 1 ); 220lua_rawseti (lstate ,-2 , (int )idx ); 221idx ++ ; 222 } 223 224return 1 ; 225} 226 227/// Return the offset from the 1-indexed byte position to the first byte of the 228/// current character. 229/// 230/// Expects a string and an int. 231/// 232/// Returns the byte offset to the first byte of the current character 233/// pointed into by the offset. 234static int nlua_str_utf_start (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 235{ 236size_t s1_len ; 237const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 238ptrdiff_t offset = luaL_checkinteger (lstate ,2 ); 239if (offset <=0 || offset > (intptr_t )s1_len ) { 240return luaL_error (lstate ,"index out of range" ); 241 } 242size_t const off = (size_t )(offset - 1 ); 243int head_off = - utf_cp_bounds_len (s1 ,s1 + off , (int )(s1_len - off )).begin_off ; 244lua_pushinteger (lstate ,head_off ); 245return 1 ; 246} 247 248/// Return the offset from the 1-indexed byte position to the last 249/// byte of the current character. 250/// 251/// Expects a string and an int. 252/// 253/// Returns the byte offset to the last byte of the current character 254/// pointed into by the offset. 255static int nlua_str_utf_end (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 256{ 257size_t s1_len ; 258const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 259ptrdiff_t offset = luaL_checkinteger (lstate ,2 ); 260if (offset <=0 || offset > (intptr_t )s1_len ) { 261return luaL_error (lstate ,"index out of range" ); 262 } 263size_t const off = (size_t )(offset - 1 ); 264int tail_off = utf_cp_bounds_len (s1 ,s1 + off , (int )(s1_len - off )).end_off - 1 ; 265lua_pushinteger (lstate ,tail_off ); 266return 1 ; 267} 268 269/// convert UTF-32 or UTF-16 indices to byte index. 270/// 271/// Expects up to three args: string, index and use_utf16. 272/// If use_utf16 is not supplied it defaults to false (use UTF-32) 273/// 274/// Returns the byte index. 275int nlua_str_byteindex (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 276{ 277size_t s1_len ; 278const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 279intptr_t idx = luaL_checkinteger (lstate ,2 ); 280if (idx < 0 ) { 281lua_pushnil (lstate ); 282return 1 ; 283 } 284bool use_utf16 = false; 285if (lua_gettop (lstate ) >=3 ) { 286use_utf16 = lua_toboolean (lstate ,3 ); 287 } 288 289ssize_t byteidx = mb_utf_index_to_bytes (s1 ,s1_len , (size_t )idx ,use_utf16 ); 290if (byteidx == -1 ) { 291lua_pushnil (lstate ); 292return 1 ; 293 } 294 295lua_pushinteger (lstate , (lua_Integer )byteidx ); 296 297return 1 ; 298} 299 300int nlua_regex (lua_State * lstate ) 301{ 302Error err = ERROR_INIT ; 303const char * text = luaL_checkstring (lstate ,1 ); 304regprog_T * prog = NULL ; 305 306TRY_WRAP (& err , { 307// RE_NOBREAK: so vim.regex() works in api-fast context. #18111 308prog = vim_regcomp (text ,RE_AUTO |RE_MAGIC |RE_STRICT |RE_NOBREAK ); 309 }); 310 311if (ERROR_SET (& err )) { 312nlua_push_errstr (lstate ,"couldn't parse regex: %s" ,err .msg ); 313api_clear_error (& err ); 314return lua_error (lstate ); 315 }else if (prog == NULL ) { 316nlua_push_errstr (lstate ,"couldn't parse regex" ); 317return lua_error (lstate ); 318 } 319 320regprog_T ** p = lua_newuserdata (lstate ,sizeof (regprog_T * )); 321* p = prog ; 322 323lua_getfield (lstate ,LUA_REGISTRYINDEX ,"nvim_regex" );// [udata, meta] 324lua_setmetatable (lstate ,-2 );// [udata] 325return 1 ; 326} 327 328static dict_T * nlua_get_var_scope (lua_State * lstate ) 329{ 330const char * scope = luaL_checkstring (lstate ,1 ); 331handle_T handle = (handle_T )luaL_checkinteger (lstate ,2 ); 332dict_T * dict = NULL ; 333Error err = ERROR_INIT ; 334if (strequal (scope ,"g" )) { 335dict = get_globvar_dict (); 336 }else if (strequal (scope ,"v" )) { 337dict = get_vimvar_dict (); 338 }else if (strequal (scope ,"b" )) { 339buf_T * buf = find_buffer_by_handle (handle ,& err ); 340if (buf ) { 341dict = buf -> b_vars ; 342 } 343 }else if (strequal (scope ,"w" )) { 344win_T * win = find_window_by_handle (handle ,& err ); 345if (win ) { 346dict = win -> w_vars ; 347 } 348 }else if (strequal (scope ,"t" )) { 349tabpage_T * tabpage = find_tab_by_handle (handle ,& err ); 350if (tabpage ) { 351dict = tabpage -> tp_vars ; 352 } 353 }else { 354luaL_error (lstate ,"invalid scope" ); 355return NULL ; 356 } 357 358if (ERROR_SET (& err )) { 359nlua_push_errstr (lstate ,"scoped variable: %s" ,err .msg ); 360api_clear_error (& err ); 361lua_error (lstate ); 362return NULL ; 363 } 364return dict ; 365} 366 367int nlua_setvar (lua_State * lstate ) 368{ 369// non-local return if not found 370dict_T * dict = nlua_get_var_scope (lstate ); 371String key ; 372key .data = (char * )luaL_checklstring (lstate ,3 ,& key .size ); 373 374bool del = (lua_gettop (lstate )< 4 )|| lua_isnil (lstate ,4 ); 375 376Error err = ERROR_INIT ; 377dictitem_T * di = dict_check_writable (dict ,key ,del ,& err ); 378if (ERROR_SET (& err )) { 379nlua_push_errstr (lstate ,"%s" ,err .msg ); 380api_clear_error (& err ); 381lua_error (lstate ); 382return 0 ; 383 } 384 385bool watched = tv_dict_is_watched (dict ); 386 387if (del ) { 388// Delete the key 389if (di == NULL ) { 390// Doesn't exist, nothing to do 391return 0 ; 392 } 393// Notify watchers 394if (watched ) { 395tv_dict_watcher_notify (dict ,key .data ,NULL ,& di -> di_tv ); 396 } 397 398// Delete the entry 399tv_dict_item_remove (dict ,di ); 400 }else { 401// Update the key 402typval_T tv ; 403 404// Convert the lua value to a vimscript type in the temporary variable 405lua_pushvalue (lstate ,4 ); 406if (!nlua_pop_typval (lstate ,& tv )) { 407return luaL_error (lstate ,"Couldn't convert lua value" ); 408 } 409 410typval_T oldtv = TV_INITIAL_VALUE ; 411 412if (di == NULL ) { 413// Need to create an entry 414di = tv_dict_item_alloc_len (key .data ,key .size ); 415tv_dict_add (dict ,di ); 416 }else { 417bool type_error = false; 418if (dict == get_vimvar_dict () 419&& !before_set_vvar (key .data ,di ,& tv , true,watched ,& type_error )) { 420tv_clear (& tv ); 421if (type_error ) { 422return luaL_error (lstate ,"Setting v:%s to value with wrong type" ,key .data ); 423 } 424return 0 ; 425 } 426if (watched ) { 427tv_copy (& di -> di_tv ,& oldtv ); 428 } 429// Clear the old value 430tv_clear (& di -> di_tv ); 431 } 432 433// Update the value 434tv_copy (& tv ,& di -> di_tv ); 435 436// Notify watchers 437if (watched ) { 438tv_dict_watcher_notify (dict ,key .data ,& tv ,& oldtv ); 439tv_clear (& oldtv ); 440 } 441 442// Clear the temporary variable 443tv_clear (& tv ); 444 } 445return 0 ; 446} 447 448int nlua_getvar (lua_State * lstate ) 449{ 450// non-local return if not found 451dict_T * dict = nlua_get_var_scope (lstate ); 452size_t len ; 453const char * name = luaL_checklstring (lstate ,3 ,& len ); 454 455dictitem_T * di = tv_dict_find (dict ,name , (ptrdiff_t )len ); 456if (di == NULL && dict == get_globvar_dict ()) {// try to autoload script 457if (!script_autoload (name ,len , false)|| aborting ()) { 458return 0 ;// nil 459 } 460di = tv_dict_find (dict ,name , (ptrdiff_t )len ); 461 } 462if (di == NULL ) { 463return 0 ;// nil 464 } 465nlua_push_typval (lstate ,& di -> di_tv ,0 ); 466return 1 ; 467} 468 469/// Compare two strings, ignoring case 470/// 471/// Expects two values on the stack: compared strings. Returns one of the 472/// following numbers: 0, -1 or 1. 473/// 474/// Does no error handling: never call it with non-string or with some arguments 475/// omitted. 476static int nlua_stricmp (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 477{ 478size_t s1_len ; 479size_t s2_len ; 480const char * s1 = luaL_checklstring (lstate ,1 ,& s1_len ); 481const char * s2 = luaL_checklstring (lstate ,2 ,& s2_len ); 482const char * nul1 ; 483const char * nul2 ; 484int ret = 0 ; 485assert (s1 [s1_len ]== NUL ); 486assert (s2 [s2_len ]== NUL ); 487while (true) { 488nul1 = memchr (s1 ,NUL ,s1_len ); 489nul2 = memchr (s2 ,NUL ,s2_len ); 490ret = STRICMP (s1 ,s2 ); 491if (ret == 0 ) { 492// Compare "a\0" greater then "a". 493if ((nul1 == NULL )!= (nul2 == NULL )) { 494ret = ((nul1 != NULL )- (nul2 != NULL )); 495break ; 496 } 497if (nul1 != NULL ) { 498assert (nul2 != NULL ); 499// Can't shift both strings by the same amount of bytes: lowercase 500// letter may have different byte-length than uppercase. 501s1_len -= (size_t )(nul1 - s1 )+ 1 ; 502s2_len -= (size_t )(nul2 - s2 )+ 1 ; 503s1 = nul1 + 1 ; 504s2 = nul2 + 1 ; 505 }else { 506break ; 507 } 508 }else { 509break ; 510 } 511 } 512lua_pop (lstate ,2 ); 513lua_pushnumber (lstate , (lua_Number )((ret > 0 )- (ret < 0 ))); 514return 1 ; 515} 516 517/// Convert string from one encoding to another 518static int nlua_iconv (lua_State * lstate ) 519{ 520int narg = lua_gettop (lstate ); 521 522if (narg < 3 ) { 523return luaL_error (lstate ,"Expected at least 3 arguments" ); 524 } 525 526for (int i = 1 ;i <=3 ;i ++ ) { 527if (lua_type (lstate ,i )!= LUA_TSTRING ) { 528return luaL_argerror (lstate ,i ,"expected string" ); 529 } 530 } 531 532size_t str_len = 0 ; 533const char * str = lua_tolstring (lstate ,1 ,& str_len ); 534 535char * from = enc_canonize (enc_skip ((char * )lua_tolstring (lstate ,2 ,NULL ))); 536char * to = enc_canonize (enc_skip ((char * )lua_tolstring (lstate ,3 ,NULL ))); 537 538vimconv_T vimconv ; 539vimconv .vc_type = CONV_NONE ; 540convert_setup_ext (& vimconv ,from , false,to , false); 541 542char * ret = string_convert (& vimconv , (char * )str ,& str_len ); 543 544convert_setup (& vimconv ,NULL ,NULL ); 545 546xfree (from ); 547xfree (to ); 548 549if (ret == NULL ) { 550lua_pushnil (lstate ); 551 }else { 552lua_pushlstring (lstate ,ret ,str_len ); 553xfree (ret ); 554 } 555 556return 1 ; 557} 558 559// Update foldlevels (e.g., by evaluating 'foldexpr') for the given line range in the given window, 560// without invoking other side effects. Unlike `zx`, it does not close manually opened folds and 561// does not open folds under the cursor. 562static int nlua_foldupdate (lua_State * lstate ) 563{ 564handle_T window = (handle_T )luaL_checkinteger (lstate ,1 ); 565win_T * win = handle_get_window (window ); 566if (!win ) { 567return luaL_error (lstate ,"invalid window" ); 568 } 569// input is zero-based end-exclusive range 570linenr_T top = (linenr_T )luaL_checkinteger (lstate ,2 )+ 1 ; 571if (top < 1 ) { 572return luaL_error (lstate ,"invalid top" ); 573 } 574linenr_T bot = (linenr_T )luaL_checkinteger (lstate ,3 ); 575if (top > bot ) { 576return luaL_error (lstate ,"invalid bot" ); 577 } 578 579foldUpdate (win ,top ,bot ); 580 581return 0 ; 582} 583 584static int nlua_with (lua_State * L ) 585{ 586int flags = 0 ; 587buf_T * buf = NULL ; 588win_T * win = NULL ; 589bool keepcwd = false; 590int log_level = -1 ; 591 592#define APPLY_FLAG (key ,flag ) \ 593 if (strequal((key), k) && (v)) { \ 594 flags |= (flag); \ 595 } 596 597luaL_argcheck (L ,lua_istable (L ,1 ),1 ,"table expected" ); 598lua_pushnil (L );// [dict, ..., nil] 599while (lua_next (L ,1 )) { 600// [dict, ..., key, value] 601if (lua_type (L ,-2 )== LUA_TSTRING ) { 602const char * k = lua_tostring (L ,-2 ); 603bool v = lua_toboolean (L ,-1 ); 604if (strequal ("buf" ,k )) { 605buf = handle_get_buffer ((int )luaL_checkinteger (L ,-1 )); 606 }else if (strequal ("win" ,k )) { 607win = handle_get_window ((int )luaL_checkinteger (L ,-1 )); 608 }else if (strequal ("keepcwd" ,k )) { 609keepcwd = v ; 610 }else if (strequal ("log_level" ,k )) { 611log_level = (int )luaL_checkinteger (L ,-1 ); 612 }else { 613APPLY_FLAG ("sandbox" ,CMOD_SANDBOX ); 614APPLY_FLAG ("silent" ,CMOD_SILENT ); 615APPLY_FLAG ("emsg_silent" ,CMOD_ERRSILENT ); 616APPLY_FLAG ("unsilent" ,CMOD_UNSILENT ); 617APPLY_FLAG ("noautocmd" ,CMOD_NOAUTOCMD ); 618APPLY_FLAG ("hide" ,CMOD_HIDE ); 619APPLY_FLAG ("keepalt" ,CMOD_KEEPALT ); 620APPLY_FLAG ("keepmarks" ,CMOD_KEEPMARKS ); 621APPLY_FLAG ("keepjumps" ,CMOD_KEEPJUMPS ); 622APPLY_FLAG ("lockmarks" ,CMOD_LOCKMARKS ); 623APPLY_FLAG ("keeppatterns" ,CMOD_KEEPPATTERNS ); 624 } 625 } 626// pop the value; lua_next will pop the key. 627lua_pop (L ,1 );// [dict, ..., key] 628 } 629int status = 0 ; 630int rets = 0 ; 631 632if (flags & CMOD_ERRSILENT ) { 633// CMOD_ERRSILENT must imply CMOD_SILENT, otherwise apply_cmdmod() and undo_cmdmod() won't 634// work properly. 635flags |=CMOD_SILENT ; 636 } 637 638const int save_min_log_level = g_min_log_level ; 639if (log_level >=0 ) { 640g_min_log_level = log_level ; 641 } 642cmdmod_T save_cmdmod = cmdmod ; 643CLEAR_FIELD (cmdmod ); 644cmdmod .cmod_flags = flags ; 645apply_cmdmod (& cmdmod ); 646 647Error err = ERROR_INIT ; 648TRY_WRAP (& err , { 649CtxSwitch cs = {0 }; 650bool switched = true; 651 652if (win || buf || keepcwd ) { 653CtxSwitchFlags dirs = keepcwd ?kCtxKeepDirs :kCtxKeepCwd ; 654tabpage_T * tab = win ?win_find_tabpage (win ) :NULL ; 655switched = ctx_switch (& cs ,win ,tab ,buf ,kCtxNoDisplay |dirs | (win ?kCtxValidate :0 )); 656 } 657 658if (switched ) { 659int s = lua_gettop (L ); 660lua_pushvalue (L ,2 ); 661status = lua_pcall (L ,0 ,LUA_MULTRET ,0 ); 662rets = lua_gettop (L )- s ; 663 } 664 665// No-op if nothing was switched. Restores even when ctx_switch() failed. 666ctx_restore (& cs ); 667 }); 668 669undo_cmdmod (& cmdmod ); 670cmdmod = save_cmdmod ; 671if (log_level >=0 ) { 672g_min_log_level = save_min_log_level ; 673 } 674 675if (status ) { 676return lua_error (L ); 677 }else if (ERROR_SET (& err )) { 678nlua_push_errstr (L ,"%s" ,err .msg ); 679api_clear_error (& err ); 680return lua_error (L ); 681 } 682 683return rets ; 684} 685 686/// Parses the internal representation of `keys` (as produced by nvim_replace_termcodes()) into 687/// a structured list of dicts representing one or more key-chords. 688static int nlua_keyparse (lua_State * L ) 689{ 690luaL_argcheck (L ,lua_isstring (L ,1 ),1 ,"string expected" ); 691 692char * escaped = vim_strsave_escape_ks ((char * )lua_tostring (L ,1 )); 693const char * p = escaped ; 694 695lua_newtable (L ); 696 697struct keychord data ; 698 699while (* p != NUL ) { 700// kTrue (same flags as keytrans()) so `keys` == keytrans(vim.keycode(…)). 701const char * keys = str2special (& p , true,kTrue ,& data ); 702 703lua_createtable (L ,0 ,3 ); 704 705lua_newtable (L ); 706for (int i = 0 ;mod_mask_table [i ].name != 'A' ;i ++ ) { 707if ((data .mods & mod_mask_table [i ].mod_mask )== mod_mask_table [i ].mod_flag ) { 708lua_pushlstring (L ,& mod_mask_table [i ].name ,1 ); 709lua_rawseti (L ,-2 , (int )lua_objlen (L ,-2 )+ 1 ); 710 } 711 } 712lua_setfield (L ,-2 ,"mod" ); 713 714lua_pushlstring (L ,data .key .data ,data .key .size ); 715lua_setfield (L ,-2 ,"key" ); 716 717lua_pushstring (L ,keys ); 718lua_setfield (L ,-2 ,"keys" ); 719 720if (data .key_alt .size != 0 ) { 721lua_pushlstring (L ,data .key_alt .data ,data .key_alt .size ); 722lua_setfield (L ,-2 ,"key_alt" ); 723 } 724 725lua_rawseti (L ,-2 , (int )lua_objlen (L ,-2 )+ 1 ); 726 } 727 728xfree (escaped ); 729 730return 1 ; 731} 732 733// Access to internal functions. For use in runtime/ 734static void nlua_state_add_internal (lua_State * const lstate ) 735{ 736// _getvar 737lua_pushcfunction (lstate ,& nlua_getvar ); 738lua_setfield (lstate ,-2 ,"_getvar" ); 739 740// _setvar 741lua_pushcfunction (lstate ,& nlua_setvar ); 742lua_setfield (lstate ,-2 ,"_setvar" ); 743 744// _updatefolds 745lua_pushcfunction (lstate ,& nlua_foldupdate ); 746lua_setfield (lstate ,-2 ,"_foldupdate" ); 747 748lua_pushcfunction (lstate ,& nlua_with ); 749lua_setfield (lstate ,-2 ,"_with_c" ); 750 751// vim._core.keyparse 752lua_getfield (lstate ,-1 ,"_core" ); 753lua_pushcfunction (lstate ,& nlua_keyparse ); 754lua_setfield (lstate ,-2 ,"keyparse" ); 755lua_pop (lstate ,1 ); 756} 757 758void nlua_state_add_stdlib (lua_State * const lstate ,bool is_thread ) 759{ 760if (!is_thread ) { 761// TODO(bfredl): some of basic string functions should already be 762// (or be easy to make) threadsafe 763 764// stricmp 765lua_pushcfunction (lstate ,& nlua_stricmp ); 766lua_setfield (lstate ,-2 ,"stricmp" ); 767// str_utfindex 768lua_pushcfunction (lstate ,& nlua_str_utfindex ); 769lua_setfield (lstate ,-2 ,"_str_utfindex" ); 770// str_byteindex 771lua_pushcfunction (lstate ,& nlua_str_byteindex ); 772lua_setfield (lstate ,-2 ,"_str_byteindex" ); 773// str_utf_pos 774lua_pushcfunction (lstate ,& nlua_str_utf_pos ); 775lua_setfield (lstate ,-2 ,"str_utf_pos" ); 776// str_utf_start 777lua_pushcfunction (lstate ,& nlua_str_utf_start ); 778lua_setfield (lstate ,-2 ,"str_utf_start" ); 779// str_utf_end 780lua_pushcfunction (lstate ,& nlua_str_utf_end ); 781lua_setfield (lstate ,-2 ,"str_utf_end" ); 782// regex 783lua_pushcfunction (lstate ,& nlua_regex ); 784lua_setfield (lstate ,-2 ,"regex" ); 785luaL_newmetatable (lstate ,"nvim_regex" ); 786luaL_register (lstate ,NULL ,regex_meta ); 787 788lua_pushvalue (lstate ,-1 );// [meta, meta] 789lua_setfield (lstate ,-2 ,"__index" );// [meta] 790lua_pop (lstate ,1 );// don't use metatable now 791 792// vim.spell 793luaopen_spell (lstate ); 794lua_setfield (lstate ,-2 ,"spell" ); 795 796// vim.iconv 797// depends on p_ambw, p_emoji 798lua_pushcfunction (lstate ,& nlua_iconv ); 799lua_setfield (lstate ,-2 ,"iconv" ); 800 801// vim.base64 802luaopen_base64 (lstate ); 803lua_setfield (lstate ,-2 ,"base64" ); 804 805nlua_state_add_internal (lstate ); 806 } 807 808// vim.mpack 809luaopen_mpack (lstate ); 810lua_pushvalue (lstate ,-1 ); 811lua_setfield (lstate ,-3 ,"mpack" ); 812 813// package.loaded.mpack = vim.mpack 814// otherwise luv will be reinitialized when require'mpack' 815lua_getglobal (lstate ,"package" ); 816lua_getfield (lstate ,-1 ,"loaded" ); 817lua_pushvalue (lstate ,-3 ); 818lua_setfield (lstate ,-2 ,"mpack" ); 819lua_pop (lstate ,3 ); 820 821// vim.lpeg 822int luaopen_lpeg (lua_State * ); 823luaopen_lpeg (lstate ); 824lua_pushvalue (lstate ,-1 ); 825lua_setfield (lstate ,-4 ,"lpeg" ); 826 827// package.loaded.lpeg = vim.lpeg 828lua_getglobal (lstate ,"package" ); 829lua_getfield (lstate ,-1 ,"loaded" ); 830lua_pushvalue (lstate ,-3 ); 831lua_setfield (lstate ,-2 ,"lpeg" ); 832lua_pop (lstate ,4 ); 833 834// vim.text.diff 835lua_pushcfunction (lstate ,& nlua_xdl_diff ); 836// TODO(justinmk): set vim.text.diff here, or rename this to "_diff". goddamnit. 837lua_setfield (lstate ,-2 ,"diff" ); 838 839// vim.json 840lua_cjson_new (lstate ); 841lua_setfield (lstate ,-2 ,"json" ); 842 843#ifdef NVIM_VENDOR_BIT 844// if building with puc lua, use internal fallback for require'bit' 845int top = lua_gettop (lstate ); 846luaopen_bit (lstate ); 847lua_settop (lstate ,top ); 848#endif 849} 850 851/// like luaL_error, but allow cleanup 852void nlua_push_errstr (lua_State * L ,const char * fmt , ...) 853{ 854va_list argp ; 855va_start (argp ,fmt ); 856luaL_where (L ,1 ); 857lua_pushvfstring (L ,fmt ,argp ); 858va_end (argp ); 859lua_concat (L ,2 ); 860}