xref: /vim-8.2.3635/src/if_lua.c (revision 6c35beaa)
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, (char *) tv->vval.v_string);
468 	    break;
469 	case VAR_NUMBER:
470 	    lua_pushinteger(L, (int) tv->vval.v_number);
471 	    break;
472 #ifdef FEAT_FLOAT
473 	case VAR_FLOAT:
474 	    lua_pushnumber(L, (lua_Number) tv->vval.v_float);
475 	    break;
476 #endif
477 	case VAR_LIST:
478 	    luaV_pushlist(L, tv->vval.v_list);
479 	    break;
480 	case VAR_DICT:
481 	    luaV_pushdict(L, tv->vval.v_dict);
482 	    break;
483 	default:
484 	    lua_pushnil(L);
485     }
486 }
487 
488 /* converts lua value at 'pos' to typval 'tv' */
489     static void
490 luaV_totypval (lua_State *L, int pos, typval_T *tv)
491 {
492     switch(lua_type(L, pos)) {
493 	case LUA_TBOOLEAN:
494 	    tv->v_type = VAR_NUMBER;
495 	    tv->vval.v_number = (varnumber_T) lua_toboolean(L, pos);
496 	    break;
497 	case LUA_TSTRING:
498 	    tv->v_type = VAR_STRING;
499 	    tv->vval.v_string = vim_strsave((char_u *) lua_tostring(L, pos));
500 	    break;
501 	case LUA_TNUMBER:
502 #ifdef FEAT_FLOAT
503 	    tv->v_type = VAR_FLOAT;
504 	    tv->vval.v_float = (float_T) lua_tonumber(L, pos);
505 #else
506 	    tv->v_type = VAR_NUMBER;
507 	    tv->vval.v_number = (varnumber_T) lua_tointeger(L, pos);
508 #endif
509 	    break;
510 	case LUA_TUSERDATA: {
511 	    void *p = lua_touserdata(L, pos);
512 	    if (lua_getmetatable(L, pos)) /* has metatable? */
513 	    {
514 		/* check list */
515 		luaV_getfield(L, LUAVIM_LIST);
516 		if (lua_rawequal(L, -1, -2))
517 		{
518 		    tv->v_type = VAR_LIST;
519 		    tv->vval.v_list = *((luaV_List *) p);
520 		    ++tv->vval.v_list->lv_refcount;
521 		    lua_pop(L, 2); /* MTs */
522 		    return;
523 		}
524 		/* check dict */
525 		luaV_getfield(L, LUAVIM_DICT);
526 		if (lua_rawequal(L, -1, -3))
527 		{
528 		    tv->v_type = VAR_DICT;
529 		    tv->vval.v_dict = *((luaV_Dict *) p);
530 		    ++tv->vval.v_dict->dv_refcount;
531 		    lua_pop(L, 3); /* MTs */
532 		    return;
533 		}
534 		lua_pop(L, 3); /* MTs */
535 	    }
536 	    break;
537 	}
538 	default:
539 	    tv->v_type = VAR_NUMBER;
540 	    tv->vval.v_number = 0;
541     }
542 }
543 
544 /* similar to luaL_addlstring, but replaces \0 with \n if toline and
545  * \n with \0 otherwise */
546     static void
547 luaV_addlstring(luaL_Buffer *b, const char *s, size_t l, int toline)
548 {
549     while (l--)
550     {
551 	if (*s == '\0' && toline)
552 	    luaL_addchar(b, '\n');
553 	else if (*s == '\n' && !toline)
554 	    luaL_addchar(b, '\0');
555 	else
556 	    luaL_addchar(b, *s);
557 	s++;
558     }
559 }
560 
561     static void
562 luaV_pushline(lua_State *L, buf_T *buf, linenr_T n)
563 {
564     const char *s = (const char *) ml_get_buf(buf, n, FALSE);
565     luaL_Buffer b;
566     luaL_buffinit(L, &b);
567     luaV_addlstring(&b, s, strlen(s), 0);
568     luaL_pushresult(&b);
569 }
570 
571     static char_u *
572 luaV_toline(lua_State *L, int pos)
573 {
574     size_t l;
575     const char *s = lua_tolstring(L, pos, &l);
576 
577     luaL_Buffer b;
578     luaL_buffinit(L, &b);
579     luaV_addlstring(&b, s, l, 1);
580     luaL_pushresult(&b);
581     return (char_u *) lua_tostring(L, -1);
582 }
583 
584 /* pops a string s from the top of the stack and calls mf(t) for pieces t of
585  * s separated by newlines */
586     static void
587 luaV_msgfunc(lua_State *L, msgfunc_T mf)
588 {
589     luaL_Buffer b;
590     size_t l;
591     const char *p, *s = lua_tolstring(L, -1, &l);
592     luaL_buffinit(L, &b);
593     luaV_addlstring(&b, s, l, 0);
594     luaL_pushresult(&b);
595     /* break string */
596     p = s = lua_tolstring(L, -1, &l);
597     while (l--)
598     {
599 	if (*p++ == '\0') /* break? */
600 	{
601 	    mf((char_u *) s);
602 	    s = p;
603 	}
604     }
605     mf((char_u *) s);
606     lua_pop(L, 2); /* original and modified strings */
607 }
608 
609 #define luaV_newtype(typ,tname,luatyp,luatname) \
610 	static luatyp * \
611     luaV_new##tname (lua_State *L, typ *obj) \
612     { \
613 	luatyp *o = (luatyp *) lua_newuserdata(L, sizeof(luatyp)); \
614 	*o = obj; \
615 	luaV_setudata(L, obj); /* cache[obj] = udata */ \
616 	luaV_getfield(L, luatname); \
617 	lua_setmetatable(L, -2); \
618 	return o; \
619     }
620 
621 #define luaV_pushtype(typ,tname,luatyp) \
622 	static luatyp * \
623     luaV_push##tname (lua_State *L, typ *obj) \
624     { \
625 	luatyp *o = NULL; \
626 	if (obj == NULL) \
627 	    lua_pushnil(L); \
628 	else { \
629 	    luaV_getudata(L, obj); \
630 	    if (lua_isnil(L, -1)) /* not interned? */ \
631 	    { \
632 		lua_pop(L, 1); \
633 		o = luaV_new##tname(L, obj); \
634 	    } \
635 	    else \
636 		o = (luatyp *) lua_touserdata(L, -1); \
637 	} \
638 	return o; \
639     }
640 
641 #define luaV_type_tostring(tname,luatname) \
642 	static int \
643     luaV_##tname##_tostring (lua_State *L) \
644     { \
645 	lua_pushfstring(L, "%s: %p", luatname, lua_touserdata(L, 1)); \
646 	return 1; \
647     }
648 
649 /* =======   List type   ======= */
650 
651     static luaV_List *
652 luaV_newlist (lua_State *L, list_T *lis)
653 {
654     luaV_List *l = (luaV_List *) lua_newuserdata(L, sizeof(luaV_List));
655     *l = lis;
656     lis->lv_refcount++; /* reference in Lua */
657     luaV_setudata(L, lis); /* cache[lis] = udata */
658     luaV_getfield(L, LUAVIM_LIST);
659     lua_setmetatable(L, -2);
660     return l;
661 }
662 
663 luaV_pushtype(list_T, list, luaV_List)
664 luaV_type_tostring(list, LUAVIM_LIST)
665 
666     static int
667 luaV_list_gc (lua_State *L)
668 {
669     list_unref(luaV_unbox(L, luaV_List, 1));
670     return 0;
671 }
672 
673     static int
674 luaV_list_len (lua_State *L)
675 {
676     list_T *l = luaV_unbox(L, luaV_List, 1);
677     lua_pushinteger(L, (l == NULL) ? 0 : (int) l->lv_len);
678     return 1;
679 }
680 
681     static int
682 luaV_list_iter (lua_State *L)
683 {
684     listitem_T *li = (listitem_T *) lua_touserdata(L, lua_upvalueindex(2));
685     if (li == NULL) return 0;
686     luaV_pushtypval(L, &li->li_tv);
687     lua_pushlightuserdata(L, (void *) li->li_next);
688     lua_replace(L, lua_upvalueindex(2));
689     return 1;
690 }
691 
692     static int
693 luaV_list_call (lua_State *L)
694 {
695     list_T *l = luaV_unbox(L, luaV_List, 1);
696     lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
697     lua_pushlightuserdata(L, (void *) l->lv_first);
698     lua_pushcclosure(L, luaV_list_iter, 2);
699     return 1;
700 }
701 
702     static int
703 luaV_list_index (lua_State *L)
704 {
705     list_T *l = luaV_unbox(L, luaV_List, 1);
706     if (lua_isnumber(L, 2)) /* list item? */
707     {
708 	listitem_T *li = list_find(l, (long) luaL_checkinteger(L, 2));
709 	if (li == NULL)
710 	    lua_pushnil(L);
711 	else
712 	    luaV_pushtypval(L, &li->li_tv);
713     }
714     else if (lua_isstring(L, 2)) /* method? */
715     {
716 	const char *s = lua_tostring(L, 2);
717 	if (strncmp(s, "add", 3) == 0
718 		|| strncmp(s, "insert", 6) == 0
719 		|| strncmp(s, "extend", 6) == 0)
720 	{
721 	    lua_getmetatable(L, 1);
722 	    lua_getfield(L, -1, s);
723 	}
724 	else
725 	    lua_pushnil(L);
726     }
727     else
728 	lua_pushnil(L);
729     return 1;
730 }
731 
732     static int
733 luaV_list_newindex (lua_State *L)
734 {
735     list_T *l = luaV_unbox(L, luaV_List, 1);
736     long n = (long) luaL_checkinteger(L, 2);
737     listitem_T *li;
738     if (l->lv_lock)
739 	luaL_error(L, "list is locked");
740     li = list_find(l, n);
741     if (li == NULL) return 0;
742     if (lua_isnil(L, 3)) /* remove? */
743     {
744 	list_remove(l, li, li);
745 	clear_tv(&li->li_tv);
746 	vim_free(li);
747     }
748     else
749     {
750 	typval_T v;
751 	luaV_totypval(L, 3, &v);
752 	clear_tv(&li->li_tv);
753 	copy_tv(&v, &li->li_tv);
754     }
755     return 0;
756 }
757 
758     static int
759 luaV_list_add (lua_State *L)
760 {
761     luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
762     list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
763     listitem_T *li;
764     if (l->lv_lock)
765 	luaL_error(L, "list is locked");
766     li = listitem_alloc();
767     if (li != NULL)
768     {
769 	typval_T v;
770 	lua_settop(L, 2);
771 	luaV_totypval(L, 2, &v);
772 	list_append_tv(l, &v);
773     }
774     lua_settop(L, 1);
775     return 1;
776 }
777 
778     static int
779 luaV_list_insert (lua_State *L)
780 {
781     luaV_List *lis = luaV_checkudata(L, 1, LUAVIM_LIST);
782     list_T *l = (list_T *) luaV_checkcache(L, (void *) *lis);
783     long pos = luaL_optlong(L, 3, 0);
784     listitem_T *li = NULL;
785     typval_T v;
786     if (l->lv_lock)
787 	luaL_error(L, "list is locked");
788     if (pos < l->lv_len)
789     {
790 	li = list_find(l, pos);
791 	if (li == NULL)
792 	    luaL_error(L, "invalid position");
793     }
794     lua_settop(L, 2);
795     luaV_totypval(L, 2, &v);
796     list_insert_tv(l, &v, li);
797     lua_settop(L, 1);
798     return 1;
799 }
800 
801 static const luaL_Reg luaV_List_mt[] = {
802     {"__tostring", luaV_list_tostring},
803     {"__gc", luaV_list_gc},
804     {"__len", luaV_list_len},
805     {"__call", luaV_list_call},
806     {"__index", luaV_list_index},
807     {"__newindex", luaV_list_newindex},
808     {"add", luaV_list_add},
809     {"insert", luaV_list_insert},
810     {NULL, NULL}
811 };
812 
813 
814 /* =======   Dict type   ======= */
815 
816     static luaV_Dict *
817 luaV_newdict (lua_State *L, dict_T *dic)
818 {
819     luaV_Dict *d = (luaV_Dict *) lua_newuserdata(L, sizeof(luaV_Dict));
820     *d = dic;
821     dic->dv_refcount++; /* reference in Lua */
822     luaV_setudata(L, dic); /* cache[dic] = udata */
823     luaV_getfield(L, LUAVIM_DICT);
824     lua_setmetatable(L, -2);
825     return d;
826 }
827 
828 luaV_pushtype(dict_T, dict, luaV_Dict)
829 luaV_type_tostring(dict, LUAVIM_DICT)
830 
831     static int
832 luaV_dict_gc (lua_State *L)
833 {
834     dict_unref(luaV_unbox(L, luaV_Dict, 1));
835     return 0;
836 }
837 
838     static int
839 luaV_dict_len (lua_State *L)
840 {
841     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
842     lua_pushinteger(L, (d == NULL) ? 0 : (int) d->dv_hashtab.ht_used);
843     return 1;
844 }
845 
846     static int
847 luaV_dict_iter (lua_State *L)
848 {
849     hashitem_T *hi = (hashitem_T *) lua_touserdata(L, lua_upvalueindex(2));
850     int n = lua_tointeger(L, lua_upvalueindex(3));
851     dictitem_T *di;
852     if (n <= 0) return 0;
853     while (HASHITEM_EMPTY(hi)) hi++;
854     di = dict_lookup(hi);
855     lua_pushstring(L, (char *) hi->hi_key);
856     luaV_pushtypval(L, &di->di_tv);
857     lua_pushlightuserdata(L, (void *) (hi + 1));
858     lua_replace(L, lua_upvalueindex(2));
859     lua_pushinteger(L, n - 1);
860     lua_replace(L, lua_upvalueindex(3));
861     return 2;
862 }
863 
864     static int
865 luaV_dict_call (lua_State *L)
866 {
867     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
868     hashtab_T *ht = &d->dv_hashtab;
869     lua_pushvalue(L, lua_upvalueindex(1)); /* pass cache table along */
870     lua_pushlightuserdata(L, (void *) ht->ht_array);
871     lua_pushinteger(L, ht->ht_used); /* # remaining items */
872     lua_pushcclosure(L, luaV_dict_iter, 3);
873     return 1;
874 }
875 
876     static int
877 luaV_dict_index (lua_State *L)
878 {
879     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
880     char_u *key = (char_u *) luaL_checkstring(L, 2);
881     dictitem_T *di = dict_find(d, key, -1);
882     if (di == NULL)
883 	lua_pushnil(L);
884     else
885 	luaV_pushtypval(L, &di->di_tv);
886     return 1;
887 }
888 
889     static int
890 luaV_dict_newindex (lua_State *L)
891 {
892     dict_T *d = luaV_unbox(L, luaV_Dict, 1);
893     char_u *key = (char_u *) luaL_checkstring(L, 2);
894     dictitem_T *di;
895     if (d->dv_lock)
896 	luaL_error(L, "dict is locked");
897     di = dict_find(d, key, -1);
898     if (di == NULL) /* non-existing key? */
899     {
900 	if (lua_isnil(L, 3)) return 0;
901 	di = dictitem_alloc(key);
902 	if (di == NULL) return 0;
903 	if (dict_add(d, di) == FAIL)
904 	{
905 		vim_free(di);
906 		return 0;
907 	}
908     }
909     else
910 	clear_tv(&di->di_tv);
911     if (lua_isnil(L, 3)) /* remove? */
912     {
913 	hashitem_T *hi = hash_find(&d->dv_hashtab, di->di_key);
914 	hash_remove(&d->dv_hashtab, hi);
915 	dictitem_free(di);
916     }
917     else {
918 	typval_T v;
919 	luaV_totypval(L, 3, &v);
920 	copy_tv(&v, &di->di_tv);
921     }
922     return 0;
923 }
924 
925 static const luaL_Reg luaV_Dict_mt[] = {
926     {"__tostring", luaV_dict_tostring},
927     {"__gc", luaV_dict_gc},
928     {"__len", luaV_dict_len},
929     {"__call", luaV_dict_call},
930     {"__index", luaV_dict_index},
931     {"__newindex", luaV_dict_newindex},
932     {NULL, NULL}
933 };
934 
935 
936 /* =======   Buffer type   ======= */
937 
938 luaV_newtype(buf_T, buffer, luaV_Buffer, LUAVIM_BUFFER)
939 luaV_pushtype(buf_T, buffer, luaV_Buffer)
940 luaV_type_tostring(buffer, LUAVIM_BUFFER)
941 
942     static int
943 luaV_buffer_len(lua_State *L)
944 {
945     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
946     lua_pushinteger(L, b->b_ml.ml_line_count);
947     return 1;
948 }
949 
950     static int
951 luaV_buffer_call(lua_State *L)
952 {
953     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
954     lua_settop(L, 1);
955     set_curbuf(b, DOBUF_SPLIT);
956     return 1;
957 }
958 
959     static int
960 luaV_buffer_index(lua_State *L)
961 {
962     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
963     linenr_T n = (linenr_T) lua_tointeger(L, 2);
964     if (n > 0 && n <= b->b_ml.ml_line_count)
965 	luaV_pushline(L, b, n);
966     else if (lua_isstring(L, 2))
967     {
968 	const char *s = lua_tostring(L, 2);
969 	if (strncmp(s, "name", 4) == 0)
970 	    lua_pushstring(L, (char *) b->b_sfname);
971 	else if (strncmp(s, "fname", 5) == 0)
972 	    lua_pushstring(L, (char *) b->b_ffname);
973 	else if (strncmp(s, "number", 6) == 0)
974 	    lua_pushinteger(L, b->b_fnum);
975 	/* methods */
976 	else if (strncmp(s,   "insert", 6) == 0
977 		|| strncmp(s, "next", 4) == 0
978 		|| strncmp(s, "previous", 8) == 0
979 		|| strncmp(s, "isvalid", 7) == 0)
980 	{
981 	    lua_getmetatable(L, 1);
982 	    lua_getfield(L, -1, s);
983 	}
984 	else
985 	    lua_pushnil(L);
986     }
987     else
988 	lua_pushnil(L);
989     return 1;
990 }
991 
992     static int
993 luaV_buffer_newindex(lua_State *L)
994 {
995     buf_T *b = (buf_T *) luaV_checkvalid(L, luaV_Buffer, 1);
996     linenr_T n = (linenr_T) luaL_checkinteger(L, 2);
997 #ifdef HAVE_SANDBOX
998     luaV_checksandbox(L);
999 #endif
1000     if (n < 1 || n > b->b_ml.ml_line_count)
1001 	luaL_error(L, "invalid line number");
1002     if (lua_isnil(L, 3)) /* delete line */
1003     {
1004 	buf_T *buf = curbuf;
1005 	curbuf = b;
1006 	if (u_savedel(n, 1L) == FAIL)
1007 	{
1008 	    curbuf = buf;
1009 	    luaL_error(L, "cannot save undo information");
1010 	}
1011 	else if (ml_delete(n, FALSE) == FAIL)
1012 	{
1013 	    curbuf = buf;
1014 	    luaL_error(L, "cannot delete line");
1015 	}
1016 	else {
1017 	    deleted_lines_mark(n, 1L);
1018 	    if (b == curwin->w_buffer) /* fix cursor in current window? */
1019 	    {
1020 		if (curwin->w_cursor.lnum >= n)
1021 		{
1022 		    if (curwin->w_cursor.lnum > n)
1023 		    {
1024 			curwin->w_cursor.lnum -= 1;
1025 			check_cursor_col();
1026 		    }
1027 		    else check_cursor();
1028 		    changed_cline_bef_curs();
1029 		}
1030 		invalidate_botline();
1031 	    }
1032 	}
1033 	curbuf = buf;
1034     }
1035     else if (lua_isstring(L, 3)) /* update line */
1036     {
1037 	buf_T *buf = curbuf;
1038 	curbuf = b;
1039 	if (u_savesub(n) == FAIL)
1040 	{
1041 	    curbuf = buf;
1042 	    luaL_error(L, "cannot save undo information");
1043 	}
1044 	else if (ml_replace(n, luaV_toline(L, 3), TRUE) == FAIL)
1045 	{
1046 	    curbuf = buf;
1047 	    luaL_error(L, "cannot replace line");
1048 	}
1049 	else changed_bytes(n, 0);
1050 	curbuf = buf;
1051 	if (b == curwin->w_buffer)
1052 	    check_cursor_col();
1053     }
1054     else
1055 	luaL_error(L, "wrong argument to change line");
1056     return 0;
1057 }
1058 
1059     static int
1060 luaV_buffer_insert(lua_State *L)
1061 {
1062     luaV_Buffer *lb = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1063     buf_T *b = (buf_T *) luaV_checkcache(L, (void *) *lb);
1064     linenr_T last = b->b_ml.ml_line_count;
1065     linenr_T n = (linenr_T) luaL_optinteger(L, 3, last);
1066     buf_T *buf;
1067     luaL_checktype(L, 2, LUA_TSTRING);
1068 #ifdef HAVE_SANDBOX
1069     luaV_checksandbox(L);
1070 #endif
1071     /* fix insertion line */
1072     if (n < 0) n = 0;
1073     if (n > last) n = last;
1074     /* insert */
1075     buf = curbuf;
1076     curbuf = b;
1077     if (u_save(n, n + 1) == FAIL)
1078     {
1079 	curbuf = buf;
1080 	luaL_error(L, "cannot save undo information");
1081     }
1082     else if (ml_append(n, luaV_toline(L, 2), 0, FALSE) == FAIL)
1083     {
1084 	curbuf = buf;
1085 	luaL_error(L, "cannot insert line");
1086     }
1087     else
1088 	appended_lines_mark(n, 1L);
1089     curbuf = buf;
1090     update_screen(VALID);
1091     return 0;
1092 }
1093 
1094     static int
1095 luaV_buffer_next(lua_State *L)
1096 {
1097     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1098     buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
1099     luaV_pushbuffer(L, buf->b_next);
1100     return 1;
1101 }
1102 
1103     static int
1104 luaV_buffer_previous(lua_State *L)
1105 {
1106     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1107     buf_T *buf = (buf_T *) luaV_checkcache(L, (void *) *b);
1108     luaV_pushbuffer(L, buf->b_prev);
1109     return 1;
1110 }
1111 
1112     static int
1113 luaV_buffer_isvalid(lua_State *L)
1114 {
1115     luaV_Buffer *b = luaV_checkudata(L, 1, LUAVIM_BUFFER);
1116     luaV_getudata(L, *b);
1117     lua_pushboolean(L, !lua_isnil(L, -1));
1118     return 1;
1119 }
1120 
1121 static const luaL_Reg luaV_Buffer_mt[] = {
1122     {"__tostring", luaV_buffer_tostring},
1123     {"__len", luaV_buffer_len},
1124     {"__call", luaV_buffer_call},
1125     {"__index", luaV_buffer_index},
1126     {"__newindex", luaV_buffer_newindex},
1127     {"insert", luaV_buffer_insert},
1128     {"next", luaV_buffer_next},
1129     {"previous", luaV_buffer_previous},
1130     {"isvalid", luaV_buffer_isvalid},
1131     {NULL, NULL}
1132 };
1133 
1134 
1135 /* =======   Window type   ======= */
1136 
1137 luaV_newtype(win_T, window, luaV_Window, LUAVIM_WINDOW)
1138 luaV_pushtype(win_T, window, luaV_Window)
1139 luaV_type_tostring(window, LUAVIM_WINDOW)
1140 
1141     static int
1142 luaV_window_call(lua_State *L)
1143 {
1144     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1145     lua_settop(L, 1);
1146     win_goto(w);
1147     return 1;
1148 }
1149 
1150     static int
1151 luaV_window_index(lua_State *L)
1152 {
1153     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1154     const char *s = luaL_checkstring(L, 2);
1155     if (strncmp(s, "buffer", 6) == 0)
1156 	luaV_pushbuffer(L, w->w_buffer);
1157     else if (strncmp(s, "line", 4) == 0)
1158 	lua_pushinteger(L, w->w_cursor.lnum);
1159     else if (strncmp(s, "col", 3) == 0)
1160 	lua_pushinteger(L, w->w_cursor.col + 1);
1161 #ifdef FEAT_VERTSPLIT
1162     else if (strncmp(s, "width", 5) == 0)
1163 	lua_pushinteger(L, W_WIDTH(w));
1164 #endif
1165     else if (strncmp(s, "height", 6) == 0)
1166 	lua_pushinteger(L, w->w_height);
1167     /* methods */
1168     else if (strncmp(s,   "next", 4) == 0
1169 	    || strncmp(s, "previous", 8) == 0
1170 	    || strncmp(s, "isvalid", 7) == 0)
1171     {
1172 	lua_getmetatable(L, 1);
1173 	lua_getfield(L, -1, s);
1174     }
1175     else
1176 	lua_pushnil(L);
1177     return 1;
1178 }
1179 
1180     static int
1181 luaV_window_newindex (lua_State *L)
1182 {
1183     win_T *w = (win_T *) luaV_checkvalid(L, luaV_Window, 1);
1184     const char *s = luaL_checkstring(L, 2);
1185     int v = luaL_checkinteger(L, 3);
1186     if (strncmp(s, "line", 4) == 0)
1187     {
1188 #ifdef HAVE_SANDBOX
1189 	luaV_checksandbox(L);
1190 #endif
1191 	if (v < 1 || v > w->w_buffer->b_ml.ml_line_count)
1192 	    luaL_error(L, "line out of range");
1193 	w->w_cursor.lnum = v;
1194 	update_screen(VALID);
1195     }
1196     else if (strncmp(s, "col", 3) == 0)
1197     {
1198 #ifdef HAVE_SANDBOX
1199 	luaV_checksandbox(L);
1200 #endif
1201 	w->w_cursor.col = v - 1;
1202 	update_screen(VALID);
1203     }
1204 #ifdef FEAT_VERTSPLIT
1205     else if (strncmp(s, "width", 5) == 0)
1206     {
1207 	win_T *win = curwin;
1208 #ifdef FEAT_GUI
1209 	need_mouse_correct = TRUE;
1210 #endif
1211 	curwin = w;
1212 	win_setwidth(v);
1213 	curwin = win;
1214     }
1215 #endif
1216     else if (strncmp(s, "height", 6) == 0)
1217     {
1218 	win_T *win = curwin;
1219 #ifdef FEAT_GUI
1220 	need_mouse_correct = TRUE;
1221 #endif
1222 	curwin = w;
1223 	win_setheight(v);
1224 	curwin = win;
1225     }
1226     else
1227 	luaL_error(L, "invalid window property: `%s'", s);
1228     return 0;
1229 }
1230 
1231     static int
1232 luaV_window_next(lua_State *L)
1233 {
1234     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1235     win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
1236     luaV_pushwindow(L, win->w_next);
1237     return 1;
1238 }
1239 
1240     static int
1241 luaV_window_previous(lua_State *L)
1242 {
1243     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1244     win_T *win = (win_T *) luaV_checkcache(L, (void *) *w);
1245     luaV_pushwindow(L, win->w_prev);
1246     return 1;
1247 }
1248 
1249     static int
1250 luaV_window_isvalid(lua_State *L)
1251 {
1252     luaV_Window *w = luaV_checkudata(L, 1, LUAVIM_WINDOW);
1253     luaV_getudata(L, *w);
1254     lua_pushboolean(L, !lua_isnil(L, -1));
1255     return 1;
1256 }
1257 
1258 static const luaL_Reg luaV_Window_mt[] = {
1259     {"__tostring", luaV_window_tostring},
1260     {"__call", luaV_window_call},
1261     {"__index", luaV_window_index},
1262     {"__newindex", luaV_window_newindex},
1263     {"next", luaV_window_next},
1264     {"previous", luaV_window_previous},
1265     {"isvalid", luaV_window_isvalid},
1266     {NULL, NULL}
1267 };
1268 
1269 
1270 /* =======   Vim module   ======= */
1271 
1272     static int
1273 luaV_print(lua_State *L)
1274 {
1275     int i, n = lua_gettop(L); /* nargs */
1276     const char *s;
1277     size_t l;
1278     luaL_Buffer b;
1279     luaL_buffinit(L, &b);
1280     lua_getglobal(L, "tostring");
1281     for (i = 1; i <= n; i++)
1282     {
1283 	lua_pushvalue(L, -1); /* tostring */
1284 	lua_pushvalue(L, i); /* arg */
1285 	lua_call(L, 1, 1);
1286 	s = lua_tolstring(L, -1, &l);
1287 	if (s == NULL)
1288 	    return luaL_error(L, "cannot convert to string");
1289 	if (i > 1) luaL_addchar(&b, ' '); /* use space instead of tab */
1290 	luaV_addlstring(&b, s, l, 0);
1291 	lua_pop(L, 1);
1292     }
1293     luaL_pushresult(&b);
1294     luaV_msg(L);
1295     return 0;
1296 }
1297 
1298     static int
1299 luaV_debug(lua_State *L)
1300 {
1301     lua_settop(L, 0);
1302     lua_getglobal(L, "vim");
1303     lua_getfield(L, -1, "eval");
1304     lua_remove(L, -2); /* vim.eval at position 1 */
1305     for (;;)
1306     {
1307 	const char *input;
1308 	size_t l;
1309 	lua_pushvalue(L, 1); /* vim.eval */
1310 	lua_pushliteral(L, "input('lua_debug> ')");
1311 	lua_call(L, 1, 1); /* return string */
1312 	input = lua_tolstring(L, -1, &l);
1313 	if (l == 0 || strcmp(input, "cont") == 0)
1314 	    return 0;
1315 	msg_putchar('\n'); /* avoid outputting on input line */
1316 	if (luaL_loadbuffer(L, input, l, "=(debug command)")
1317 		|| lua_pcall(L, 0, 0, 0))
1318 	    luaV_emsg(L);
1319 	lua_settop(L, 1); /* remove eventual returns, but keep vim.eval */
1320     }
1321 }
1322 
1323     static int
1324 luaV_command(lua_State *L)
1325 {
1326     do_cmdline_cmd((char_u *) luaL_checkstring(L, 1));
1327     update_screen(VALID);
1328     return 0;
1329 }
1330 
1331     static int
1332 luaV_eval(lua_State *L)
1333 {
1334     typval_T *tv = eval_expr((char_u *) luaL_checkstring(L, 1), NULL);
1335     if (tv == NULL) luaL_error(L, "invalid expression");
1336     luaV_pushtypval(L, tv);
1337     return 1;
1338 }
1339 
1340     static int
1341 luaV_beep(lua_State *L UNUSED)
1342 {
1343     vim_beep();
1344     return 0;
1345 }
1346 
1347     static int
1348 luaV_line(lua_State *L)
1349 {
1350     luaV_pushline(L, curbuf, curwin->w_cursor.lnum);
1351     return 1;
1352 }
1353 
1354     static int
1355 luaV_list(lua_State *L)
1356 {
1357     list_T *l = list_alloc();
1358     if (l == NULL)
1359 	lua_pushnil(L);
1360     else
1361 	luaV_newlist(L, l);
1362     return 1;
1363 }
1364 
1365     static int
1366 luaV_dict(lua_State *L)
1367 {
1368     dict_T *d = dict_alloc();
1369     if (d == NULL)
1370 	lua_pushnil(L);
1371     else
1372 	luaV_newdict(L, d);
1373     return 1;
1374 }
1375 
1376     static int
1377 luaV_buffer(lua_State *L)
1378 {
1379     buf_T *buf;
1380     if (lua_isstring(L, 1)) /* get by number or name? */
1381     {
1382 	if (lua_isnumber(L, 1)) /* by number? */
1383 	{
1384 	    int n = lua_tointeger(L, 1);
1385 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1386 		if (buf->b_fnum == n) break;
1387 	}
1388 	else { /* by name */
1389 	    size_t l;
1390 	    const char *s = lua_tolstring(L, 1, &l);
1391 	    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1392 	    {
1393 		if (buf->b_ffname == NULL || buf->b_sfname == NULL)
1394 		{
1395 		    if (l == 0) break;
1396 		}
1397 		else if (strncmp(s, (char *)buf->b_ffname, l) == 0
1398 			|| strncmp(s, (char *)buf->b_sfname, l) == 0)
1399 		    break;
1400 	    }
1401 	}
1402     }
1403     else
1404 	buf = (lua_toboolean(L, 1)) ? firstbuf : curbuf; /* first buffer? */
1405     luaV_pushbuffer(L, buf);
1406     return 1;
1407 }
1408 
1409     static int
1410 luaV_window(lua_State *L)
1411 {
1412     win_T *win;
1413     if (lua_isnumber(L, 1)) /* get by number? */
1414     {
1415 	int n = lua_tointeger(L, 1);
1416 	for (win = firstwin; win != NULL; win = win->w_next, n--)
1417 	    if (n == 1) break;
1418     }
1419     else
1420 	win = (lua_toboolean(L, 1)) ? firstwin : curwin; /* first window? */
1421     luaV_pushwindow(L, win);
1422     return 1;
1423 }
1424 
1425     static int
1426 luaV_open(lua_State *L)
1427 {
1428     char_u *s = NULL;
1429 #ifdef HAVE_SANDBOX
1430     luaV_checksandbox(L);
1431 #endif
1432     if (lua_isstring(L, 1)) s = (char_u *) lua_tostring(L, 1);
1433     luaV_pushbuffer(L, buflist_new(s, NULL, 1L, BLN_LISTED));
1434     return 1;
1435 }
1436 
1437     static int
1438 luaV_type(lua_State *L)
1439 {
1440     luaL_checkany(L, 1);
1441     if (lua_type(L, 1) == LUA_TUSERDATA) /* check vim udata? */
1442     {
1443 	lua_settop(L, 1);
1444 	if (lua_getmetatable(L, 1))
1445 	{
1446 	    luaV_getfield(L, LUAVIM_LIST);
1447 	    if (lua_rawequal(L, -1, 2))
1448 	    {
1449 		lua_pushstring(L, "list");
1450 		return 1;
1451 	    }
1452 	    luaV_getfield(L, LUAVIM_DICT);
1453 	    if (lua_rawequal(L, -1, 2))
1454 	    {
1455 		lua_pushstring(L, "dict");
1456 		return 1;
1457 	    }
1458 	    luaV_getfield(L, LUAVIM_BUFFER);
1459 	    if (lua_rawequal(L, -1, 2))
1460 	    {
1461 		lua_pushstring(L, "buffer");
1462 		return 1;
1463 	    }
1464 	    luaV_getfield(L, LUAVIM_WINDOW);
1465 	    if (lua_rawequal(L, -1, 2))
1466 	    {
1467 		lua_pushstring(L, "window");
1468 		return 1;
1469 	    }
1470 	}
1471     }
1472     lua_pushstring(L, luaL_typename(L, 1)); /* fallback */
1473     return 1;
1474 }
1475 
1476 static const luaL_Reg luaV_module[] = {
1477     {"command", luaV_command},
1478     {"eval", luaV_eval},
1479     {"beep", luaV_beep},
1480     {"line", luaV_line},
1481     {"list", luaV_list},
1482     {"dict", luaV_dict},
1483     {"buffer", luaV_buffer},
1484     {"window", luaV_window},
1485     {"open", luaV_open},
1486     {"type", luaV_type},
1487     {NULL, NULL}
1488 };
1489 
1490 /* for freeing list, dict, buffer and window objects; lightuserdata as arg */
1491     static int
1492 luaV_free(lua_State *L)
1493 {
1494     lua_pushnil(L);
1495     luaV_setudata(L, lua_touserdata(L, 1));
1496     return 0;
1497 }
1498 
1499     static int
1500 luaV_luaeval (lua_State *L)
1501 {
1502     luaL_Buffer b;
1503     size_t l;
1504     const char *str = lua_tolstring(L, 1, &l);
1505     typval_T *arg = (typval_T *) lua_touserdata(L, 2);
1506     typval_T *rettv = (typval_T *) lua_touserdata(L, 3);
1507     luaL_buffinit(L, &b);
1508     luaL_addlstring(&b, LUAVIM_EVALHEADER, sizeof(LUAVIM_EVALHEADER) - 1);
1509     luaL_addlstring(&b, str, l);
1510     luaL_pushresult(&b);
1511     str = lua_tolstring(L, -1, &l);
1512     if (luaL_loadbuffer(L, str, l, LUAVIM_EVALNAME)) /* compile error? */
1513     {
1514 	luaV_emsg(L);
1515 	return 0;
1516     }
1517     luaV_pushtypval(L, arg);
1518     if (lua_pcall(L, 1, 1, 0)) /* running error? */
1519     {
1520 	luaV_emsg(L);
1521 	return 0;
1522     }
1523     luaV_totypval(L, -1, rettv);
1524     return 0;
1525 }
1526 
1527     static int
1528 luaV_setref (lua_State *L)
1529 {
1530     int copyID = lua_tointeger(L, 1);
1531     typval_T tv;
1532     luaV_getfield(L, LUAVIM_LIST);
1533     luaV_getfield(L, LUAVIM_DICT);
1534     lua_pushnil(L);
1535     while (lua_next(L, lua_upvalueindex(1)) != 0) /* traverse cache table */
1536     {
1537 	lua_getmetatable(L, -1);
1538 	if (lua_rawequal(L, -1, 2)) /* list? */
1539 	{
1540 	    tv.v_type = VAR_LIST;
1541 	    tv.vval.v_list = (list_T *) lua_touserdata(L, 4); /* key */
1542 	}
1543 	else if (lua_rawequal(L, -1, 3)) /* dict? */
1544 	{
1545 	    tv.v_type = VAR_DICT;
1546 	    tv.vval.v_dict = (dict_T *) lua_touserdata(L, 4); /* key */
1547 	}
1548 	lua_pop(L, 2); /* metatable and value */
1549 	set_ref_in_item(&tv, copyID);
1550     }
1551     return 0;
1552 }
1553 
1554     static int
1555 luaopen_vim(lua_State *L)
1556 {
1557     /* set cache table */
1558     lua_newtable(L);
1559     lua_newtable(L);
1560     lua_pushstring(L, "v");
1561     lua_setfield(L, -2, "__mode");
1562     lua_setmetatable(L, -2); /* cache is weak-valued */
1563     /* print */
1564     lua_pushcfunction(L, luaV_print);
1565     lua_setglobal(L, "print");
1566     /* debug.debug */
1567     lua_getglobal(L, "debug");
1568     lua_pushcfunction(L, luaV_debug);
1569     lua_setfield(L, -2, "debug");
1570     lua_pop(L, 1);
1571     /* free */
1572     lua_pushlightuserdata(L, (void *) LUAVIM_FREE);
1573     lua_pushvalue(L, 1); /* cache table */
1574     lua_pushcclosure(L, luaV_free, 1);
1575     lua_rawset(L, LUA_REGISTRYINDEX);
1576     /* luaeval */
1577     lua_pushlightuserdata(L, (void *) LUAVIM_LUAEVAL);
1578     lua_pushvalue(L, 1); /* cache table */
1579     lua_pushcclosure(L, luaV_luaeval, 1);
1580     lua_rawset(L, LUA_REGISTRYINDEX);
1581     /* setref */
1582     lua_pushlightuserdata(L, (void *) LUAVIM_SETREF);
1583     lua_pushvalue(L, 1); /* cache table */
1584     lua_pushcclosure(L, luaV_setref, 1);
1585     lua_rawset(L, LUA_REGISTRYINDEX);
1586     /* register */
1587     luaV_newmetatable(L, LUAVIM_LIST);
1588     lua_pushvalue(L, 1);
1589     luaV_openlib(L, luaV_List_mt, 1);
1590     luaV_newmetatable(L, LUAVIM_DICT);
1591     lua_pushvalue(L, 1);
1592     luaV_openlib(L, luaV_Dict_mt, 1);
1593     luaV_newmetatable(L, LUAVIM_BUFFER);
1594     lua_pushvalue(L, 1); /* cache table */
1595     luaV_openlib(L, luaV_Buffer_mt, 1);
1596     luaV_newmetatable(L, LUAVIM_WINDOW);
1597     lua_pushvalue(L, 1); /* cache table */
1598     luaV_openlib(L, luaV_Window_mt, 1);
1599     lua_newtable(L); /* vim table */
1600     lua_pushvalue(L, 1); /* cache table */
1601     luaV_openlib(L, luaV_module, 1);
1602     lua_setglobal(L, LUAVIM_NAME);
1603     return 0;
1604 }
1605 
1606     static lua_State *
1607 luaV_newstate(void)
1608 {
1609     lua_State *L = luaL_newstate();
1610     luaL_openlibs(L); /* core libs */
1611     lua_pushcfunction(L, luaopen_vim); /* vim */
1612     lua_call(L, 0, 0);
1613     return L;
1614 }
1615 
1616     static void
1617 luaV_setrange(lua_State *L, int line1, int line2)
1618 {
1619     lua_getglobal(L, LUAVIM_NAME);
1620     lua_pushinteger(L, line1);
1621     lua_setfield(L, -2, "firstline");
1622     lua_pushinteger(L, line2);
1623     lua_setfield(L, -2, "lastline");
1624     lua_pop(L, 1); /* vim table */
1625 }
1626 
1627 
1628 /* =======   Interface   ======= */
1629 
1630 static lua_State *L = NULL;
1631 
1632     static int
1633 lua_isopen(void)
1634 {
1635     return L != NULL;
1636 }
1637 
1638     static int
1639 lua_init(void)
1640 {
1641     if (!lua_isopen())
1642     {
1643 #ifdef DYNAMIC_LUA
1644 	if (!lua_enabled(TRUE))
1645 	{
1646 	    EMSG(_("Lua library cannot be loaded."));
1647 	    return FAIL;
1648 	}
1649 #endif
1650 	L = luaV_newstate();
1651     }
1652     return OK;
1653 }
1654 
1655     void
1656 lua_end(void)
1657 {
1658     if (lua_isopen())
1659     {
1660 	lua_close(L);
1661 	L = NULL;
1662 #ifdef DYNAMIC_LUA
1663 	end_dynamic_lua();
1664 #endif
1665     }
1666 }
1667 
1668 /* ex commands */
1669     void
1670 ex_lua(exarg_T *eap)
1671 {
1672     char *script;
1673     if (lua_init() == FAIL) return;
1674     script = (char *) script_get(eap, eap->arg);
1675     if (!eap->skip)
1676     {
1677 	char *s = (script) ? script :  (char *) eap->arg;
1678 	luaV_setrange(L, eap->line1, eap->line2);
1679 	if (luaL_loadbuffer(L, s, strlen(s), LUAVIM_CHUNKNAME)
1680 		|| lua_pcall(L, 0, 0, 0))
1681 	    luaV_emsg(L);
1682     }
1683     if (script != NULL) vim_free(script);
1684 }
1685 
1686     void
1687 ex_luado(exarg_T *eap)
1688 {
1689     linenr_T l;
1690     const char *s = (const char *) eap->arg;
1691     luaL_Buffer b;
1692     size_t len;
1693     if (lua_init() == FAIL) return;
1694     if (u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
1695     {
1696 	EMSG(_("cannot save undo information"));
1697 	return;
1698     }
1699     luaV_setrange(L, eap->line1, eap->line2);
1700     luaL_buffinit(L, &b);
1701     luaL_addlstring(&b, "return function(line, linenr) ", 30); /* header */
1702     luaL_addlstring(&b, s, strlen(s));
1703     luaL_addlstring(&b, " end", 4); /* footer */
1704     luaL_pushresult(&b);
1705     s = lua_tolstring(L, -1, &len);
1706     if (luaL_loadbuffer(L, s, len, LUAVIM_CHUNKNAME))
1707     {
1708 	luaV_emsg(L);
1709 	lua_pop(L, 1); /* function body */
1710 	return;
1711     }
1712     lua_call(L, 0, 1);
1713     lua_replace(L, -2); /* function -> body */
1714     for (l = eap->line1; l <= eap->line2; l++)
1715     {
1716 	lua_pushvalue(L, -1); /* function */
1717 	luaV_pushline(L, curbuf, l); /* current line as arg */
1718 	lua_pushinteger(L, l); /* current line number as arg */
1719 	if (lua_pcall(L, 2, 1, 0))
1720 	{
1721 	    luaV_emsg(L);
1722 	    break;
1723 	}
1724 	if (lua_isstring(L, -1)) /* update line? */
1725 	{
1726 #ifdef HAVE_SANDBOX
1727 	    luaV_checksandbox(L);
1728 #endif
1729 	    ml_replace(l, luaV_toline(L, -1), TRUE);
1730 	    changed_bytes(l, 0);
1731 	    lua_pop(L, 1); /* result from luaV_toline */
1732 	}
1733 	lua_pop(L, 1); /* line */
1734     }
1735     lua_pop(L, 1); /* function */
1736     check_cursor();
1737     update_screen(NOT_VALID);
1738 }
1739 
1740     void
1741 ex_luafile(exarg_T *eap)
1742 {
1743     if (lua_init() == FAIL)
1744 	return;
1745     if (!eap->skip)
1746     {
1747 	luaV_setrange(L, eap->line1, eap->line2);
1748 	if (luaL_loadfile(L, (char *) eap->arg) || lua_pcall(L, 0, 0, 0))
1749 	    luaV_emsg(L);
1750     }
1751 }
1752 
1753 #define luaV_freetype(typ,tname) \
1754 	void \
1755     lua_##tname##_free(typ *o) \
1756     { \
1757 	if (!lua_isopen()) return; \
1758 	luaV_getfield(L, LUAVIM_FREE); \
1759 	lua_pushlightuserdata(L, (void *) o); \
1760 	lua_call(L, 1, 0); \
1761     }
1762 
1763 luaV_freetype(buf_T, buffer)
1764 luaV_freetype(win_T, window)
1765 
1766     void
1767 do_luaeval (char_u *str, typval_T *arg, typval_T *rettv)
1768 {
1769     lua_init();
1770     luaV_getfield(L, LUAVIM_LUAEVAL);
1771     lua_pushstring(L, (char *) str);
1772     lua_pushlightuserdata(L, (void *) arg);
1773     lua_pushlightuserdata(L, (void *) rettv);
1774     lua_call(L, 3, 0);
1775 }
1776 
1777     void
1778 set_ref_in_lua (int copyID)
1779 {
1780     if (!lua_isopen()) return;
1781     luaV_getfield(L, LUAVIM_SETREF);
1782     lua_pushinteger(L, copyID);
1783     lua_call(L, 1, 0);
1784 }
1785 
1786 #endif
1787