xref: /vim-8.2.3635/src/if_lua.c (revision 57e4ee4d)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Lua interface by Luis Carvalho
6  *
7  * Do ":help uganda"  in Vim to read copying and usage conditions.
8  * Do ":help credits" in Vim to see a list of people who contributed.
9  * See README.txt for an overview of the Vim source code.
10  */
11 
12 #include "vim.h"
13 
14 #include <lua.h>
15 #include <lualib.h>
16 #include <lauxlib.h>
17 
18 /* Only do the following when the feature is enabled.  Needed for "make
19  * depend". */
20 #if defined(FEAT_LUA) || defined(PROTO)
21 
22 #define LUAVIM_CHUNKNAME "vim chunk"
23 #define LUAVIM_NAME "vim"
24 #define LUAVIM_EVALNAME "luaeval"
25 #define LUAVIM_EVALHEADER "local _A=select(1,...) return "
26 
27 typedef buf_T *luaV_Buffer;
28 typedef win_T *luaV_Window;
29 typedef dict_T *luaV_Dict;
30 typedef list_T *luaV_List;
31 typedef void (*msgfunc_T)(char_u *);
32 
33 static const char LUAVIM_DICT[] = "dict";
34 static const char LUAVIM_LIST[] = "list";
35 static const char LUAVIM_BUFFER[] = "buffer";
36 static const char LUAVIM_WINDOW[] = "window";
37 static const char LUAVIM_FREE[] = "luaV_free";
38 static const char LUAVIM_LUAEVAL[] = "luaV_luaeval";
39 static const char LUAVIM_SETREF[] = "luaV_setref";
40 
41 /* most functions are closures with a cache table as first upvalue;
42  * get/setudata manage references to vim userdata in cache table through
43  * object pointers (light userdata) */
44 #define luaV_getudata(L, v) \
45     lua_pushlightuserdata((L), (void *) (v)); \
46     lua_rawget((L), lua_upvalueindex(1))
47 #define luaV_setudata(L, v) \
48     lua_pushlightuserdata((L), (void *) (v)); \
49     lua_pushvalue((L), -2); \
50     lua_rawset((L), lua_upvalueindex(1))
51 #define luaV_getfield(L, s) \
52     lua_pushlightuserdata((L), (void *)(s)); \
53     lua_rawget((L), LUA_REGISTRYINDEX)
54 #define luaV_checksandbox(L) \
55     if (sandbox) luaL_error((L), "not allowed in sandbox")
56 #define luaV_msg(L) luaV_msgfunc((L), (msgfunc_T) msg)
57 #define luaV_emsg(L) luaV_msgfunc((L), (msgfunc_T) emsg)
58 
59 static luaV_List *luaV_pushlist (lua_State *L, list_T *lis);
60 static luaV_Dict *luaV_pushdict (lua_State *L, dict_T *dic);
61 
62 #if LUA_VERSION_NUM <= 501
63 #define luaV_openlib(L, l, n) luaL_openlib(L, NULL, l, n)
64 #define luaL_typeerror luaL_typerror
65 #else
66 #define luaV_openlib luaL_setfuncs
67 #endif
68 
69 #ifdef DYNAMIC_LUA
70 
71 #ifndef WIN3264
72 # include <dlfcn.h>
73 # define HANDLE void*
74 # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
75 # define symbol_from_dll dlsym
76 # define close_dll dlclose
77 #else
78 # define load_dll vimLoadLib
79 # define symbol_from_dll GetProcAddress
80 # define close_dll FreeLibrary
81 #endif
82 
83 /* lauxlib */
84 #if LUA_VERSION_NUM <= 501
85 #define luaL_register dll_luaL_register
86 #define luaL_prepbuffer dll_luaL_prepbuffer
87 #define luaL_openlib dll_luaL_openlib
88 #define luaL_typerror dll_luaL_typerror
89 #define luaL_loadfile dll_luaL_loadfile
90 #define luaL_loadbuffer dll_luaL_loadbuffer
91 #else
92 #define luaL_prepbuffsize dll_luaL_prepbuffsize
93 #define luaL_setfuncs dll_luaL_setfuncs
94 #define luaL_loadfilex dll_luaL_loadfilex
95 #define luaL_loadbufferx dll_luaL_loadbufferx
96 #define luaL_argerror dll_luaL_argerror
97 #endif
98 #define luaL_checkany dll_luaL_checkany
99 #define luaL_checklstring dll_luaL_checklstring
100 #define luaL_checkinteger dll_luaL_checkinteger
101 #define luaL_optinteger dll_luaL_optinteger
102 #define luaL_checktype dll_luaL_checktype
103 #define luaL_error dll_luaL_error
104 #define luaL_newstate dll_luaL_newstate
105 #define luaL_buffinit dll_luaL_buffinit
106 #define luaL_addlstring dll_luaL_addlstring
107 #define luaL_pushresult dll_luaL_pushresult
108 /* lua */
109 #if LUA_VERSION_NUM <= 501
110 #define lua_tonumber dll_lua_tonumber
111 #define lua_tointeger dll_lua_tointeger
112 #define lua_call dll_lua_call
113 #define lua_pcall dll_lua_pcall
114 #else
115 #define lua_tonumberx dll_lua_tonumberx
116 #define lua_tointegerx dll_lua_tointegerx
117 #define lua_callk dll_lua_callk
118 #define lua_pcallk dll_lua_pcallk
119 #define lua_getglobal dll_lua_getglobal
120 #define lua_setglobal dll_lua_setglobal
121 #endif
122 #define lua_typename dll_lua_typename
123 #define lua_close dll_lua_close
124 #define lua_gettop dll_lua_gettop
125 #define lua_settop dll_lua_settop
126 #define lua_pushvalue dll_lua_pushvalue
127 #define lua_replace dll_lua_replace
128 #define lua_remove dll_lua_remove
129 #define lua_isnumber dll_lua_isnumber
130 #define lua_isstring dll_lua_isstring
131 #define lua_type dll_lua_type
132 #define lua_rawequal dll_lua_rawequal
133 #define lua_toboolean dll_lua_toboolean
134 #define lua_tolstring dll_lua_tolstring
135 #define lua_touserdata dll_lua_touserdata
136 #define lua_pushnil dll_lua_pushnil
137 #define lua_pushnumber dll_lua_pushnumber
138 #define lua_pushinteger dll_lua_pushinteger
139 #define lua_pushlstring dll_lua_pushlstring
140 #define lua_pushstring dll_lua_pushstring
141 #define lua_pushfstring dll_lua_pushfstring
142 #define lua_pushcclosure dll_lua_pushcclosure
143 #define lua_pushboolean dll_lua_pushboolean
144 #define lua_pushlightuserdata dll_lua_pushlightuserdata
145 #define lua_getfield dll_lua_getfield
146 #define lua_rawget dll_lua_rawget
147 #define lua_rawgeti dll_lua_rawgeti
148 #define lua_createtable dll_lua_createtable
149 #define lua_newuserdata dll_lua_newuserdata
150 #define lua_getmetatable dll_lua_getmetatable
151 #define lua_setfield dll_lua_setfield
152 #define lua_rawset dll_lua_rawset
153 #define lua_rawseti dll_lua_rawseti
154 #define lua_setmetatable dll_lua_setmetatable
155 #define lua_next dll_lua_next
156 /* libs */
157 #define luaopen_base dll_luaopen_base
158 #define luaopen_table dll_luaopen_table
159 #define luaopen_string dll_luaopen_string
160 #define luaopen_math dll_luaopen_math
161 #define luaopen_io dll_luaopen_io
162 #define luaopen_os dll_luaopen_os
163 #define luaopen_package dll_luaopen_package
164 #define luaopen_debug dll_luaopen_debug
165 #define luaL_openlibs dll_luaL_openlibs
166 
167 /* lauxlib */
168 #if LUA_VERSION_NUM <= 501
169 void (*dll_luaL_register) (lua_State *L, const char *libname, const luaL_Reg *l);
170 char *(*dll_luaL_prepbuffer) (luaL_Buffer *B);
171 void (*dll_luaL_openlib) (lua_State *L, const char *libname, const luaL_Reg *l, int nup);
172 int (*dll_luaL_typerror) (lua_State *L, int narg, const char *tname);
173 int (*dll_luaL_loadfile) (lua_State *L, const char *filename);
174 int (*dll_luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz, const char *name);
175 #else
176 char *(*dll_luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
177 void (*dll_luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
178 int (*dll_luaL_loadfilex) (lua_State *L, const char *filename, const char *mode);
179 int (*dll_luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, const char *name, const char *mode);
180 int (*dll_luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
181 #endif
182 void (*dll_luaL_checkany) (lua_State *L, int narg);
183 const char *(*dll_luaL_checklstring) (lua_State *L, int numArg, size_t *l);
184 lua_Integer (*dll_luaL_checkinteger) (lua_State *L, int numArg);
185 lua_Integer (*dll_luaL_optinteger) (lua_State *L, int nArg, lua_Integer def);
186 void (*dll_luaL_checktype) (lua_State *L, int narg, int t);
187 int (*dll_luaL_error) (lua_State *L, const char *fmt, ...);
188 lua_State *(*dll_luaL_newstate) (void);
189 void (*dll_luaL_buffinit) (lua_State *L, luaL_Buffer *B);
190 void (*dll_luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
191 void (*dll_luaL_pushresult) (luaL_Buffer *B);
192 /* lua */
193 #if LUA_VERSION_NUM <= 501
194 lua_Number (*dll_lua_tonumber) (lua_State *L, int idx);
195 lua_Integer (*dll_lua_tointeger) (lua_State *L, int idx);
196 void (*dll_lua_call) (lua_State *L, int nargs, int nresults);
197 int (*dll_lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc);
198 #else
199 lua_Number (*dll_lua_tonumberx) (lua_State *L, int idx, int *isnum);
200 lua_Integer (*dll_lua_tointegerx) (lua_State *L, int idx, int *isnum);
201 void (*dll_lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
202 	lua_CFunction k);
203 int (*dll_lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
204 	int ctx, lua_CFunction k);
205 void (*dll_lua_getglobal) (lua_State *L, const char *var);
206 void (*dll_lua_setglobal) (lua_State *L, const char *var);
207 #endif
208 const char *(*dll_lua_typename) (lua_State *L, int tp);
209 void       (*dll_lua_close) (lua_State *L);
210 int (*dll_lua_gettop) (lua_State *L);
211 void (*dll_lua_settop) (lua_State *L, int idx);
212 void (*dll_lua_pushvalue) (lua_State *L, int idx);
213 void (*dll_lua_replace) (lua_State *L, int idx);
214 void (*dll_lua_remove) (lua_State *L, int idx);
215 int (*dll_lua_isnumber) (lua_State *L, int idx);
216 int (*dll_lua_isstring) (lua_State *L, int idx);
217 int (*dll_lua_type) (lua_State *L, int idx);
218 int (*dll_lua_rawequal) (lua_State *L, int idx1, int idx2);
219 int (*dll_lua_toboolean) (lua_State *L, int idx);
220 const char *(*dll_lua_tolstring) (lua_State *L, int idx, size_t *len);
221 void *(*dll_lua_touserdata) (lua_State *L, int idx);
222 void (*dll_lua_pushnil) (lua_State *L);
223 void (*dll_lua_pushnumber) (lua_State *L, lua_Number n);
224 void (*dll_lua_pushinteger) (lua_State *L, lua_Integer n);
225 void (*dll_lua_pushlstring) (lua_State *L, const char *s, size_t l);
226 void (*dll_lua_pushstring) (lua_State *L, const char *s);
227 const char *(*dll_lua_pushfstring) (lua_State *L, const char *fmt, ...);
228 void (*dll_lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
229 void (*dll_lua_pushboolean) (lua_State *L, int b);
230 void (*dll_lua_pushlightuserdata) (lua_State *L, void *p);
231 void (*dll_lua_getfield) (lua_State *L, int idx, const char *k);
232 void (*dll_lua_rawget) (lua_State *L, int idx);
233 void (*dll_lua_rawgeti) (lua_State *L, int idx, int n);
234 void (*dll_lua_createtable) (lua_State *L, int narr, int nrec);
235 void *(*dll_lua_newuserdata) (lua_State *L, size_t sz);
236 int (*dll_lua_getmetatable) (lua_State *L, int objindex);
237 void (*dll_lua_setfield) (lua_State *L, int idx, const char *k);
238 void (*dll_lua_rawset) (lua_State *L, int idx);
239 void (*dll_lua_rawseti) (lua_State *L, int idx, int n);
240 int (*dll_lua_setmetatable) (lua_State *L, int objindex);
241 int (*dll_lua_next) (lua_State *L, int idx);
242 /* libs */
243 int (*dll_luaopen_base) (lua_State *L);
244 int (*dll_luaopen_table) (lua_State *L);
245 int (*dll_luaopen_string) (lua_State *L);
246 int (*dll_luaopen_math) (lua_State *L);
247 int (*dll_luaopen_io) (lua_State *L);
248 int (*dll_luaopen_os) (lua_State *L);
249 int (*dll_luaopen_package) (lua_State *L);
250 int (*dll_luaopen_debug) (lua_State *L);
251 void (*dll_luaL_openlibs) (lua_State *L);
252 
253 typedef void **luaV_function;
254 typedef struct {
255     const char *name;
256     luaV_function func;
257 } luaV_Reg;
258 
259 static const luaV_Reg luaV_dll[] = {
260     /* lauxlib */
261 #if LUA_VERSION_NUM <= 501
262     {"luaL_register", (luaV_function) &dll_luaL_register},
263     {"luaL_prepbuffer", (luaV_function) &dll_luaL_prepbuffer},
264     {"luaL_openlib", (luaV_function) &dll_luaL_openlib},
265     {"luaL_typerror", (luaV_function) &dll_luaL_typerror},
266     {"luaL_loadfile", (luaV_function) &dll_luaL_loadfile},
267     {"luaL_loadbuffer", (luaV_function) &dll_luaL_loadbuffer},
268 #else
269     {"luaL_prepbuffsize", (luaV_function) &dll_luaL_prepbuffsize},
270     {"luaL_setfuncs", (luaV_function) &dll_luaL_setfuncs},
271     {"luaL_loadfilex", (luaV_function) &dll_luaL_loadfilex},
272     {"luaL_loadbufferx", (luaV_function) &dll_luaL_loadbufferx},
273     {"luaL_argerror", (luaV_function) &dll_luaL_argerror},
274 #endif
275     {"luaL_checkany", (luaV_function) &dll_luaL_checkany},
276     {"luaL_checklstring", (luaV_function) &dll_luaL_checklstring},
277     {"luaL_checkinteger", (luaV_function) &dll_luaL_checkinteger},
278     {"luaL_optinteger", (luaV_function) &dll_luaL_optinteger},
279     {"luaL_checktype", (luaV_function) &dll_luaL_checktype},
280     {"luaL_error", (luaV_function) &dll_luaL_error},
281     {"luaL_newstate", (luaV_function) &dll_luaL_newstate},
282     {"luaL_buffinit", (luaV_function) &dll_luaL_buffinit},
283     {"luaL_addlstring", (luaV_function) &dll_luaL_addlstring},
284     {"luaL_pushresult", (luaV_function) &dll_luaL_pushresult},
285     /* lua */
286 #if LUA_VERSION_NUM <= 501
287     {"lua_tonumber", (luaV_function) &dll_lua_tonumber},
288     {"lua_tointeger", (luaV_function) &dll_lua_tointeger},
289     {"lua_call", (luaV_function) &dll_lua_call},
290     {"lua_pcall", (luaV_function) &dll_lua_pcall},
291 #else
292     {"lua_tonumberx", (luaV_function) &dll_lua_tonumberx},
293     {"lua_tointegerx", (luaV_function) &dll_lua_tointegerx},
294     {"lua_callk", (luaV_function) &dll_lua_callk},
295     {"lua_pcallk", (luaV_function) &dll_lua_pcallk},
296     {"lua_getglobal", (luaV_function) &dll_lua_getglobal},
297     {"lua_setglobal", (luaV_function) &dll_lua_setglobal},
298 #endif
299     {"lua_typename", (luaV_function) &dll_lua_typename},
300     {"lua_close", (luaV_function) &dll_lua_close},
301     {"lua_gettop", (luaV_function) &dll_lua_gettop},
302     {"lua_settop", (luaV_function) &dll_lua_settop},
303     {"lua_pushvalue", (luaV_function) &dll_lua_pushvalue},
304     {"lua_replace", (luaV_function) &dll_lua_replace},
305     {"lua_remove", (luaV_function) &dll_lua_remove},
306     {"lua_isnumber", (luaV_function) &dll_lua_isnumber},
307     {"lua_isstring", (luaV_function) &dll_lua_isstring},
308     {"lua_type", (luaV_function) &dll_lua_type},
309     {"lua_rawequal", (luaV_function) &dll_lua_rawequal},
310     {"lua_toboolean", (luaV_function) &dll_lua_toboolean},
311     {"lua_tolstring", (luaV_function) &dll_lua_tolstring},
312     {"lua_touserdata", (luaV_function) &dll_lua_touserdata},
313     {"lua_pushnil", (luaV_function) &dll_lua_pushnil},
314     {"lua_pushnumber", (luaV_function) &dll_lua_pushnumber},
315     {"lua_pushinteger", (luaV_function) &dll_lua_pushinteger},
316     {"lua_pushlstring", (luaV_function) &dll_lua_pushlstring},
317     {"lua_pushstring", (luaV_function) &dll_lua_pushstring},
318     {"lua_pushfstring", (luaV_function) &dll_lua_pushfstring},
319     {"lua_pushcclosure", (luaV_function) &dll_lua_pushcclosure},
320     {"lua_pushboolean", (luaV_function) &dll_lua_pushboolean},
321     {"lua_pushlightuserdata", (luaV_function) &dll_lua_pushlightuserdata},
322     {"lua_getfield", (luaV_function) &dll_lua_getfield},
323     {"lua_rawget", (luaV_function) &dll_lua_rawget},
324     {"lua_rawgeti", (luaV_function) &dll_lua_rawgeti},
325     {"lua_createtable", (luaV_function) &dll_lua_createtable},
326     {"lua_newuserdata", (luaV_function) &dll_lua_newuserdata},
327     {"lua_getmetatable", (luaV_function) &dll_lua_getmetatable},
328     {"lua_setfield", (luaV_function) &dll_lua_setfield},
329     {"lua_rawset", (luaV_function) &dll_lua_rawset},
330     {"lua_rawseti", (luaV_function) &dll_lua_rawseti},
331     {"lua_setmetatable", (luaV_function) &dll_lua_setmetatable},
332     {"lua_next", (luaV_function) &dll_lua_next},
333     /* libs */
334     {"luaopen_base", (luaV_function) &dll_luaopen_base},
335     {"luaopen_table", (luaV_function) &dll_luaopen_table},
336     {"luaopen_string", (luaV_function) &dll_luaopen_string},
337     {"luaopen_math", (luaV_function) &dll_luaopen_math},
338     {"luaopen_io", (luaV_function) &dll_luaopen_io},
339     {"luaopen_os", (luaV_function) &dll_luaopen_os},
340     {"luaopen_package", (luaV_function) &dll_luaopen_package},
341     {"luaopen_debug", (luaV_function) &dll_luaopen_debug},
342     {"luaL_openlibs", (luaV_function) &dll_luaL_openlibs},
343     {NULL, NULL}
344 };
345 
346 static HANDLE hinstLua = NULL;
347 
348     static void
349 end_dynamic_lua(void)
350 {
351     if (hinstLua)
352     {
353 	close_dll(hinstLua);
354 	hinstLua = 0;
355     }
356 }
357 
358     static int
359 lua_link_init(char *libname, int verbose)
360 {
361     const luaV_Reg *reg;
362     if (hinstLua) return OK;
363     hinstLua = load_dll(libname);
364     if (!hinstLua)
365     {
366 	if (verbose)
367 	    EMSG2(_(e_loadlib), libname);
368 	return FAIL;
369     }
370     for (reg = luaV_dll; reg->func; reg++)
371     {
372 	if ((*reg->func = symbol_from_dll(hinstLua, reg->name)) == NULL)
373 	{
374 	    close_dll(hinstLua);
375 	    hinstLua = 0;
376 	    if (verbose)
377 		EMSG2(_(e_loadfunc), reg->name);
378 	    return FAIL;
379 	}
380     }
381     return OK;
382 }
383 
384     int
385 lua_enabled(int verbose)
386 {
387     return lua_link_init(DYNAMIC_LUA_DLL, verbose) == OK;
388 }
389 
390 #endif /* DYNAMIC_LUA */
391 
392 #if LUA_VERSION_NUM > 501
393     static int
394 luaL_typeerror (lua_State *L, int narg, const char *tname)
395 {
396     const char *msg = lua_pushfstring(L, "%s expected, got %s",
397 	    tname, luaL_typename(L, narg));
398     return luaL_argerror(L, narg, msg);
399 }
400 #endif
401 
402 
403 /* =======   Internal   ======= */
404 
405     static void
406 luaV_newmetatable(lua_State *L, const char *tname)
407 {
408     lua_newtable(L);
409     lua_pushlightuserdata(L, (void *) tname);
410     lua_pushvalue(L, -2);
411     lua_rawset(L, LUA_REGISTRYINDEX);
412 }
413 
414     static void *
415 luaV_toudata(lua_State *L, int ud, const char *tname)
416 {
417     void *p = lua_touserdata(L, ud);
418 
419     if (p != NULL) /* value is userdata? */
420     {
421 	if (lua_getmetatable(L, ud)) /* does it have a metatable? */
422 	{
423 	    luaV_getfield(L, tname); /* get metatable */
424 	    if (lua_rawequal(L, -1, -2)) /* MTs match? */
425 	    {
426 		lua_pop(L, 2); /* MTs */
427 		return p;
428 	    }
429 	}
430     }
431     return NULL;
432 }
433 
434     static void *
435 luaV_checkcache(lua_State *L, void *p)
436 {
437     luaV_getudata(L, p);
438     if (lua_isnil(L, -1)) luaL_error(L, "invalid object");
439     lua_pop(L, 1);
440     return p;
441 }
442 
443 #define luaV_unbox(L,luatyp,ud) (*((luatyp *) lua_touserdata((L),(ud))))
444 
445 #define luaV_checkvalid(L,luatyp,ud) \
446     luaV_checkcache((L), (void *) luaV_unbox((L),luatyp,(ud)))
447 
448     static void *
449 luaV_checkudata(lua_State *L, int ud, const char *tname)
450 {
451     void *p = luaV_toudata(L, ud, tname);
452     if (p == NULL) luaL_typeerror(L, ud, tname);
453     return p;
454 }
455 
456     static void
457 luaV_pushtypval(lua_State *L, typval_T *tv)
458 {
459     if (tv == NULL)
460     {
461 	lua_pushnil(L);
462 	return;
463     }
464     switch (tv->v_type)
465     {
466 	case VAR_STRING:
467 	    lua_pushstring(L, tv->vval.v_string == NULL
468 					    ? "" : (char *)tv->vval.v_string);
469 	    break;
470 	case VAR_NUMBER:
471 	    lua_pushinteger(L, (int) tv->vval.v_number);
472 	    break;
473 #ifdef FEAT_FLOAT
474 	case VAR_FLOAT:
475 	    lua_pushnumber(L, (lua_Number) tv->vval.v_float);
476 	    break;
477 #endif
478 	case VAR_LIST:
479 	    luaV_pushlist(L, tv->vval.v_list);
480 	    break;
481 	case VAR_DICT:
482 	    luaV_pushdict(L, tv->vval.v_dict);
483 	    break;
484 	default:
485 	    lua_pushnil(L);
486     }
487 }
488 
489 /* converts lua value at 'pos' to typval 'tv' */
490     static void
491 luaV_totypval (lua_State *L, int pos, typval_T *tv)
492 {
493     switch(lua_type(L, pos)) {
494 	case LUA_TBOOLEAN:
495 	    tv->v_type = VAR_NUMBER;
496 	    tv->vval.v_number = (varnumber_T) lua_toboolean(L, pos);
497 	    break;
498 	case LUA_TSTRING:
499 	    tv->v_type = VAR_STRING;
500 	    tv->vval.v_string = vim_strsave((char_u *) lua_tostring(L, pos));
501 	    break;
502 	case LUA_TNUMBER:
503 #ifdef FEAT_FLOAT
504 	    tv->v_type = VAR_FLOAT;
505 	    tv->vval.v_float = (float_T) lua_tonumber(L, pos);
506 #else
507 	    tv->v_type = VAR_NUMBER;
508 	    tv->vval.v_number = (varnumber_T) lua_tointeger(L, pos);
509 #endif
510 	    break;
511 	case LUA_TUSERDATA: {
512 	    void *p = lua_touserdata(L, pos);
513 	    if (lua_getmetatable(L, pos)) /* has metatable? */
514 	    {
515 		/* check list */
516 		luaV_getfield(L, LUAVIM_LIST);
517 		if (lua_rawequal(L, -1, -2))
518 		{
519 		    tv->v_type = VAR_LIST;
520 		    tv->vval.v_list = *((luaV_List *) p);
521 		    ++tv->vval.v_list->lv_refcount;
522 		    lua_pop(L, 2); /* MTs */
523 		    return;
524 		}
525 		/* check dict */
526 		luaV_getfield(L, LUAVIM_DICT);
527 		if (lua_rawequal(L, -1, -3))
528 		{
529 		    tv->v_type = VAR_DICT;
530 		    tv->vval.v_dict = *((luaV_Dict *) p);
531 		    ++tv->vval.v_dict->dv_refcount;
532 		    lua_pop(L, 3); /* MTs */
533 		    return;
534 		}
535 		lua_pop(L, 3); /* MTs */
536 	    }
537 	    break;
538 	}
539 	default:
540 	    tv->v_type = VAR_NUMBER;
541 	    tv->vval.v_number = 0;
542     }
543 }
544 
545 /* similar to luaL_addlstring, but replaces \0 with \n if toline and
546  * \n with \0 otherwise */
547     static void
548 luaV_addlstring(luaL_Buffer *b, const char *s, size_t l, int toline)
549 {
550     while (l--)
551     {
552 	if (*s == '\0' && toline)
553 	    luaL_addchar(b, '\n');
554 	else if (*s == '\n' && !toline)
555 	    luaL_addchar(b, '\0');
556 	else
557 	    luaL_addchar(b, *s);
558 	s++;
559     }
560 }
561 
562     static void
563 luaV_pushline(lua_State *L, buf_T *buf, linenr_T n)
564 {
565     const char *s = (const char *) ml_get_buf(buf, n, FALSE);
566     luaL_Buffer b;
567     luaL_buffinit(L, &b);
568     luaV_addlstring(&b, s, strlen(s), 0);
569     luaL_pushresult(&b);
570 }
571 
572     static char_u *
573 luaV_toline(lua_State *L, int pos)
574 {
575     size_t l;
576     const char *s = lua_tolstring(L, pos, &l);
577 
578     luaL_Buffer b;
579     luaL_buffinit(L, &b);
580     luaV_addlstring(&b, s, l, 1);
581     luaL_pushresult(&b);
582     return (char_u *) lua_tostring(L, -1);
583 }
584 
585 /* pops a string s from the top of the stack and calls mf(t) for pieces t of
586  * s separated by newlines */
587     static void
588 luaV_msgfunc(lua_State *L, msgfunc_T mf)
589 {
590     luaL_Buffer b;
591     size_t l;
592     const char *p, *s = lua_tolstring(L, -1, &l);
593     luaL_buffinit(L, &b);
594     luaV_addlstring(&b, s, l, 0);
595     luaL_pushresult(&b);
596     /* break string */
597     p = s = lua_tolstring(L, -1, &l);
598     while (l--)
599     {
600 	if (*p++ == '\0') /* break? */
601 	{
602 	    mf((char_u *) s);
603 	    s = p;
604 	}
605     }
606     mf((char_u *) s);
607     lua_pop(L, 2); /* original and modified strings */
608 }
609 
610 #define luaV_newtype(typ,tname,luatyp,luatname) \
611 	static luatyp * \
612     luaV_new##tname (lua_State *L, typ *obj) \
613     { \
614 	luatyp *o = (luatyp *) lua_newuserdata(L, sizeof(luatyp)); \
615 	*o = obj; \
616 	luaV_setudata(L, obj); /* cache[obj] = udata */ \
617 	luaV_getfield(L, luatname); \
618 	lua_setmetatable(L, -2); \
619 	return o; \
620     }
621 
622 #define luaV_pushtype(typ,tname,luatyp) \
623 	static luatyp * \
624     luaV_push##tname (lua_State *L, typ *obj) \
625     { \
626 	luatyp *o = NULL; \
627 	if (obj == NULL) \
628 	    lua_pushnil(L); \
629 	else { \
630 	    luaV_getudata(L, obj); \
631 	    if (lua_isnil(L, -1)) /* not interned? */ \
632 	    { \
633 		lua_pop(L, 1); \
634 		o = luaV_new##tname(L, obj); \
635 	    } \
636 	    else \
637 		o = (luatyp *) lua_touserdata(L, -1); \
638 	} \
639 	return o; \
640     }
641 
642 #define luaV_type_tostring(tname,luatname) \
643 	static int \
644     luaV_##tname##_tostring (lua_State *L) \
645     { \
646 	lua_pushfstring(L, "%s: %p", luatname, lua_touserdata(L, 1)); \
647 	return 1; \
648     }
649 
650 /* =======   List type   ======= */
651 
652     static luaV_List *
653 luaV_newlist (lua_State *L, list_T *lis)
654 {
655     luaV_List *l = (luaV_List *) lua_newuserdata(L, sizeof(luaV_List));
656     *l = lis;
657     lis->lv_refcount++; /* reference in Lua */
658     luaV_setudata(L, lis); /* cache[lis] = udata */
659     luaV_getfield(L, LUAVIM_LIST);
660     lua_setmetatable(L, -2);
661     return l;
662 }
663 
664 luaV_pushtype(list_T, list, luaV_List)
665 luaV_type_tostring(list, LUAVIM_LIST)
666 
667     static int
668 luaV_list_gc (lua_State *L)
669 {
670     list_unref(luaV_unbox(L, luaV_List, 1));
671     return 0;
672 }
673 
674     static int
675 luaV_list_len (lua_State *L)
676 {
677     list_T *l = luaV_unbox(L, luaV_List, 1);
678     lua_pushinteger(L, (l == NULL) ? 0 : (int) l->lv_len);
679     return 1;
680 }
681 
682     static int
683 luaV_list_iter (lua_State *L)
684 {
685     listitem_T *li = (listitem_T *) lua_touserdata(L, lua_upvalueindex(2));
686     if (li == NULL) return 0;
687     luaV_pushtypval(L, &li->li_tv);
688     lua_pushlightuserdata(L, (void *) li->li_next);
689     lua_replace(L, lua_upvalueindex(2));
690     return 1;
691 }
692 
693     static int
694 luaV_list_call (lua_State *L)
695 {
696     list_T *l = luaV_unbox(L, luaV_List, 1);
697     lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
698     lua_pushlightuserdata(L, (void *) l->lv_first);
699     lua_pushcclosure(L, luaV_list_iter, 2);
700     return 1;
701 }
702 
703     static int
704 luaV_list_index (lua_State *L)
705 {
706     list_T *l = luaV_unbox(L, luaV_List, 1);
707     if (lua_isnumber(L, 2)) /* list item? */
708     {
709 	listitem_T *li = list_find(l, (long) luaL_checkinteger(L, 2));
710 	if (li == NULL)
711 	    lua_pushnil(L);
712 	else
713 	    luaV_pushtypval(L, &li->li_tv);
714     }
715     else if (lua_isstring(L, 2)) /* method? */
716     {
717 	const char *s = lua_tostring(L, 2);
718 	if (strncmp(s, "add", 3) == 0
719 		|| strncmp(s, "insert", 6) == 0
720 		|| strncmp(s, "extend", 6) == 0)
721 	{
722 	    lua_getmetatable(L, 1);
723 	    lua_getfield(L, -1, s);
724 	}
725 	else
726 	    lua_pushnil(L);
727     }
728     else
729 	lua_pushnil(L);
730     return 1;
731 }
732 
733     static int
734 luaV_list_newindex (lua_State *L)
735 {
736     list_T *l = luaV_unbox(L, luaV_List, 1);
737     long n = (long) luaL_checkinteger(L, 2);
738     listitem_T *li;
739     if (l->lv_lock)
740 	luaL_error(L, "list is locked");
741     li = list_find(l, n);
742     if (li == NULL) return 0;
743     if (lua_isnil(L, 3)) /* remove? */
744     {
745 	list_remove(l, li, li);
746 	clear_tv(&li->li_tv);
747 	vim_free(li);
748     }
749     else
750     {
751 	typval_T v;
752 	luaV_totypval(L, 3, &v);
753 	clear_tv(&li->li_tv);
754 	copy_tv(&v, &li->li_tv);
755     }
756     return 0;
757 }
758 
759     static int
760 luaV_list_add (lua_State *L)
761 {
762     luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
763     list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
764     listitem_T *li;
765     if (l->lv_lock)
766 	luaL_error(L, "list is locked");
767     li = listitem_alloc();
768     if (li != NULL)
769     {
770 	typval_T v;
771 	lua_settop(L, 2);
772 	luaV_totypval(L, 2, &v);
773 	list_append_tv(l, &v);
774     }
775     lua_settop(L, 1);
776     return 1;
777 }
778 
779     static int
780 luaV_list_insert (lua_State *L)
781 {
782     luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
783     list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
784     long pos = luaL_optlong(L, 3, 0);
785     listitem_T *li = NULL;
786     typval_T v;
787     if (l->lv_lock)
788 	luaL_error(L, "list is locked");
789     if (pos < l->lv_len)
790     {
791 	li = list_find(l, pos);
792 	if (li == NULL)
793 	    luaL_error(L, "invalid position");
794     }
795     lua_settop(L, 2);
796     luaV_totypval(L, 2, &v);
797     list_insert_tv(l, &v, li);
798     lua_settop(L, 1);
799     return 1;
800 }
801 
802 static const luaL_Reg luaV_List_mt[] = {
803     {"__tostring", luaV_list_tostring},
804     {"__gc", luaV_list_gc},
805     {"__len", luaV_list_len},
806     {"__call", luaV_list_call},
807     {"__index", luaV_list_index},
808     {"__newindex", luaV_list_newindex},
809     {"add", luaV_list_add},
810     {"insert", luaV_list_insert},
811     {NULL, NULL}
812 };
813 
814 
815 /* =======   Dict type   ======= */
816 
817     static luaV_Dict *
818 luaV_newdict (lua_State *L, dict_T *dic)
819 {
820     luaV_Dict *d = (luaV_Dict *) lua_newuserdata(L, sizeof(luaV_Dict));
821     *d = dic;
822     dic->dv_refcount++; /* reference in Lua */
823     luaV_setudata(L, dic); /* cache[dic] = udata */
824     luaV_getfield(L, LUAVIM_DICT);
825     lua_setmetatable(L, -2);
826     return d;
827 }
828 
829 luaV_pushtype(dict_T, dict, luaV_Dict)
830 luaV_type_tostring(dict, LUAVIM_DICT)
831 
832     static int
833 luaV_dict_gc (lua_State *L)
834 {
835     dict_unref(luaV_unbox(L, luaV_Dict, 1));
836     return 0;
837 }
838 
839     static int
840 luaV_dict_len (lua_State *L)
841 {
842     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
843     lua_pushinteger(L, (d == NULL) ? 0 : (int) d->dv_hashtab.ht_used);
844     return 1;
845 }
846 
847     static int
848 luaV_dict_iter (lua_State *L)
849 {
850     hashitem_T *hi = (hashitem_T *) lua_touserdata(L, lua_upvalueindex(2));
851     int n = lua_tointeger(L, lua_upvalueindex(3));
852     dictitem_T *di;
853     if (n <= 0) return 0;
854     while (HASHITEM_EMPTY(hi)) hi++;
855     di = dict_lookup(hi);
856     lua_pushstring(L, (char *) hi->hi_key);
857     luaV_pushtypval(L, &di->di_tv);
858     lua_pushlightuserdata(L, (void *) (hi + 1));
859     lua_replace(L, lua_upvalueindex(2));
860     lua_pushinteger(L, n - 1);
861     lua_replace(L, lua_upvalueindex(3));
862     return 2;
863 }
864 
865     static int
866 luaV_dict_call (lua_State *L)
867 {
868     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
869     hashtab_T *ht = &d->dv_hashtab;
870     lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
871     lua_pushlightuserdata(L, (void *) ht->ht_array);
872     lua_pushinteger(L, ht->ht_used); /* # remaining items */
873     lua_pushcclosure(L, luaV_dict_iter, 3);
874     return 1;
875 }
876 
877     static int
878 luaV_dict_index (lua_State *L)
879 {
880     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
881     char_u *key = (char_u *) luaL_checkstring(L, 2);
882     dictitem_T *di = dict_find(d, key, -1);
883     if (di == NULL)
884 	lua_pushnil(L);
885     else
886 	luaV_pushtypval(L, &di->di_tv);
887     return 1;
888 }
889 
890     static int
891 luaV_dict_newindex (lua_State *L)
892 {
893     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
894     char_u *key = (char_u *) luaL_checkstring(L, 2);
895     dictitem_T *di;
896     if (d->dv_lock)
897 	luaL_error(L, "dict is locked");
898     di = dict_find(d, key, -1);
899     if (di == NULL) /* non-existing key? */
900     {
901 	if (lua_isnil(L, 3)) return 0;
902 	di = dictitem_alloc(key);
903 	if (di == NULL) return 0;
904 	if (dict_add(d, di) == FAIL)
905 	{
906 		vim_free(di);
907 		return 0;
908 	}
909     }
910     else
911 	clear_tv(&di->di_tv);
912     if (lua_isnil(L, 3)) /* remove? */
913     {
914 	hashitem_T *hi = hash_find(&d->dv_hashtab, di->di_key);
915 	hash_remove(&d->dv_hashtab, hi);
916 	dictitem_free(di);
917     }
918     else {
919 	typval_T v;
920 	luaV_totypval(L, 3, &v);
921 	copy_tv(&v, &di->di_tv);
922     }
923     return 0;
924 }
925 
926 static const luaL_Reg luaV_Dict_mt[] = {
927     {"__tostring", luaV_dict_tostring},
928     {"__gc", luaV_dict_gc},
929     {"__len", luaV_dict_len},
930     {"__call", luaV_dict_call},
931     {"__index", luaV_dict_index},
932     {"__newindex", luaV_dict_newindex},
933     {NULL, NULL}
934 };
935 
936 
937 /* =======   Buffer type   ======= */
938 
939 luaV_newtype(buf_T, buffer, luaV_Buffer, LUAVIM_BUFFER)
940 luaV_pushtype(buf_T, buffer, luaV_Buffer)
941 luaV_type_tostring(buffer, LUAVIM_BUFFER)
942 
943     static int
944 luaV_buffer_len(lua_State *L)
945 {
946     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
947     lua_pushinteger(L, b->b_ml.ml_line_count);
948     return 1;
949 }
950 
951     static int
952 luaV_buffer_call(lua_State *L)
953 {
954     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
955     lua_settop(L, 1);
956     set_curbuf(b, DOBUF_SPLIT);
957     return 1;
958 }
959 
960     static int
961 luaV_buffer_index(lua_State *L)
962 {
963     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
964     linenr_T n = (linenr_T) lua_tointeger(L, 2);
965     if (n > 0 && n <= b->b_ml.ml_line_count)
966 	luaV_pushline(L, b, n);
967     else if (lua_isstring(L, 2))
968     {
969 	const char *s = lua_tostring(L, 2);
970 	if (strncmp(s, "name", 4) == 0)
971 	    lua_pushstring(L, (char *) b->b_sfname);
972 	else if (strncmp(s, "fname", 5) == 0)
973 	    lua_pushstring(L, (char *) b->b_ffname);
974 	else if (strncmp(s, "number", 6) == 0)
975 	    lua_pushinteger(L, b->b_fnum);
976 	/* methods */
977 	else if (strncmp(s,   "insert", 6) == 0
978 		|| strncmp(s, "next", 4) == 0
979 		|| strncmp(s, "previous", 8) == 0
980 		|| strncmp(s, "isvalid", 7) == 0)
981 	{
982 	    lua_getmetatable(L, 1);
983 	    lua_getfield(L, -1, s);
984 	}
985 	else
986 	    lua_pushnil(L);
987     }
988     else
989 	lua_pushnil(L);
990     return 1;
991 }
992 
993     static int
994 luaV_buffer_newindex(lua_State *L)
995 {
996     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
997     linenr_T n = (linenr_T) luaL_checkinteger(L, 2);
998 #ifdef HAVE_SANDBOX
999     luaV_checksandbox(L);
1000 #endif
1001     if (n < 1 || n > b->b_ml.ml_line_count)
1002 	luaL_error(L, "invalid line number");
1003     if (lua_isnil(L, 3)) /* delete line */
1004     {
1005 	buf_T *buf = curbuf;
1006 	curbuf = b;
1007 	if (u_savedel(n, 1L) == FAIL)
1008 	{
1009 	    curbuf = buf;
1010 	    luaL_error(L, "cannot save undo information");
1011 	}
1012 	else if (ml_delete(n, FALSE) == FAIL)
1013 	{
1014 	    curbuf = buf;
1015 	    luaL_error(L, "cannot delete line");
1016 	}
1017 	else {
1018 	    deleted_lines_mark(n, 1L);
1019 	    if (b == curwin->w_buffer) /* fix cursor in current window? */
1020 	    {
1021 		if (curwin->w_cursor.lnum >= n)
1022 		{
1023 		    if (curwin->w_cursor.lnum > n)
1024 		    {
1025 			curwin->w_cursor.lnum -= 1;
1026 			check_cursor_col();
1027 		    }
1028 		    else check_cursor();
1029 		    changed_cline_bef_curs();
1030 		}
1031 		invalidate_botline();
1032 	    }
1033 	}
1034 	curbuf = buf;
1035     }
1036     else if (lua_isstring(L, 3)) /* update line */
1037     {
1038 	buf_T *buf = curbuf;
1039 	curbuf = b;
1040 	if (u_savesub(n) == FAIL)
1041 	{
1042 	    curbuf = buf;
1043 	    luaL_error(L, "cannot save undo information");
1044 	}
1045 	else if (ml_replace(n, luaV_toline(L, 3), TRUE) == FAIL)
1046 	{
1047 	    curbuf = buf;
1048 	    luaL_error(L, "cannot replace line");
1049 	}
1050 	else changed_bytes(n, 0);
1051 	curbuf = buf;
1052 	if (b == curwin->w_buffer)
1053 	    check_cursor_col();
1054     }
1055     else
1056 	luaL_error(L, "wrong argument to change line");
1057     return 0;
1058 }
1059 
1060     static int
1061 luaV_buffer_insert(lua_State *L)
1062 {
1063     luaV_Buffer *lb = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1064     buf_T *b = (buf_T *) luaV_checkcache(L, (void *) *lb);
1065     linenr_T last = b->b_ml.ml_line_count;
1066     linenr_T n = (linenr_T) luaL_optinteger(L, 3, last);
1067     buf_T *buf;
1068     luaL_checktype(L, 2, LUA_TSTRING);
1069 #ifdef HAVE_SANDBOX
1070     luaV_checksandbox(L);
1071 #endif
1072     /* fix insertion line */
1073     if (n < 0) n = 0;
1074     if (n > last) n = last;
1075     /* insert */
1076     buf = curbuf;
1077     curbuf = b;
1078     if (u_save(n, n + 1) == FAIL)
1079     {
1080 	curbuf = buf;
1081 	luaL_error(L, "cannot save undo information");
1082     }
1083     else if (ml_append(n, luaV_toline(L, 2), 0, FALSE) == FAIL)
1084     {
1085 	curbuf = buf;
1086 	luaL_error(L, "cannot insert line");
1087     }
1088     else
1089 	appended_lines_mark(n, 1L);
1090     curbuf = buf;
1091     update_screen(VALID);
1092     return 0;
1093 }
1094 
1095     static int
1096 luaV_buffer_next(lua_State *L)
1097 {
1098     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1099     buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
1100     luaV_pushbuffer(L, buf->b_next);
1101     return 1;
1102 }
1103 
1104     static int
1105 luaV_buffer_previous(lua_State *L)
1106 {
1107     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1108     buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
1109     luaV_pushbuffer(L, buf->b_prev);
1110     return 1;
1111 }
1112 
1113     static int
1114 luaV_buffer_isvalid(lua_State *L)
1115 {
1116     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1117     luaV_getudata(L, *b);
1118     lua_pushboolean(L, !lua_isnil(L, -1));
1119     return 1;
1120 }
1121 
1122 static const luaL_Reg luaV_Buffer_mt[] = {
1123     {"__tostring", luaV_buffer_tostring},
1124     {"__len", luaV_buffer_len},
1125     {"__call", luaV_buffer_call},
1126     {"__index", luaV_buffer_index},
1127     {"__newindex", luaV_buffer_newindex},
1128     {"insert", luaV_buffer_insert},
1129     {"next", luaV_buffer_next},
1130     {"previous", luaV_buffer_previous},
1131     {"isvalid", luaV_buffer_isvalid},
1132     {NULL, NULL}
1133 };
1134 
1135 
1136 /* =======   Window type   ======= */
1137 
1138 luaV_newtype(win_T, window, luaV_Window, LUAVIM_WINDOW)
1139 luaV_pushtype(win_T, window, luaV_Window)
1140 luaV_type_tostring(window, LUAVIM_WINDOW)
1141 
1142     static int
1143 luaV_window_call(lua_State *L)
1144 {
1145     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1146     lua_settop(L, 1);
1147     win_goto(w);
1148     return 1;
1149 }
1150 
1151     static int
1152 luaV_window_index(lua_State *L)
1153 {
1154     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1155     const char *s = luaL_checkstring(L, 2);
1156     if (strncmp(s, "buffer", 6) == 0)
1157 	luaV_pushbuffer(L, w->w_buffer);
1158     else if (strncmp(s, "line", 4) == 0)
1159 	lua_pushinteger(L, w->w_cursor.lnum);
1160     else if (strncmp(s, "col", 3) == 0)
1161 	lua_pushinteger(L, w->w_cursor.col + 1);
1162 #ifdef FEAT_VERTSPLIT
1163     else if (strncmp(s, "width", 5) == 0)
1164 	lua_pushinteger(L, W_WIDTH(w));
1165 #endif
1166     else if (strncmp(s, "height", 6) == 0)
1167 	lua_pushinteger(L, w->w_height);
1168     /* methods */
1169     else if (strncmp(s,   "next", 4) == 0
1170 	    || strncmp(s, "previous", 8) == 0
1171 	    || strncmp(s, "isvalid", 7) == 0)
1172     {
1173 	lua_getmetatable(L, 1);
1174 	lua_getfield(L, -1, s);
1175     }
1176     else
1177 	lua_pushnil(L);
1178     return 1;
1179 }
1180 
1181     static int
1182 luaV_window_newindex (lua_State *L)
1183 {
1184     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1185     const char *s = luaL_checkstring(L, 2);
1186     int v = luaL_checkinteger(L, 3);
1187     if (strncmp(s, "line", 4) == 0)
1188     {
1189 #ifdef HAVE_SANDBOX
1190 	luaV_checksandbox(L);
1191 #endif
1192 	if (v < 1 || v > w->w_buffer->b_ml.ml_line_count)
1193 	    luaL_error(L, "line out of range");
1194 	w->w_cursor.lnum = v;
1195 	update_screen(VALID);
1196     }
1197     else if (strncmp(s, "col", 3) == 0)
1198     {
1199 #ifdef HAVE_SANDBOX
1200 	luaV_checksandbox(L);
1201 #endif
1202 	w->w_cursor.col = v - 1;
1203 	update_screen(VALID);
1204     }
1205 #ifdef FEAT_VERTSPLIT
1206     else if (strncmp(s, "width", 5) == 0)
1207     {
1208 	win_T *win = curwin;
1209 #ifdef FEAT_GUI
1210 	need_mouse_correct = TRUE;
1211 #endif
1212 	curwin = w;
1213 	win_setwidth(v);
1214 	curwin = win;
1215     }
1216 #endif
1217     else if (strncmp(s, "height", 6) == 0)
1218     {
1219 	win_T *win = curwin;
1220 #ifdef FEAT_GUI
1221 	need_mouse_correct = TRUE;
1222 #endif
1223 	curwin = w;
1224 	win_setheight(v);
1225 	curwin = win;
1226     }
1227     else
1228 	luaL_error(L, "invalid window property: `%s'", s);
1229     return 0;
1230 }
1231 
1232     static int
1233 luaV_window_next(lua_State *L)
1234 {
1235     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1236     win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
1237     luaV_pushwindow(L, win->w_next);
1238     return 1;
1239 }
1240 
1241     static int
1242 luaV_window_previous(lua_State *L)
1243 {
1244     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1245     win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
1246     luaV_pushwindow(L, win->w_prev);
1247     return 1;
1248 }
1249 
1250     static int
1251 luaV_window_isvalid(lua_State *L)
1252 {
1253     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1254     luaV_getudata(L, *w);
1255     lua_pushboolean(L, !lua_isnil(L, -1));
1256     return 1;
1257 }
1258 
1259 static const luaL_Reg luaV_Window_mt[] = {
1260     {"__tostring", luaV_window_tostring},
1261     {"__call", luaV_window_call},
1262     {"__index", luaV_window_index},
1263     {"__newindex", luaV_window_newindex},
1264     {"next", luaV_window_next},
1265     {"previous", luaV_window_previous},
1266     {"isvalid", luaV_window_isvalid},
1267     {NULL, NULL}
1268 };
1269 
1270 
1271 /* =======   Vim module   ======= */
1272 
1273     static int
1274 luaV_print(lua_State *L)
1275 {
1276     int i, n = lua_gettop(L); /* nargs */
1277     const char *s;
1278     size_t l;
1279     luaL_Buffer b;
1280     luaL_buffinit(L, &b);
1281     lua_getglobal(L, "tostring");
1282     for (i = 1; i <= n; i++)
1283     {
1284 	lua_pushvalue(L, -1); /* tostring */
1285 	lua_pushvalue(L, i); /* arg */
1286 	lua_call(L, 1, 1);
1287 	s = lua_tolstring(L, -1, &l);
1288 	if (s == NULL)
1289 	    return luaL_error(L, "cannot convert to string");
1290 	if (i > 1) luaL_addchar(&b, ' '); /* use space instead of tab */
1291 	luaV_addlstring(&b, s, l, 0);
1292 	lua_pop(L, 1);
1293     }
1294     luaL_pushresult(&b);
1295     luaV_msg(L);
1296     return 0;
1297 }
1298 
1299     static int
1300 luaV_debug(lua_State *L)
1301 {
1302     lua_settop(L, 0);
1303     lua_getglobal(L, "vim");
1304     lua_getfield(L, -1, "eval");
1305     lua_remove(L, -2); /* vim.eval at position 1 */
1306     for (;;)
1307     {
1308 	const char *input;
1309 	size_t l;
1310 	lua_pushvalue(L, 1); /* vim.eval */
1311 	lua_pushliteral(L, "input('lua_debug> ')");
1312 	lua_call(L, 1, 1); /* return string */
1313 	input = lua_tolstring(L, -1, &l);
1314 	if (l == 0 || strcmp(input, "cont") == 0)
1315 	    return 0;
1316 	msg_putchar('\n'); /* avoid outputting on input line */
1317 	if (luaL_loadbuffer(L, input, l, "=(debug command)")
1318 		|| lua_pcall(L, 0, 0, 0))
1319 	    luaV_emsg(L);
1320 	lua_settop(L, 1); /* remove eventual returns, but keep vim.eval */
1321     }
1322 }
1323 
1324     static int
1325 luaV_command(lua_State *L)
1326 {
1327     do_cmdline_cmd((char_u *) luaL_checkstring(L, 1));
1328     update_screen(VALID);
1329     return 0;
1330 }
1331 
1332     static int
1333 luaV_eval(lua_State *L)
1334 {
1335     typval_T *tv = eval_expr((char_u *) luaL_checkstring(L, 1), NULL);
1336     if (tv == NULL) luaL_error(L, "invalid expression");
1337     luaV_pushtypval(L, tv);
1338     return 1;
1339 }
1340 
1341     static int
1342 luaV_beep(lua_State *L UNUSED)
1343 {
1344     vim_beep();
1345     return 0;
1346 }
1347 
1348     static int
1349 luaV_line(lua_State *L)
1350 {
1351     luaV_pushline(L, curbuf, curwin->w_cursor.lnum);
1352     return 1;
1353 }
1354 
1355     static int
1356 luaV_list(lua_State *L)
1357 {
1358     list_T *l = list_alloc();
1359     if (l == NULL)
1360 	lua_pushnil(L);
1361     else
1362 	luaV_newlist(L, l);
1363     return 1;
1364 }
1365 
1366     static int
1367 luaV_dict(lua_State *L)
1368 {
1369     dict_T *d = dict_alloc();
1370     if (d == NULL)
1371 	lua_pushnil(L);
1372     else
1373 	luaV_newdict(L, d);
1374     return 1;
1375 }
1376 
1377     static int
1378 luaV_buffer(lua_State *L)
1379 {
1380     buf_T *buf;
1381     if (lua_isstring(L, 1)) /* get by number or name? */
1382     {
1383 	if (lua_isnumber(L, 1)) /* by number? */
1384 	{
1385 	    int n = lua_tointeger(L, 1);
1386 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1387 		if (buf->b_fnum == n) break;
1388 	}
1389 	else { /* by name */
1390 	    size_t l;
1391 	    const char *s = lua_tolstring(L, 1, &l);
1392 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1393 	    {
1394 		if (buf->b_ffname == NULL || buf->b_sfname == NULL)
1395 		{
1396 		    if (l == 0) break;
1397 		}
1398 		else if (strncmp(s, (char *)buf->b_ffname, l) == 0
1399 			|| strncmp(s, (char *)buf->b_sfname, l) == 0)
1400 		    break;
1401 	    }
1402 	}
1403     }
1404     else
1405 	buf = (lua_toboolean(L, 1)) ? firstbuf : curbuf; /* first buffer? */
1406     luaV_pushbuffer(L, buf);
1407     return 1;
1408 }
1409 
1410     static int
1411 luaV_window(lua_State *L)
1412 {
1413     win_T *win;
1414     if (lua_isnumber(L, 1)) /* get by number? */
1415     {
1416 	int n = lua_tointeger(L, 1);
1417 	for (win = firstwin; win != NULL; win = win->w_next, n--)
1418 	    if (n == 1) break;
1419     }
1420     else
1421 	win = (lua_toboolean(L, 1)) ? firstwin : curwin; /* first window? */
1422     luaV_pushwindow(L, win);
1423     return 1;
1424 }
1425 
1426     static int
1427 luaV_open(lua_State *L)
1428 {
1429     char_u *s = NULL;
1430 #ifdef HAVE_SANDBOX
1431     luaV_checksandbox(L);
1432 #endif
1433     if (lua_isstring(L, 1)) s = (char_u *) lua_tostring(L, 1);
1434     luaV_pushbuffer(L, buflist_new(s, NULL, 1L, BLN_LISTED));
1435     return 1;
1436 }
1437 
1438     static int
1439 luaV_type(lua_State *L)
1440 {
1441     luaL_checkany(L, 1);
1442     if (lua_type(L, 1) == LUA_TUSERDATA) /* check vim udata? */
1443     {
1444 	lua_settop(L, 1);
1445 	if (lua_getmetatable(L, 1))
1446 	{
1447 	    luaV_getfield(L, LUAVIM_LIST);
1448 	    if (lua_rawequal(L, -1, 2))
1449 	    {
1450 		lua_pushstring(L, "list");
1451 		return 1;
1452 	    }
1453 	    luaV_getfield(L, LUAVIM_DICT);
1454 	    if (lua_rawequal(L, -1, 2))
1455 	    {
1456 		lua_pushstring(L, "dict");
1457 		return 1;
1458 	    }
1459 	    luaV_getfield(L, LUAVIM_BUFFER);
1460 	    if (lua_rawequal(L, -1, 2))
1461 	    {
1462 		lua_pushstring(L, "buffer");
1463 		return 1;
1464 	    }
1465 	    luaV_getfield(L, LUAVIM_WINDOW);
1466 	    if (lua_rawequal(L, -1, 2))
1467 	    {
1468 		lua_pushstring(L, "window");
1469 		return 1;
1470 	    }
1471 	}
1472     }
1473     lua_pushstring(L, luaL_typename(L, 1)); /* fallback */
1474     return 1;
1475 }
1476 
1477 static const luaL_Reg luaV_module[] = {
1478     {"command", luaV_command},
1479     {"eval", luaV_eval},
1480     {"beep", luaV_beep},
1481     {"line", luaV_line},
1482     {"list", luaV_list},
1483     {"dict", luaV_dict},
1484     {"buffer", luaV_buffer},
1485     {"window", luaV_window},
1486     {"open", luaV_open},
1487     {"type", luaV_type},
1488     {NULL, NULL}
1489 };
1490 
1491 /* for freeing list, dict, buffer and window objects; lightuserdata as arg */
1492     static int
1493 luaV_free(lua_State *L)
1494 {
1495     lua_pushnil(L);
1496     luaV_setudata(L, lua_touserdata(L, 1));
1497     return 0;
1498 }
1499 
1500     static int
1501 luaV_luaeval (lua_State *L)
1502 {
1503     luaL_Buffer b;
1504     size_t l;
1505     const char *str = lua_tolstring(L, 1, &l);
1506     typval_T *arg = (typval_T *) lua_touserdata(L, 2);
1507     typval_T *rettv = (typval_T *) lua_touserdata(L, 3);
1508     luaL_buffinit(L, &b);
1509     luaL_addlstring(&b, LUAVIM_EVALHEADER, sizeof(LUAVIM_EVALHEADER) - 1);
1510     luaL_addlstring(&b, str, l);
1511     luaL_pushresult(&b);
1512     str = lua_tolstring(L, -1, &l);
1513     if (luaL_loadbuffer(L, str, l, LUAVIM_EVALNAME)) /* compile error? */
1514     {
1515 	luaV_emsg(L);
1516 	return 0;
1517     }
1518     luaV_pushtypval(L, arg);
1519     if (lua_pcall(L, 1, 1, 0)) /* running error? */
1520     {
1521 	luaV_emsg(L);
1522 	return 0;
1523     }
1524     luaV_totypval(L, -1, rettv);
1525     return 0;
1526 }
1527 
1528     static int
1529 luaV_setref (lua_State *L)
1530 {
1531     int copyID = lua_tointeger(L, 1);
1532     typval_T tv;
1533     luaV_getfield(L, LUAVIM_LIST);
1534     luaV_getfield(L, LUAVIM_DICT);
1535     lua_pushnil(L);
1536     while (lua_next(L, lua_upvalueindex(1)) != 0) /* traverse cache table */
1537     {
1538 	lua_getmetatable(L, -1);
1539 	if (lua_rawequal(L, -1, 2)) /* list? */
1540 	{
1541 	    tv.v_type = VAR_LIST;
1542 	    tv.vval.v_list = (list_T *) lua_touserdata(L, 4); /* key */
1543 	}
1544 	else if (lua_rawequal(L, -1, 3)) /* dict? */
1545 	{
1546 	    tv.v_type = VAR_DICT;
1547 	    tv.vval.v_dict = (dict_T *) lua_touserdata(L, 4); /* key */
1548 	}
1549 	lua_pop(L, 2); /* metatable and value */
1550 	set_ref_in_item(&tv, copyID);
1551     }
1552     return 0;
1553 }
1554 
1555     static int
1556 luaopen_vim(lua_State *L)
1557 {
1558     /* set cache table */
1559     lua_newtable(L);
1560     lua_newtable(L);
1561     lua_pushstring(L, "v");
1562     lua_setfield(L, -2, "__mode");
1563     lua_setmetatable(L, -2); /* cache is weak-valued */
1564     /* print */
1565     lua_pushcfunction(L, luaV_print);
1566     lua_setglobal(L, "print");
1567     /* debug.debug */
1568     lua_getglobal(L, "debug");
1569     lua_pushcfunction(L, luaV_debug);
1570     lua_setfield(L, -2, "debug");
1571     lua_pop(L, 1);
1572     /* free */
1573     lua_pushlightuserdata(L, (void *) LUAVIM_FREE);
1574     lua_pushvalue(L, 1); /* cache table */
1575     lua_pushcclosure(L, luaV_free, 1);
1576     lua_rawset(L, LUA_REGISTRYINDEX);
1577     /* luaeval */
1578     lua_pushlightuserdata(L, (void *) LUAVIM_LUAEVAL);
1579     lua_pushvalue(L, 1); /* cache table */
1580     lua_pushcclosure(L, luaV_luaeval, 1);
1581     lua_rawset(L, LUA_REGISTRYINDEX);
1582     /* setref */
1583     lua_pushlightuserdata(L, (void *) LUAVIM_SETREF);
1584     lua_pushvalue(L, 1); /* cache table */
1585     lua_pushcclosure(L, luaV_setref, 1);
1586     lua_rawset(L, LUA_REGISTRYINDEX);
1587     /* register */
1588     luaV_newmetatable(L, LUAVIM_LIST);
1589     lua_pushvalue(L, 1);
1590     luaV_openlib(L, luaV_List_mt, 1);
1591     luaV_newmetatable(L, LUAVIM_DICT);
1592     lua_pushvalue(L, 1);
1593     luaV_openlib(L, luaV_Dict_mt, 1);
1594     luaV_newmetatable(L, LUAVIM_BUFFER);
1595     lua_pushvalue(L, 1); /* cache table */
1596     luaV_openlib(L, luaV_Buffer_mt, 1);
1597     luaV_newmetatable(L, LUAVIM_WINDOW);
1598     lua_pushvalue(L, 1); /* cache table */
1599     luaV_openlib(L, luaV_Window_mt, 1);
1600     lua_newtable(L); /* vim table */
1601     lua_pushvalue(L, 1); /* cache table */
1602     luaV_openlib(L, luaV_module, 1);
1603     lua_setglobal(L, LUAVIM_NAME);
1604     return 0;
1605 }
1606 
1607     static lua_State *
1608 luaV_newstate(void)
1609 {
1610     lua_State *L = luaL_newstate();
1611     luaL_openlibs(L); /* core libs */
1612     lua_pushcfunction(L, luaopen_vim); /* vim */
1613     lua_call(L, 0, 0);
1614     return L;
1615 }
1616 
1617     static void
1618 luaV_setrange(lua_State *L, int line1, int line2)
1619 {
1620     lua_getglobal(L, LUAVIM_NAME);
1621     lua_pushinteger(L, line1);
1622     lua_setfield(L, -2, "firstline");
1623     lua_pushinteger(L, line2);
1624     lua_setfield(L, -2, "lastline");
1625     lua_pop(L, 1); /* vim table */
1626 }
1627 
1628 
1629 /* =======   Interface   ======= */
1630 
1631 static lua_State *L = NULL;
1632 
1633     static int
1634 lua_isopen(void)
1635 {
1636     return L != NULL;
1637 }
1638 
1639     static int
1640 lua_init(void)
1641 {
1642     if (!lua_isopen())
1643     {
1644 #ifdef DYNAMIC_LUA
1645 	if (!lua_enabled(TRUE))
1646 	{
1647 	    EMSG(_("Lua library cannot be loaded."));
1648 	    return FAIL;
1649 	}
1650 #endif
1651 	L = luaV_newstate();
1652     }
1653     return OK;
1654 }
1655 
1656     void
1657 lua_end(void)
1658 {
1659     if (lua_isopen())
1660     {
1661 	lua_close(L);
1662 	L = NULL;
1663 #ifdef DYNAMIC_LUA
1664 	end_dynamic_lua();
1665 #endif
1666     }
1667 }
1668 
1669 /* ex commands */
1670     void
1671 ex_lua(exarg_T *eap)
1672 {
1673     char *script;
1674     if (lua_init() == FAIL) return;
1675     script = (char *) script_get(eap, eap->arg);
1676     if (!eap->skip)
1677     {
1678 	char *s = (script) ? script :  (char *) eap->arg;
1679 	luaV_setrange(L, eap->line1, eap->line2);
1680 	if (luaL_loadbuffer(L, s, strlen(s), LUAVIM_CHUNKNAME)
1681 		|| lua_pcall(L, 0, 0, 0))
1682 	    luaV_emsg(L);
1683     }
1684     if (script != NULL) vim_free(script);
1685 }
1686 
1687     void
1688 ex_luado(exarg_T *eap)
1689 {
1690     linenr_T l;
1691     const char *s = (const char *) eap->arg;
1692     luaL_Buffer b;
1693     size_t len;
1694     if (lua_init() == FAIL) return;
1695     if (u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
1696     {
1697 	EMSG(_("cannot save undo information"));
1698 	return;
1699     }
1700     luaV_setrange(L, eap->line1, eap->line2);
1701     luaL_buffinit(L, &b);
1702     luaL_addlstring(&b, "return function(line, linenr) ", 30); /* header */
1703     luaL_addlstring(&b, s, strlen(s));
1704     luaL_addlstring(&b, " end", 4); /* footer */
1705     luaL_pushresult(&b);
1706     s = lua_tolstring(L, -1, &len);
1707     if (luaL_loadbuffer(L, s, len, LUAVIM_CHUNKNAME))
1708     {
1709 	luaV_emsg(L);
1710 	lua_pop(L, 1); /* function body */
1711 	return;
1712     }
1713     lua_call(L, 0, 1);
1714     lua_replace(L, -2); /* function -> body */
1715     for (l = eap->line1; l <= eap->line2; l++)
1716     {
1717 	lua_pushvalue(L, -1); /* function */
1718 	luaV_pushline(L, curbuf, l); /* current line as arg */
1719 	lua_pushinteger(L, l); /* current line number as arg */
1720 	if (lua_pcall(L, 2, 1, 0))
1721 	{
1722 	    luaV_emsg(L);
1723 	    break;
1724 	}
1725 	if (lua_isstring(L, -1)) /* update line? */
1726 	{
1727 #ifdef HAVE_SANDBOX
1728 	    luaV_checksandbox(L);
1729 #endif
1730 	    ml_replace(l, luaV_toline(L, -1), TRUE);
1731 	    changed_bytes(l, 0);
1732 	    lua_pop(L, 1); /* result from luaV_toline */
1733 	}
1734 	lua_pop(L, 1); /* line */
1735     }
1736     lua_pop(L, 1); /* function */
1737     check_cursor();
1738     update_screen(NOT_VALID);
1739 }
1740 
1741     void
1742 ex_luafile(exarg_T *eap)
1743 {
1744     if (lua_init() == FAIL)
1745 	return;
1746     if (!eap->skip)
1747     {
1748 	luaV_setrange(L, eap->line1, eap->line2);
1749 	if (luaL_loadfile(L, (char *) eap->arg) || lua_pcall(L, 0, 0, 0))
1750 	    luaV_emsg(L);
1751     }
1752 }
1753 
1754 #define luaV_freetype(typ,tname) \
1755 	void \
1756     lua_##tname##_free(typ *o) \
1757     { \
1758 	if (!lua_isopen()) return; \
1759 	luaV_getfield(L, LUAVIM_FREE); \
1760 	lua_pushlightuserdata(L, (void *) o); \
1761 	lua_call(L, 1, 0); \
1762     }
1763 
1764 luaV_freetype(buf_T, buffer)
1765 luaV_freetype(win_T, window)
1766 
1767     void
1768 do_luaeval (char_u *str, typval_T *arg, typval_T *rettv)
1769 {
1770     lua_init();
1771     luaV_getfield(L, LUAVIM_LUAEVAL);
1772     lua_pushstring(L, (char *) str);
1773     lua_pushlightuserdata(L, (void *) arg);
1774     lua_pushlightuserdata(L, (void *) rettv);
1775     lua_call(L, 3, 0);
1776 }
1777 
1778     void
1779 set_ref_in_lua (int copyID)
1780 {
1781     if (!lua_isopen()) return;
1782     luaV_getfield(L, LUAVIM_SETREF);
1783     lua_pushinteger(L, copyID);
1784     lua_call(L, 1, 0);
1785 }
1786 
1787 #endif
1788