robin/laufey

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

Justin M. Keyesfeat(cwd)!: :lcd! (bang), rearrange :bcd/:lcd/… scope precedence #41194a4a544032a

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