vis: reject invalid register name when recording a macro
[vis.git] / vis-lua.c
blob80e3e383b163265d35aa9867e5ca441a020bf1df
1 /***
2 * Lua Extension API for the [Vis Editor](https://github.com/martanne/vis).
4 * *WARNING:* there is no stability guarantee at this time, the API might
5 * change without notice!
7 * This document might be out of date, run `make luadoc` to regenerate it.
9 * @module vis
10 * @author Marc André Tanner
11 * @license ISC
12 * @release RELEASE
14 #include <stddef.h>
15 #include <stdarg.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <limits.h>
19 #include <unistd.h>
20 #include <libgen.h>
21 #include <sys/types.h>
22 #include <pwd.h>
24 #include "vis-lua.h"
25 #include "vis-core.h"
26 #include "text-motions.h"
27 #include "util.h"
29 #ifndef VIS_PATH
30 #define VIS_PATH "/usr/local/share/vis"
31 #endif
33 #define VIS_LUA_TYPE_VIS "vis"
34 #define VIS_LUA_TYPE_FILE "file"
35 #define VIS_LUA_TYPE_TEXT "text"
36 #define VIS_LUA_TYPE_MARK "mark"
37 #define VIS_LUA_TYPE_MARKS "marks"
38 #define VIS_LUA_TYPE_WINDOW "window"
39 #define VIS_LUA_TYPE_CURSOR "cursor"
40 #define VIS_LUA_TYPE_CURSORS "cursors"
41 #define VIS_LUA_TYPE_UI "ui"
42 #define VIS_LUA_TYPE_REGISTERS "registers"
43 #define VIS_LUA_TYPE_KEYACTION "keyaction"
45 #ifndef DEBUG_LUA
46 #define DEBUG_LUA 0
47 #endif
49 #if DEBUG_LUA
50 #define debug(...) do { printf(__VA_ARGS__); fflush(stdout); } while (0)
51 #else
52 #define debug(...) do { } while (0)
53 #endif
55 static void window_status_update(Vis *vis, Win *win) {
56 char left_parts[4][255] = { "", "", "", "" };
57 char right_parts[4][32] = { "", "", "", "" };
58 char left[sizeof(left_parts)+LENGTH(left_parts)*8];
59 char right[sizeof(right_parts)+LENGTH(right_parts)*8];
60 char status[sizeof(left)+sizeof(right)+1];
61 size_t left_count = 0;
62 size_t right_count = 0;
64 View *view = win->view;
65 File *file = win->file;
66 Text *txt = file->text;
67 int width = vis_window_width_get(win);
68 enum UiOption options = view_options_get(view);
69 bool focused = vis->win == win;
70 const char *filename = file_name_get(file);
71 const char *mode = vis->mode->status;
73 if (focused && mode)
74 strcpy(left_parts[left_count++], mode);
76 snprintf(left_parts[left_count], sizeof(left_parts[left_count])-1, "%s%s%s",
77 filename ? filename : "[No Name]",
78 text_modified(txt) ? " [+]" : "",
79 vis_macro_recording(vis) ? " @": "");
80 left_count++;
82 int cursor_count = view_cursors_count(view);
83 if (cursor_count > 1) {
84 Cursor *c = view_cursors_primary_get(view);
85 int cursor_number = view_cursors_number(c) + 1;
86 snprintf(right_parts[right_count], sizeof(right_parts[right_count])-1,
87 "%d/%d", cursor_number, cursor_count);
88 right_count++;
91 size_t size = text_size(txt);
92 size_t pos = view_cursor_get(view);
93 size_t percent = 0;
94 if (size > 0) {
95 double tmp = ((double)pos/(double)size)*100;
96 percent = (size_t)(tmp+1);
98 snprintf(right_parts[right_count], sizeof(right_parts[right_count])-1,
99 "%zu%%", percent);
100 right_count++;
102 if (!(options & UI_OPTION_LARGE_FILE)) {
103 Cursor *cur = view_cursors_primary_get(win->view);
104 size_t line = view_cursors_line(cur);
105 size_t col = view_cursors_col(cur);
106 if (col > UI_LARGE_FILE_LINE_SIZE) {
107 options |= UI_OPTION_LARGE_FILE;
108 view_options_set(win->view, options);
110 snprintf(right_parts[right_count], sizeof(right_parts[right_count])-1,
111 "%zu, %zu", line, col);
112 right_count++;
115 int left_len = snprintf(left, sizeof(left)-1, " %s%s%s%s%s%s%s",
116 left_parts[0],
117 left_parts[1][0] ? " » " : "",
118 left_parts[1],
119 left_parts[2][0] ? " » " : "",
120 left_parts[2],
121 left_parts[3][0] ? " » " : "",
122 left_parts[3]);
124 int right_len = snprintf(right, sizeof(right)-1, "%s%s%s%s%s%s%s ",
125 right_parts[0],
126 right_parts[1][0] ? " « " : "",
127 right_parts[1],
128 right_parts[2][0] ? " « " : "",
129 right_parts[2],
130 right_parts[3][0] ? " « " : "",
131 right_parts[3]);
133 if (left_len < 0 || right_len < 0)
134 return;
135 int left_width = text_string_width(left, left_len);
136 int right_width = text_string_width(right, right_len);
138 int spaces = width - left_width - right_width;
139 if (spaces < 1)
140 spaces = 1;
142 snprintf(status, sizeof(status)-1, "%s%*s%s", left, spaces, " ", right);
143 vis_window_status(win, status);
146 #if !CONFIG_LUA
148 bool vis_lua_path_add(Vis *vis, const char *path) { return true; }
149 bool vis_lua_paths_get(Vis *vis, char **lpath, char **cpath) { return false; }
150 void vis_lua_init(Vis *vis) { }
151 void vis_lua_start(Vis *vis) { }
152 void vis_lua_quit(Vis *vis) { }
153 void vis_lua_file_open(Vis *vis, File *file) { }
154 bool vis_lua_file_save_pre(Vis *vis, File *file, const char *path) { return true; }
155 void vis_lua_file_save_post(Vis *vis, File *file, const char *path) { }
156 void vis_lua_file_close(Vis *vis, File *file) { }
157 void vis_lua_win_open(Vis *vis, Win *win) { }
158 void vis_lua_win_close(Vis *vis, Win *win) { }
159 void vis_lua_win_highlight(Vis *vis, Win *win) { }
160 void vis_lua_win_status(Vis *vis, Win *win) { window_status_update(vis, win); }
162 #else
164 #if DEBUG_LUA
165 static void stack_dump_entry(lua_State *L, int i) {
166 int t = lua_type(L, i);
167 switch (t) {
168 case LUA_TNIL:
169 printf("nil");
170 break;
171 case LUA_TBOOLEAN:
172 printf(lua_toboolean(L, i) ? "true" : "false");
173 break;
174 case LUA_TLIGHTUSERDATA:
175 printf("lightuserdata(%p)", lua_touserdata(L, i));
176 break;
177 case LUA_TNUMBER:
178 printf("%g", lua_tonumber(L, i));
179 break;
180 case LUA_TSTRING:
181 printf("`%s'", lua_tostring(L, i));
182 break;
183 case LUA_TTABLE:
184 printf("table[");
185 lua_pushnil(L); /* first key */
186 while (lua_next(L, i > 0 ? i : i - 1)) {
187 stack_dump_entry(L, -2);
188 printf("=");
189 stack_dump_entry(L, -1);
190 printf(",");
191 lua_pop(L, 1); /* remove value, keep key */
193 printf("]");
194 break;
195 case LUA_TUSERDATA:
196 printf("userdata(%p)", lua_touserdata(L, i));
197 break;
198 default: /* other values */
199 printf("%s", lua_typename(L, t));
200 break;
204 static void stack_dump(lua_State *L, const char *format, ...) {
205 va_list ap;
206 va_start(ap, format);
207 vprintf(format, ap);
208 va_end(ap);
209 int top = lua_gettop(L);
210 for (int i = 1; i <= top; i++) {
211 printf("%d: ", i);
212 stack_dump_entry(L, i);
213 printf("\n");
215 printf("\n\n");
216 fflush(stdout);
219 #endif
221 static int panic_handler(lua_State *L) {
222 void *ud = NULL;
223 lua_getallocf(L, &ud);
224 if (ud) {
225 Vis *vis = ud;
226 vis->lua = NULL;
227 const char *msg = NULL;
228 if (lua_type(L, -1) == LUA_TSTRING)
229 msg = lua_tostring(L, -1);
230 vis_info_show(vis, "Fatal Lua error: %s", msg ? msg : "unknown reason");
231 lua_close(L);
232 if (vis->running)
233 siglongjmp(vis->sigbus_jmpbuf, 1);
235 return 0;
238 static int error_handler(lua_State *L) {
239 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
240 if (vis->errorhandler)
241 return 1;
242 vis->errorhandler = true;
243 size_t len;
244 const char *msg = lua_tostring(L, 1);
245 if (msg)
246 luaL_traceback(L, L, msg, 1);
247 msg = lua_tolstring(L, 1, &len);
248 vis_message_show(vis, msg);
249 vis->errorhandler = false;
250 return 1;
253 static int pcall(Vis *vis, lua_State *L, int nargs, int nresults) {
254 /* insert a custom error function below all arguments */
255 int msgh = lua_gettop(L) - nargs;
256 lua_pushlightuserdata(L, vis);
257 lua_pushcclosure(L, error_handler, 1);
258 lua_insert(L, msgh);
259 int ret = lua_pcall(L, nargs, nresults, msgh);
260 lua_remove(L, msgh);
261 return ret;
264 /* expects a lua function at stack position `narg` and stores a
265 * reference to it in the registry. The return value can be used
266 * to look it up.
268 * registry["vis.functions"][(void*)(function)] = function
270 static const void *func_ref_new(lua_State *L, int narg) {
271 const void *addr = lua_topointer(L, narg);
272 if (!lua_isfunction(L, narg) || !addr)
273 luaL_argerror(L, narg, "function expected");
274 lua_getfield(L, LUA_REGISTRYINDEX, "vis.functions");
275 lua_pushlightuserdata(L, (void*)addr);
276 lua_pushvalue(L, narg);
277 lua_settable(L, -3);
278 lua_pop(L, 1);
279 return addr;
282 /* retrieve function from registry and place it at the top of the stack */
283 static bool func_ref_get(lua_State *L, const void *addr) {
284 if (!addr)
285 return false;
286 lua_getfield(L, LUA_REGISTRYINDEX, "vis.functions");
287 lua_pushlightuserdata(L, (void*)addr);
288 lua_gettable(L, -2);
289 lua_remove(L, -2);
290 if (!lua_isfunction(L, -1)) {
291 lua_pop(L, 1);
292 return false;
294 return true;
297 /* creates a new metatable for a given type and stores a mapping:
299 * registry["vis.types"][metatable] = type
301 * leaves the metatable at the top of the stack.
303 static void obj_type_new(lua_State *L, const char *type) {
304 luaL_newmetatable(L, type);
305 lua_getglobal(L, "vis");
306 if (!lua_isnil(L, -1)) {
307 lua_getfield(L, -1, "types");
308 lua_pushvalue(L, -3);
309 lua_setfield(L, -2, type);
310 lua_pop(L, 1);
312 lua_pop(L, 1);
313 lua_getfield(L, LUA_REGISTRYINDEX, "vis.types");
314 lua_pushvalue(L, -2);
315 lua_pushstring(L, type);
316 lua_settable(L, -3);
317 lua_pop(L, 1);
320 /* get type of userdatum at the top of the stack:
322 * return registry["vis.types"][getmetatable(userdata)]
324 const char *obj_type_get(lua_State *L) {
325 if (lua_isnil(L, -1))
326 return "nil";
327 lua_getfield(L, LUA_REGISTRYINDEX, "vis.types");
328 lua_getmetatable(L, -2);
329 lua_gettable(L, -2);
330 // XXX: in theory string might become invalid when poped from stack
331 const char *type = lua_tostring(L, -1);
332 lua_pop(L, 2);
333 return type;
336 static void *obj_new(lua_State *L, size_t size, const char *type) {
337 void *obj = lua_newuserdata(L, size);
338 luaL_getmetatable(L, type);
339 lua_setmetatable(L, -2);
340 lua_newtable(L);
341 lua_setuservalue(L, -2);
342 return obj;
345 /* returns registry["vis.objects"][addr] if it is of correct type */
346 static void *obj_ref_get(lua_State *L, void *addr, const char *type) {
347 lua_getfield(L, LUA_REGISTRYINDEX, "vis.objects");
348 lua_pushlightuserdata(L, addr);
349 lua_gettable(L, -2);
350 lua_remove(L, -2);
351 if (lua_isnil(L, -1)) {
352 debug("get: vis.objects[%p] = nil\n", addr);
353 lua_pop(L, 1);
354 return NULL;
356 if (DEBUG_LUA) {
357 const char *actual_type = obj_type_get(L);
358 if (strcmp(type, actual_type) != 0)
359 debug("get: vis.objects[%p] = %s (BUG: expected %s)\n", addr, actual_type, type);
360 void **handle = luaL_checkudata(L, -1, type);
361 if (!handle)
362 debug("get: vis.objects[%p] = %s (BUG: invalid handle)\n", addr, type);
363 else if (*handle != addr)
364 debug("get: vis.objects[%p] = %s (BUG: handle mismatch %p)\n", addr, type, *handle);
366 return luaL_checkudata(L, -1, type);
369 /* expects a userdatum at the top of the stack and sets
371 * registry["vis.objects"][addr] = userdata
373 static void obj_ref_set(lua_State *L, void *addr) {
374 //debug("set: vis.objects[%p] = %s\n", addr, obj_type_get(L));
375 lua_getfield(L, LUA_REGISTRYINDEX, "vis.objects");
376 lua_pushlightuserdata(L, addr);
377 lua_pushvalue(L, -3);
378 lua_settable(L, -3);
379 lua_pop(L, 1);
382 /* invalidates an object reference
384 * registry["vis.objects"][addr] = nil
386 static void obj_ref_free(lua_State *L, void *addr) {
387 if (DEBUG_LUA) {
388 lua_getfield(L, LUA_REGISTRYINDEX, "vis.objects");
389 lua_pushlightuserdata(L, addr);
390 lua_gettable(L, -2);
391 lua_remove(L, -2);
392 if (lua_isnil(L, -1))
393 debug("free-unused: %p\n", addr);
394 else
395 debug("free: vis.objects[%p] = %s\n", addr, obj_type_get(L));
396 lua_pop(L, 1);
398 lua_pushnil(L);
399 obj_ref_set(L, addr);
402 /* creates a new object reference of given type if it does not already exist in the registry:
404 * if (registry["vis.types"][metatable(registry["vis.objects"][addr])] != type) {
405 * // XXX: should not happen
406 * registry["vis.objects"][addr] = new_obj(addr, type)
408 * return registry["vis.objects"][addr];
410 static void *obj_ref_new(lua_State *L, void *addr, const char *type) {
411 if (!addr) {
412 lua_pushnil(L);
413 return NULL;
415 lua_getfield(L, LUA_REGISTRYINDEX, "vis.objects");
416 lua_pushlightuserdata(L, addr);
417 lua_gettable(L, -2);
418 lua_remove(L, -2);
419 const char *old_type = obj_type_get(L);
420 if (strcmp(type, old_type) == 0) {
421 debug("new: vis.objects[%p] = %s (returning existing object)\n", addr, old_type);
422 void **handle = luaL_checkudata(L, -1, type);
423 if (!handle)
424 debug("new: vis.objects[%p] = %s (BUG: invalid handle)\n", addr, old_type);
425 else if (*handle != addr)
426 debug("new: vis.objects[%p] = %s (BUG: handle mismatch %p)\n", addr, old_type, *handle);
427 return addr;
429 if (!lua_isnil(L, -1))
430 debug("new: vis.objects[%p] = %s (WARNING: changing object type from %s)\n", addr, type, old_type);
431 else
432 debug("new: vis.objects[%p] = %s (creating new object)\n", addr, type);
433 lua_pop(L, 1);
434 void **handle = obj_new(L, sizeof(addr), type);
435 obj_ref_set(L, addr);
436 *handle = addr;
437 return addr;
440 /* retrieve object stored in reference at stack location `idx' */
441 static void *obj_ref_check_get(lua_State *L, int idx, const char *type) {
442 void **addr = luaL_checkudata(L, idx, type);
443 if (!obj_ref_get(L, *addr, type))
444 return NULL;
445 return *addr;
448 /* (type) check validity of object reference at stack location `idx' */
449 static void *obj_ref_check(lua_State *L, int idx, const char *type) {
450 void *obj = obj_ref_check_get(L, idx, type);
451 if (obj)
452 lua_pop(L, 1);
453 else
454 luaL_argerror(L, idx, "invalid object reference");
455 return obj;
458 static void *obj_ref_check_containerof(lua_State *L, int idx, const char *type, size_t offset) {
459 void *obj = obj_ref_check(L, idx, type);
460 return obj ? ((char*)obj-offset) : obj;
463 static void *obj_lightref_new(lua_State *L, void *addr, const char *type) {
464 if (!addr)
465 return NULL;
466 void **handle = obj_new(L, sizeof(addr), type);
467 *handle = addr;
468 return addr;
471 static void *obj_lightref_check(lua_State *L, int idx, const char *type) {
472 void **addr = luaL_checkudata(L, idx, type);
473 return *addr;
476 static int index_common(lua_State *L) {
477 lua_getmetatable(L, 1);
478 lua_pushvalue(L, 2);
479 lua_gettable(L, -2);
480 if (lua_isnil(L, -1)) {
481 lua_getuservalue(L, 1);
482 lua_pushvalue(L, 2);
483 lua_gettable(L, -2);
485 return 1;
488 static int newindex_common(lua_State *L) {
489 lua_getuservalue(L, 1);
490 lua_pushvalue(L, 2);
491 lua_pushvalue(L, 3);
492 lua_settable(L, -3);
493 return 0;
496 static size_t getpos(lua_State *L, int narg) {
497 return lua_tounsigned(L, narg);
500 static size_t checkpos(lua_State *L, int narg) {
501 lua_Number n = luaL_checknumber(L, narg);
502 if (n >= 0 && n <= SIZE_MAX && n == (size_t)n)
503 return n;
504 return luaL_argerror(L, narg, "expected position, got number");
507 static void pushpos(lua_State *L, size_t pos) {
508 if (pos == EPOS)
509 lua_pushnil(L);
510 else
511 lua_pushunsigned(L, pos);
514 static void pushrange(lua_State *L, Filerange *r) {
515 if (!text_range_valid(r)) {
516 lua_pushnil(L);
517 return;
519 lua_createtable(L, 0, 2);
520 lua_pushstring(L, "start");
521 lua_pushunsigned(L, r->start);
522 lua_settable(L, -3);
523 lua_pushstring(L, "finish");
524 lua_pushunsigned(L, r->end);
525 lua_settable(L, -3);
528 static Filerange getrange(lua_State *L, int index) {
529 Filerange range = text_range_empty();
530 if (lua_istable(L, index)) {
531 lua_getfield(L, index, "start");
532 range.start = checkpos(L, -1);
533 lua_pop(L, 1);
534 lua_getfield(L, index, "finish");
535 range.end = checkpos(L, -1);
536 lua_pop(L, 1);
537 } else {
538 range.start = checkpos(L, index);
539 range.end = range.start + checkpos(L, index+1);
541 return range;
544 static const char *keymapping(Vis *vis, const char *keys, const Arg *arg) {
545 lua_State *L = vis->lua;
546 if (!func_ref_get(L, arg->v))
547 return keys;
548 lua_pushstring(L, keys);
549 if (pcall(vis, L, 1, 1) != 0)
550 return keys;
551 if (lua_type(L, -1) != LUA_TNUMBER)
552 return keys; /* invalid or no return value, assume zero */
553 lua_Number number = lua_tonumber(L, -1);
554 lua_Integer integer = lua_tointeger(L, -1);
555 if (number != integer)
556 return keys;
557 if (integer < 0)
558 return NULL; /* need more input */
559 size_t len = integer;
560 size_t max = strlen(keys);
561 return (len <= max) ? keys+len : keys;
564 /***
565 * The main editor object.
566 * @type Vis
569 /***
570 * Version information.
571 * @tfield string VERSION
572 * version information in `git describe` format, same as reported by `vis -v`.
574 /***
575 * Lua API object types
576 * @field types meta tables of userdata objects used for type checking
577 * @local
579 /***
580 * User interface.
581 * @tfield Ui ui the user interface being used
583 /***
584 * Mode constants.
585 * @tfield modes modes
587 /***
588 * Events.
589 * @tfield events events
591 /***
592 * Registers.
593 * @field registers array to access the register by single letter name
595 /***
596 * Scintillua lexer module.
597 * @field lexers might be `nil` if module is not found
599 /***
600 * LPeg lexer module.
601 * @field lpeg might be `nil` if module is not found
603 /***
604 * Current count.
605 * @tfield int count the specified count for the current command or `nil` if none was given
608 /***
609 * Create an iterator over all windows.
610 * @function windows
611 * @return the new iterator
612 * @see win
613 * @usage
614 * for win in vis:windows() do
615 * -- do something with win
616 * end
618 static int windows_iter(lua_State *L);
619 static int windows(lua_State *L) {
620 Vis *vis = obj_ref_check(L, 1, "vis");
621 Win **handle = lua_newuserdata(L, sizeof *handle);
622 *handle = vis->windows;
623 lua_pushcclosure(L, windows_iter, 1);
624 return 1;
627 static int windows_iter(lua_State *L) {
628 Win **handle = lua_touserdata(L, lua_upvalueindex(1));
629 if (!*handle)
630 return 0;
631 Win *win = obj_ref_new(L, *handle, VIS_LUA_TYPE_WINDOW);
632 if (win)
633 *handle = win->next;
634 return 1;
637 /***
638 * Create an iterator over all files.
639 * @function files
640 * @return the new iterator
641 * @usage
642 * for file in vis:files() do
643 * -- do something with file
644 * end
646 static int files_iter(lua_State *L);
647 static int files(lua_State *L) {
648 Vis *vis = obj_ref_check(L, 1, "vis");
649 File **handle = lua_newuserdata(L, sizeof *handle);
650 *handle = vis->files;
651 lua_pushcclosure(L, files_iter, 1);
652 return 1;
655 static int files_iter(lua_State *L) {
656 File **handle = lua_touserdata(L, lua_upvalueindex(1));
657 if (!*handle)
658 return 0;
659 File *file = obj_ref_new(L, *handle, VIS_LUA_TYPE_FILE);
660 if (file)
661 *handle = file->next;
662 return 1;
665 /***
666 * Create an iterator over all mark names.
667 * @function mark_names
668 * @return the new iterator
669 * @usage
670 * local marks = vis.win.file.marks;
671 * for mark in vis:mark_names() do
672 * local pos = marks[mark]
673 * if pos then
674 * -- do something with mark pos
675 * end
676 * end
678 static int mark_names_iter(lua_State *L);
679 static int mark_names(lua_State *L) {
680 enum VisMark *handle = lua_newuserdata(L, sizeof *handle);
681 *handle = 0;
682 lua_pushcclosure(L, mark_names_iter, 1);
683 return 1;
686 static int mark_names_iter(lua_State *L) {
687 char mark = '\0';
688 enum VisMark *handle = lua_touserdata(L, lua_upvalueindex(1));
689 if (*handle < LENGTH(vis_marks))
690 mark = vis_marks[*handle].name;
691 else if (VIS_MARK_a <= *handle && *handle <= VIS_MARK_z)
692 mark = 'a' + *handle - VIS_MARK_a;
693 if (mark) {
694 char name[2] = { mark, '\0' };
695 lua_pushstring(L, name);
696 (*handle)++;
697 return 1;
699 return 0;
702 /***
703 * Create an iterator over all register names.
704 * @function register_names
705 * @return the new iterator
706 * @usage
707 * for reg in vis:register_names() do
708 * local value = vis.registers[reg]
709 * if value then
710 * -- do something with register value
711 * end
712 * end
714 static int register_names_iter(lua_State *L);
715 static int register_names(lua_State *L) {
716 enum VisRegister *handle = lua_newuserdata(L, sizeof *handle);
717 *handle = 0;
718 lua_pushcclosure(L, register_names_iter, 1);
719 return 1;
722 static int register_names_iter(lua_State *L) {
723 char reg = '\0';
724 enum VisRegister *handle = lua_touserdata(L, lua_upvalueindex(1));
725 if (*handle < LENGTH(vis_registers))
726 reg = vis_registers[*handle].name;
727 else if (VIS_REG_a <= *handle && *handle <= VIS_REG_z)
728 reg = 'a' + *handle - VIS_REG_a;
729 if (reg) {
730 char name[2] = { reg, '\0' };
731 lua_pushstring(L, name);
732 (*handle)++;
733 return 1;
735 return 0;
738 /***
739 * Execute a `:`-command.
740 * @function command
741 * @tparam string command the command to execute
742 * @treturn bool whether the command succeeded
743 * @usage
744 * vis:command("set number")
746 static int command(lua_State *L) {
747 Vis *vis = obj_ref_check(L, 1, "vis");
748 const char *cmd = luaL_checkstring(L, 2);
749 bool ret = vis_cmd(vis, cmd);
750 lua_pushboolean(L, ret);
751 return 1;
754 /***
755 * Display a short message.
757 * The single line message will be displayed at the bottom of
758 * the scren and automatically hidden once a key is pressed.
760 * @function info
761 * @tparam string message the message to display
763 static int info(lua_State *L) {
764 Vis *vis = obj_ref_check(L, 1, "vis");
765 const char *msg = luaL_checkstring(L, 2);
766 vis_info_show(vis, "%s", msg);
767 return 0;
770 /***
771 * Display a multi line message.
773 * Opens a new window and displays an arbitrarily long message.
775 * @function message
776 * @tparam string message the message to display
778 static int message(lua_State *L) {
779 Vis *vis = obj_ref_check(L, 1, "vis");
780 const char *msg = luaL_checkstring(L, 2);
781 vis_message_show(vis, msg);
782 return 0;
785 /***
786 * Register a Lua function as key action.
787 * @function action_register
788 * @tparam string name the name of the action, can be referred to in key bindings as `<name>` pseudo key
789 * @tparam Function func the lua function implementing the key action (see @{keyhandler})
790 * @tparam[opt] string help the single line help text as displayed in `:help`
791 * @treturn KeyAction action the registered key action
792 * @see Vis:map
793 * @see Window:map
795 static int action_register(lua_State *L) {
796 Vis *vis = obj_ref_check(L, 1, "vis");
797 const char *name = luaL_checkstring(L, 2);
798 const void *func = func_ref_new(L, 3);
799 const char *help = luaL_optstring(L, 4, NULL);
800 KeyAction *action = vis_action_new(vis, name, help, keymapping, (Arg){ .v = func });
801 if (!action)
802 goto err;
803 if (!vis_action_register(vis, action))
804 goto err;
805 obj_ref_new(L, action, VIS_LUA_TYPE_KEYACTION);
806 return 1;
807 err:
808 vis_action_free(vis, action);
809 lua_pushnil(L);
810 return 1;
813 static int keymap(lua_State *L, Vis *vis, Win *win) {
814 int mode = luaL_checkint(L, 2);
815 const char *key = luaL_checkstring(L, 3);
816 const char *help = luaL_optstring(L, 5, NULL);
817 KeyBinding *binding = vis_binding_new(vis);
818 if (!binding)
819 goto err;
820 if (lua_isstring(L, 4)) {
821 const char *alias = luaL_checkstring(L, 4);
822 if (!(binding->alias = strdup(alias)))
823 goto err;
824 } else if (lua_isfunction(L, 4)) {
825 const void *func = func_ref_new(L, 4);
826 if (!(binding->action = vis_action_new(vis, NULL, help, keymapping, (Arg){ .v = func })))
827 goto err;
828 } else if (lua_isuserdata(L, 4)) {
829 binding->action = obj_ref_check(L, 4, VIS_LUA_TYPE_KEYACTION);
832 if (win) {
833 if (!vis_window_mode_map(win, mode, true, key, binding))
834 goto err;
835 } else {
836 if (!vis_mode_map(vis, mode, true, key, binding))
837 goto err;
840 lua_pushboolean(L, true);
841 return 1;
842 err:
843 vis_binding_free(vis, binding);
844 lua_pushboolean(L, false);
845 return 1;
848 /***
849 * Map a key to a Lua function.
851 * Creates a new key mapping in a given mode.
853 * @function map
854 * @tparam int mode the mode to which the mapping should be added
855 * @tparam string key the key to map
856 * @tparam function func the Lua function to handle the key mapping (see @{keyhandler})
857 * @tparam[opt] string help the single line help text as displayed in `:help`
858 * @treturn bool whether the mapping was successfully established
859 * @see Window:map
860 * @usage
861 * vis:map(vis.modes.INSERT, "<C-k>", function(keys)
862 * if #keys < 2 then
863 * return -1 -- need more input
864 * end
865 * local digraph = keys:sub(1, 2)
866 * if digraph == "l*" then
867 * vis:feedkeys('λ')
868 * return 2 -- consume 2 bytes of input
869 * end
870 * end, "Insert digraph")
872 /***
873 * Setup a key alias.
875 * This is equivalent to `vis:command('map! mode key alias')`.
877 * Mappings are always recursive!
878 * @function map
879 * @tparam int mode the mode to which the mapping should be added
880 * @tparam string key the key to map
881 * @tparam string alias the key to map to
882 * @treturn bool whether the mapping was successfully established
883 * @see Window:map
884 * @usage
885 * vis:map(vis.modes.NORMAL, "j", "k")
887 /***
888 * Map a key to a key action.
890 * @function map
891 * @tparam int mode the mode to which the mapping should be added
892 * @tparam string key the key to map
893 * @param action the action to map
894 * @treturn bool whether the mapping was successfully established
895 * @see Window:map
896 * @usage
897 * local action = vis:action_register("info", function()
898 * vis:info("Mapping works!")
899 * end, "Info message help text")
900 * vis:map(vis.modes.NORMAL, "gh", action)
901 * vis:map(vis.modes.NORMAL, "gl", action)
903 static int map(lua_State *L) {
904 Vis *vis = obj_ref_check(L, 1, "vis");
905 return keymap(L, vis, NULL);
908 /***
909 * Execute a motion.
911 * @function motion
912 * @tparam int id the id of the motion to execute
913 * @treturn bool whether the id was valid
914 * @local
916 static int motion(lua_State *L) {
917 Vis *vis = obj_ref_check(L, 1, "vis");
918 enum VisMotion id = luaL_checkunsigned(L, 2);
919 // TODO handle var args?
920 lua_pushboolean(L, vis && vis_motion(vis, id));
921 return 1;
924 static size_t motion_lua(Vis *vis, Win *win, void *data, size_t pos) {
925 lua_State *L = vis->lua;
926 if (!L || !func_ref_get(L, data) || !obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW))
927 return EPOS;
929 lua_pushunsigned(L, pos);
930 if (pcall(vis, L, 2, 1) != 0)
931 return EPOS;
932 return getpos(L, -1);
935 /***
936 * Register a custom motion.
938 * @function motion_register
939 * @tparam function motion the Lua function implementing the motion
940 * @treturn int the associated motion id, or `-1` on failure
941 * @see motion, motion_new
942 * @local
943 * @usage
944 * -- custom motion advancing to the next byte
945 * local id = vis:motion_register(function(win, pos)
946 * return pos+1
947 * end)
949 static int motion_register(lua_State *L) {
950 Vis *vis = obj_ref_check(L, 1, "vis");
951 const void *func = func_ref_new(L, 2);
952 int id = vis_motion_register(vis, 0, (void*)func, motion_lua);
953 lua_pushinteger(L, id);
954 return 1;
957 /***
958 * Execute an operator.
960 * @function operator
961 * @tparam int id the id of the operator to execute
962 * @treturn bool whether the id was valid
963 * @local
965 static int operator(lua_State *L) {
966 Vis *vis = obj_ref_check(L, 1, "vis");
967 enum VisOperator id = luaL_checkunsigned(L, 2);
968 // TODO handle var args?
969 lua_pushboolean(L, vis && vis_operator(vis, id));
970 return 1;
973 static size_t operator_lua(Vis *vis, Text *text, OperatorContext *c) {
974 lua_State *L = vis->lua;
975 if (!L || !func_ref_get(L, c->context))
976 return EPOS;
977 File *file = vis->files;
978 while (file && (file->internal || file->text != text))
979 file = file->next;
980 if (!file || !obj_ref_new(L, file, VIS_LUA_TYPE_FILE))
981 return EPOS;
982 pushrange(L, &c->range);
983 pushpos(L, c->pos);
984 if (pcall(vis, L, 3, 1) != 0)
985 return EPOS;
986 return getpos(L, -1);
989 /***
990 * Register a custom operator.
992 * @function operator_register
993 * @tparam function operator the Lua function implementing the operator
994 * @treturn int the associated operator id, or `-1` on failure
995 * @see operator, operator_new
996 * @local
997 * @usage
998 * -- custom operator replacing every 'a' with 'b'
999 * local id = vis:operator_register(function(file, range, pos)
1000 * local data = file:content(range)
1001 * data = data:gsub("a", "b")
1002 * file:delete(range)
1003 * file:insert(range.start, data)
1004 * return range.start -- new cursor location
1005 * end)
1007 static int operator_register(lua_State *L) {
1008 Vis *vis = obj_ref_check(L, 1, "vis");
1009 const void *func = func_ref_new(L, 2);
1010 int id = vis_operator_register(vis, operator_lua, (void*)func);
1011 lua_pushinteger(L, id);
1012 return 1;
1015 /***
1016 * Execute a text object.
1018 * @function textobject
1019 * @tparam int id the id of the text object to execute
1020 * @treturn bool whether the id was valid
1021 * @see textobject_register, textobject_new
1022 * @local
1024 static int textobject(lua_State *L) {
1025 Vis *vis = obj_ref_check(L, 1, "vis");
1026 enum VisTextObject id = luaL_checkunsigned(L, 2);
1027 lua_pushboolean(L, vis_textobject(vis, id));
1028 return 1;
1031 static Filerange textobject_lua(Vis *vis, Win *win, void *data, size_t pos) {
1032 lua_State *L = vis->lua;
1033 if (!L || !func_ref_get(L, data) || !obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW))
1034 return text_range_empty();
1035 lua_pushunsigned(L, pos);
1036 if (pcall(vis, L, 2, 2) != 0 || lua_isnil(L, -1))
1037 return text_range_empty();
1038 return text_range_new(getpos(L, -2), getpos(L, -1));
1041 /***
1042 * Register a custom text object.
1044 * @function textobject_register
1045 * @tparam function textobject the Lua function implementing the text object
1046 * @treturn int the associated text object id, or `-1` on failure
1047 * @see textobject, textobject_new
1048 * @local
1049 * @usage
1050 * -- custom text object covering the next byte
1051 * local id = vis:textobject_register(function(win, pos)
1052 * return pos, pos+1
1053 * end)
1055 static int textobject_register(lua_State *L) {
1056 Vis *vis = obj_ref_check(L, 1, "vis");
1057 const void *func = func_ref_new(L, 2);
1058 int id = vis_textobject_register(vis, 0, (void*)func, textobject_lua);
1059 lua_pushinteger(L, id);
1060 return 1;
1063 static bool option_lua(Vis *vis, Win *win, void *context, bool toggle,
1064 enum VisOption flags, const char *name, Arg *value) {
1065 lua_State *L = vis->lua;
1066 if (!L || !func_ref_get(L, context))
1067 return false;
1068 if (flags & VIS_OPTION_TYPE_BOOL)
1069 lua_pushboolean(L, value->b);
1070 else if (flags & VIS_OPTION_TYPE_STRING)
1071 lua_pushstring(L, value->s);
1072 else if (flags & VIS_OPTION_TYPE_NUMBER)
1073 lua_pushnumber(L, value->i);
1074 else
1075 return false;
1076 lua_pushboolean(L, toggle);
1077 return pcall(vis, L, 2, 2) == 0 && (!lua_isboolean(L, -1) || lua_toboolean(L, -1));
1080 /***
1081 * Register a custom `:set` option.
1083 * @function option_register
1084 * @tparam string name the option name
1085 * @tparam string type the option type (`bool`, `string` or `number`)
1086 * @tparam function handler the Lua function being called when the option is changed
1087 * @tparam[opt] string help the single line help text as displayed in `:help`
1088 * @treturn bool whether the option was successfully registered
1089 * @usage
1090 * vis:option_register("foo", "bool", function(value, toogle)
1091 * if not vis.win then return false end
1092 * vis.win.foo = toogle and not vis.win.foo or value
1093 * vis:info("Option foo = " .. tostring(vis.win.foo))
1094 * return true
1095 * end, "Foo enables superpowers")
1097 static int option_register(lua_State *L) {
1098 Vis *vis = obj_ref_check(L, 1, "vis");
1099 const char *name = luaL_checkstring(L, 2);
1100 const char *type = luaL_checkstring(L, 3);
1101 const void *func = func_ref_new(L, 4);
1102 const char *help = luaL_optstring(L, 5, NULL);
1103 const char *names[] = { name, NULL };
1104 enum VisOption flags = 0;
1105 if (strcmp(type, "string") == 0)
1106 flags |= VIS_OPTION_TYPE_STRING;
1107 else if (strcmp(type, "number") == 0)
1108 flags |= VIS_OPTION_TYPE_NUMBER;
1109 else
1110 flags |= VIS_OPTION_TYPE_BOOL;
1111 bool ret = vis_option_register(vis, names, flags, option_lua, (void*)func, help);
1112 lua_pushboolean(L, ret);
1113 return 1;
1116 /***
1117 * Unregister a `:set` option.
1119 * @function option_unregister
1120 * @tparam string name the option name
1121 * @treturn bool whether the option was successfully unregistered
1123 static int option_unregister(lua_State *L) {
1124 Vis *vis = obj_ref_check(L, 1, "vis");
1125 const char *name = luaL_checkstring(L, 2);
1126 bool ret = vis_option_unregister(vis, name);
1127 lua_pushboolean(L, ret);
1128 return 1;
1131 static bool command_lua(Vis *vis, Win *win, void *data, bool force, const char *argv[], Cursor *cur, Filerange *range) {
1132 lua_State *L = vis->lua;
1133 if (!L || !func_ref_get(L, data))
1134 return false;
1135 lua_newtable(L);
1136 for (size_t i = 0; argv[i]; i++) {
1137 lua_pushunsigned(L, i);
1138 lua_pushstring(L, argv[i]);
1139 lua_settable(L, -3);
1141 lua_pushboolean(L, force);
1142 if (!obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW))
1143 return false;
1144 if (!cur)
1145 cur = view_cursors_primary_get(win->view);
1146 if (!obj_lightref_new(L, cur, VIS_LUA_TYPE_CURSOR))
1147 return false;
1148 pushrange(L, range);
1149 if (pcall(vis, L, 5, 1) != 0)
1150 return false;
1151 return lua_toboolean(L, -1);
1154 /***
1155 * Register a custom `:`-command.
1157 * @function command_register
1158 * @tparam string name the command name
1159 * @tparam function command the Lua function implementing the command
1160 * @tparam[opt] string help the single line help text as displayed in `:help`
1161 * @treturn bool whether the command has been successfully registered
1162 * @usage
1163 * vis:command_register("foo", function(argv, force, win, cursor, range)
1164 * for i,arg in ipairs(argv) do
1165 * print(i..": "..arg)
1166 * end
1167 * print("was command forced with ! "..(force and "yes" or "no"))
1168 * print(win.file.name)
1169 * print(cursor.pos)
1170 * print(range ~= nil and ('['..range.start..', '..range.finish..']') or "invalid range")
1171 * return true;
1172 * end)
1174 static int command_register(lua_State *L) {
1175 Vis *vis = obj_ref_check(L, 1, "vis");
1176 const char *name = luaL_checkstring(L, 2);
1177 const void *func = func_ref_new(L, 3);
1178 const char *help = luaL_optstring(L, 4, "");
1179 bool ret = vis_cmd_register(vis, name, help, (void*)func, command_lua);
1180 lua_pushboolean(L, ret);
1181 return 1;
1184 /***
1185 * Push keys to input queue and interpret them.
1187 * The keys are processed as if they were read from the keyboard.
1189 * @function feedkeys
1190 * @tparam string keys the keys to interpret
1192 static int feedkeys(lua_State *L) {
1193 Vis *vis = obj_ref_check(L, 1, "vis");
1194 const char *keys = luaL_checkstring(L, 2);
1195 vis_keys_feed(vis, keys);
1196 return 0;
1199 /***
1200 * Insert keys at all cursor positions of active window.
1202 * This function behaves as if the keys were entered in insert mode,
1203 * but in contrast to @{Vis:feedkeys} it bypasses the input queue,
1204 * meaning mappings do not apply and the keys will not be recorded in macros.
1206 * @function insert
1207 * @tparam string keys the keys to insert
1208 * @see Vis:feedkeys
1210 static int insert(lua_State *L) {
1211 Vis *vis = obj_ref_check(L, 1, "vis");
1212 size_t len;
1213 const char *keys = luaL_checklstring(L, 2, &len);
1214 vis_insert_key(vis, keys, len);
1215 return 0;
1218 /***
1219 * Replace keys at all cursor positions of active window.
1221 * This function behaves as if the keys were entered in replace mode,
1222 * but in contrast to @{Vis:feedkeys} it bypasses the input queue,
1223 * meaning mappings do not apply and the keys will not be recorded in macros.
1225 * @function replace
1226 * @tparam string keys the keys to insert
1227 * @see Vis:feedkeys
1229 static int replace(lua_State *L) {
1230 Vis *vis = obj_ref_check(L, 1, "vis");
1231 size_t len;
1232 const char *keys = luaL_checklstring(L, 2, &len);
1233 vis_replace_key(vis, keys, len);
1234 return 0;
1237 /***
1238 * Terminate editor process.
1240 * Termination happens upon the next iteration of the main event loop.
1241 * This means the calling Lua code will be executed further until it
1242 * eventually hands over control to the editor core. The exit status
1243 * of the most recent call is used.
1245 * All unsaved chanes will be lost!
1247 * @function exit
1248 * @tparam int code the exit status returned to the operating system
1250 static int exit_func(lua_State *L) {
1251 Vis *vis = obj_ref_check(L, 1, "vis");
1252 int code = luaL_checkint(L, 2);
1253 vis_exit(vis, code);
1254 return 0;
1257 /***
1258 * Pipe file range to external process and collect output.
1260 * The editor core will be blocked while the external process is running.
1262 * @function pipe
1263 * @tparam File file the file to which the range applies
1264 * @tparam Range range the range to pipe
1265 * @tparam string command the command to execute
1266 * @treturn int code the exit status of the executed command
1267 * @treturn string stdout the data written to stdout
1268 * @treturn string stderr the data written to stderr
1270 static int pipe_func(lua_State *L) {
1271 Vis *vis = obj_ref_check(L, 1, "vis");
1272 File *file = obj_ref_check(L, 2, VIS_LUA_TYPE_FILE);
1273 Filerange range = getrange(L, 3);
1274 const char *cmd = luaL_checkstring(L, 4);
1275 char *out = NULL, *err = NULL;
1276 int status = vis_pipe_collect(vis, file, &range, (const char*[]){ cmd, NULL }, &out, &err);
1277 lua_pushinteger(L, status);
1278 if (out)
1279 lua_pushstring(L, out);
1280 else
1281 lua_pushnil(L);
1282 free(out);
1283 if (err)
1284 lua_pushstring(L, err);
1285 else
1286 lua_pushnil(L);
1287 free(err);
1288 vis_draw(vis);
1289 return 3;
1291 /***
1292 * Currently active window.
1293 * @tfield Window win
1294 * @see windows
1296 /***
1297 * Currently active mode.
1298 * @tfield modes mode
1300 /***
1301 * Whether a macro is being recorded.
1302 * @tfield bool recording
1304 static int vis_index(lua_State *L) {
1305 Vis *vis = obj_ref_check(L, 1, "vis");
1307 if (lua_isstring(L, 2)) {
1308 const char *key = lua_tostring(L, 2);
1309 if (strcmp(key, "win") == 0) {
1310 if (vis->win)
1311 obj_ref_new(L, vis->win, VIS_LUA_TYPE_WINDOW);
1312 else
1313 lua_pushnil(L);
1314 return 1;
1317 if (strcmp(key, "mode") == 0) {
1318 lua_pushunsigned(L, vis->mode->id);
1319 return 1;
1322 if (strcmp(key, "recording") == 0) {
1323 lua_pushboolean(L, vis_macro_recording(vis));
1324 return 1;
1327 if (strcmp(key, "count") == 0) {
1328 int count = vis_count_get(vis);
1329 if (count == VIS_COUNT_UNKNOWN)
1330 lua_pushnil(L);
1331 else
1332 lua_pushunsigned(L, count);
1333 return 1;
1336 if (strcmp(key, "registers") == 0) {
1337 obj_ref_new(L, vis->ui, VIS_LUA_TYPE_REGISTERS);
1338 return 1;
1341 if (strcmp(key, "ui") == 0) {
1342 obj_ref_new(L, vis->ui, VIS_LUA_TYPE_UI);
1343 return 1;
1347 return index_common(L);
1350 static int vis_newindex(lua_State *L) {
1351 Vis *vis = obj_ref_check(L, 1, "vis");
1352 if (lua_isstring(L, 2)) {
1353 const char *key = lua_tostring(L, 2);
1354 if (strcmp(key, "mode") == 0) {
1355 enum VisMode mode = luaL_checkunsigned(L, 3);
1356 vis_mode_switch(vis, mode);
1357 return 0;
1360 if (strcmp(key, "count") == 0) {
1361 int count;
1362 if (lua_isnil(L, 3))
1363 count = VIS_COUNT_UNKNOWN;
1364 else
1365 count = luaL_checkunsigned(L, 3);
1366 vis_count_set(vis, count);
1367 return 0;
1370 if (strcmp(key, "win") == 0) {
1371 vis_window_focus(obj_ref_check(L, 3, VIS_LUA_TYPE_WINDOW));
1372 return 0;
1375 return newindex_common(L);
1378 static const struct luaL_Reg vis_lua[] = {
1379 { "files", files },
1380 { "windows", windows },
1381 { "mark_names", mark_names },
1382 { "register_names", register_names },
1383 { "command", command },
1384 { "info", info },
1385 { "message", message },
1386 { "map", map },
1387 { "operator", operator },
1388 { "operator_register", operator_register },
1389 { "motion", motion },
1390 { "motion_register", motion_register },
1391 { "textobject", textobject },
1392 { "textobject_register", textobject_register },
1393 { "option_register", option_register },
1394 { "option_unregister", option_unregister },
1395 { "command_register", command_register },
1396 { "feedkeys", feedkeys },
1397 { "insert", insert },
1398 { "replace", replace },
1399 { "action_register", action_register },
1400 { "exit", exit_func },
1401 { "pipe", pipe_func },
1402 { "__index", vis_index },
1403 { "__newindex", vis_newindex },
1404 { NULL, NULL },
1407 static const struct luaL_Reg ui_funcs[] = {
1408 { "__index", index_common },
1409 { NULL, NULL },
1412 static int registers_index(lua_State *L) {
1413 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
1414 const char *symbol = luaL_checkstring(L, 2);
1415 if (strlen(symbol) != 1)
1416 goto err;
1417 enum VisRegister reg = vis_register_from(vis, symbol[0]);
1418 if (reg >= VIS_REG_INVALID)
1419 goto err;
1420 size_t len;
1421 const char *value = vis_register_get(vis, reg, &len);
1422 lua_pushlstring(L, value ? value : "" , len);
1423 return 1;
1424 err:
1425 lua_pushnil(L);
1426 return 1;
1429 static int registers_newindex(lua_State *L) {
1430 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
1431 const char *symbol = luaL_checkstring(L, 2);
1432 if (strlen(symbol) != 1)
1433 return 0;
1434 enum VisRegister reg = vis_register_from(vis, symbol[0]);
1435 if (reg >= VIS_REG_INVALID)
1436 return 0;
1437 size_t len;
1438 const char *value = luaL_checklstring(L, 3, &len);
1439 register_put(vis, &vis->registers[reg], value, len+1);
1440 return 0;
1443 static int registers_len(lua_State *L) {
1444 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
1445 lua_pushunsigned(L, LENGTH(vis->registers));
1446 return 1;
1449 static const struct luaL_Reg registers_funcs[] = {
1450 { "__index", registers_index },
1451 { "__newindex", registers_newindex },
1452 { "__len", registers_len },
1453 { NULL, NULL },
1456 /***
1457 * A window object.
1458 * @type Window
1461 /***
1462 * Viewport currently being displayed.
1463 * @tfield Range viewport
1465 /***
1466 * The window width.
1467 * @tfield int width
1469 /***
1470 * The window height.
1471 * @tfield int height
1473 /***
1474 * The file being displayed in this window.
1475 * @tfield File file
1477 /***
1478 * The primary cursor of this window.
1479 * @tfield Cursor cursor
1481 /***
1482 * The cursors of this window.
1483 * @tfield Array(Cursor) cursors
1485 static int window_index(lua_State *L) {
1486 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1488 if (lua_isstring(L, 2)) {
1489 const char *key = lua_tostring(L, 2);
1491 if (strcmp(key, "viewport") == 0) {
1492 Filerange r = view_viewport_get(win->view);
1493 pushrange(L, &r);
1494 return 1;
1497 if (strcmp(key, "width") == 0) {
1498 lua_pushunsigned(L, vis_window_width_get(win));
1499 return 1;
1502 if (strcmp(key, "height") == 0) {
1503 lua_pushunsigned(L, vis_window_height_get(win));
1504 return 1;
1507 if (strcmp(key, "file") == 0) {
1508 obj_ref_new(L, win->file, VIS_LUA_TYPE_FILE);
1509 return 1;
1512 if (strcmp(key, "cursor") == 0) {
1513 Cursor *cur = view_cursors_primary_get(win->view);
1514 obj_lightref_new(L, cur, VIS_LUA_TYPE_CURSOR);
1515 return 1;
1518 if (strcmp(key, "cursors") == 0) {
1519 obj_ref_new(L, win->view, VIS_LUA_TYPE_CURSORS);
1520 return 1;
1524 return index_common(L);
1527 static int window_cursors_iterator_next(lua_State *L) {
1528 Cursor **handle = lua_touserdata(L, lua_upvalueindex(1));
1529 if (!*handle)
1530 return 0;
1531 Cursor *cur = obj_lightref_new(L, *handle, VIS_LUA_TYPE_CURSOR);
1532 if (!cur)
1533 return 0;
1534 *handle = view_cursors_next(cur);
1535 return 1;
1538 /***
1539 * Create an iterator over all cursors of this window.
1540 * @function cursors_iterator
1541 * @return the new iterator
1543 static int window_cursors_iterator(lua_State *L) {
1544 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1545 Cursor **handle = lua_newuserdata(L, sizeof *handle);
1546 *handle = view_cursors(win->view);
1547 lua_pushcclosure(L, window_cursors_iterator_next, 1);
1548 return 1;
1551 /***
1552 * Set up a window local key mapping.
1553 * The function signatures are the same as for @{Vis:map}.
1554 * @function map
1555 * @param ...
1556 * @see Vis:map
1558 static int window_map(lua_State *L) {
1559 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1560 return keymap(L, win->vis, win);
1563 /***
1564 * Define a display style.
1565 * @function style_define
1566 * @tparam int id the style id to use
1567 * @tparam string style the style definition
1568 * @treturn bool whether the style definition has been successfully
1569 * associated with the given id
1570 * @see style
1571 * @usage
1572 * win:style_define(win.STYLE_DEFAULT, "fore:red")
1574 static int window_style_define(lua_State *L) {
1575 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1576 enum UiStyle id = luaL_checkunsigned(L, 2);
1577 const char *style = luaL_checkstring(L, 3);
1578 bool ret = view_style_define(win->view, id, style);
1579 lua_pushboolean(L, ret);
1580 return 1;
1583 /***
1584 * Style a window range.
1586 * The style will be cleared after every window redraw.
1587 * @function style
1588 * @tparam int id the display style as registered with @{style_define}
1589 * @tparam int start the absolute file position in bytes
1590 * @tparam int len the length in bytes to style
1591 * @see style_define
1592 * @usage
1593 * win:style(win.STYLE_DEFAULT, 0, 10)
1595 static int window_style(lua_State *L) {
1596 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1597 enum UiStyle style = luaL_checkunsigned(L, 2);
1598 size_t start = checkpos(L, 3);
1599 size_t end = checkpos(L, 4);
1600 view_style(win->view, style, start, end);
1601 return 0;
1604 /***
1605 * Set window status line.
1607 * @function status
1608 * @tparam string left the left aligned part of the status line
1609 * @tparam[opt] string right the right aligned part of the status line
1611 static int window_status(lua_State *L) {
1612 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1613 char status[1024] = "";
1614 int width = vis_window_width_get(win);
1615 const char *left = luaL_checkstring(L, 2);
1616 const char *right = luaL_optstring(L, 3, "");
1617 int left_width = text_string_width(left, strlen(left));
1618 int right_width = text_string_width(right, strlen(right));
1619 int spaces = width - left_width - right_width;
1620 if (spaces < 1)
1621 spaces = 1;
1622 snprintf(status, sizeof(status)-1, "%s%*s%s", left, spaces, " ", right);
1623 vis_window_status(win, status);
1624 return 0;
1627 /***
1628 * Redraw window content.
1630 * @function draw
1632 static int window_draw(lua_State *L) {
1633 Win *win = obj_ref_check(L, 1, VIS_LUA_TYPE_WINDOW);
1634 view_draw(win->view);
1635 return 0;
1638 static const struct luaL_Reg window_funcs[] = {
1639 { "__index", window_index },
1640 { "__newindex", newindex_common },
1641 { "cursors_iterator", window_cursors_iterator },
1642 { "map", window_map },
1643 { "style_define", window_style_define },
1644 { "style", window_style },
1645 { "status", window_status },
1646 { "draw", window_draw },
1647 { NULL, NULL },
1650 static int window_cursors_index(lua_State *L) {
1651 View *view = obj_ref_check(L, 1, VIS_LUA_TYPE_CURSORS);
1652 size_t index = luaL_checkunsigned(L, 2);
1653 size_t count = view_cursors_count(view);
1654 if (index == 0 || index > count)
1655 goto err;
1656 for (Cursor *c = view_cursors(view); c; c = view_cursors_next(c)) {
1657 if (!--index) {
1658 obj_lightref_new(L, c, VIS_LUA_TYPE_CURSOR);
1659 return 1;
1662 err:
1663 lua_pushnil(L);
1664 return 1;
1667 static int window_cursors_len(lua_State *L) {
1668 View *view = obj_ref_check(L, 1, VIS_LUA_TYPE_CURSORS);
1669 lua_pushunsigned(L, view_cursors_count(view));
1670 return 1;
1673 static const struct luaL_Reg window_cursors_funcs[] = {
1674 { "__index", window_cursors_index },
1675 { "__len", window_cursors_len },
1676 { NULL, NULL },
1679 /***
1680 * A cursor object.
1682 * Cursors are represented as absolute byte offsets from the start of the file.
1683 * Valid cursor placements are within the closed interval `[0, file.size]`.
1684 * Cursors are currently implemented using character marks into the underlying
1685 * persistent [text management data structure](https://github.com/martanne/vis/wiki/Text-management-using-a-piece-chain).
1686 * This has a few consequences you should be aware of:
1688 * - A cursor becomes invalid when the underlying text range it is referencing
1689 * is deleted:
1691 * -- leaves cursor in an invalid state
1692 * win.file:delete(win.cursor.pos, 1)
1693 * assert(win.cursor.pos == nil)
1695 * Like a regular mark it will become valid again when the text is reverted
1696 * to the state before the deletion.
1698 * - Inserts after the cursor position (`> cursor.pos`) will not affect the
1699 * cursor postion.
1701 * local pos = win.cursor.pos
1702 * win.file:insert(pos+1, "-")
1703 * assert(win.cursor.pos == pos)
1705 * - Non-cached inserts before the cursor position (`<= cursor.pos`) will
1706 * affect the mark and adjust the cursor postion by the number of bytes
1707 * which were inserted.
1709 * local pos = win.cursor.pos
1710 * win.file:insert(pos, "-")
1711 * assert(win.cursor.pos == pos+1)
1713 * - Cached inserts before the cursor position (`<= cursor.pos`) will
1714 * not affect the cursor position because the underlying text is replaced
1715 * inplace.
1717 * For these reasons it is generally recommended to update the cursor position
1718 * after a modification. The general procedure amounts to:
1720 * 1. Read out the current cursor position
1721 * 2. Perform text modifications
1722 * 3. Update the cursor postion
1724 * This is what @{Vis:insert} and @{Vis:replace} do internally.
1726 * @type Cursor
1727 * @usage
1728 * local data = "new text"
1729 * local pos = win.cursor.pos
1730 * win.file:insert(pos, data)
1731 * win.cursor.pos = pos + #data
1734 /***
1735 * The zero based byte position in the file.
1737 * Might be `nil` if the cursor is in an invalid state.
1738 * Setting this field will move the cursor to the given position.
1739 * @tfield int pos
1741 /***
1742 * The 1-based line the cursor resides on.
1744 * @tfield int line
1745 * @see to
1747 /***
1748 * The 1-based column position the cursor resides on.
1749 * @tfield int col
1750 * @see to
1752 /***
1753 * The 1-based cursor index.
1754 * @tfield int number
1756 /***
1757 * The selection associated with this cursor.
1758 * @tfield Range selection the selection or `nil` if not in visual mode
1760 static int window_cursor_index(lua_State *L) {
1761 Cursor *cur = obj_lightref_check(L, 1, VIS_LUA_TYPE_CURSOR);
1762 if (!cur) {
1763 lua_pushnil(L);
1764 return 1;
1767 if (lua_isstring(L, 2)) {
1768 const char *key = lua_tostring(L, 2);
1769 if (strcmp(key, "pos") == 0) {
1770 pushpos(L, view_cursors_pos(cur));
1771 return 1;
1774 if (strcmp(key, "line") == 0) {
1775 lua_pushunsigned(L, view_cursors_line(cur));
1776 return 1;
1779 if (strcmp(key, "col") == 0) {
1780 lua_pushunsigned(L, view_cursors_col(cur));
1781 return 1;
1784 if (strcmp(key, "number") == 0) {
1785 lua_pushunsigned(L, view_cursors_number(cur)+1);
1786 return 1;
1789 if (strcmp(key, "selection") == 0) {
1790 Filerange sel = view_cursors_selection_get(cur);
1791 pushrange(L, &sel);
1792 return 1;
1796 return index_common(L);
1799 static int window_cursor_newindex(lua_State *L) {
1800 Cursor *cur = obj_lightref_check(L, 1, VIS_LUA_TYPE_CURSOR);
1801 if (!cur)
1802 return 0;
1803 if (lua_isstring(L, 2)) {
1804 const char *key = lua_tostring(L, 2);
1805 if (strcmp(key, "pos") == 0) {
1806 size_t pos = checkpos(L, 3);
1807 view_cursors_to(cur, pos);
1808 return 0;
1811 if (strcmp(key, "selection") == 0) {
1812 Filerange sel = getrange(L, 3);
1813 if (text_range_valid(&sel))
1814 view_cursors_selection_set(cur, &sel);
1815 else
1816 view_cursors_selection_clear(cur);
1817 return 0;
1820 return newindex_common(L);
1823 /***
1824 * Move cursor.
1825 * @function to
1826 * @tparam int line the 1-based line number
1827 * @tparam int col the 1-based column number
1829 static int window_cursor_to(lua_State *L) {
1830 Cursor *cur = obj_lightref_check(L, 1, VIS_LUA_TYPE_CURSOR);
1831 if (cur) {
1832 size_t line = checkpos(L, 2);
1833 size_t col = checkpos(L, 3);
1834 view_cursors_place(cur, line, col);
1836 return 0;
1839 static const struct luaL_Reg window_cursor_funcs[] = {
1840 { "__index", window_cursor_index },
1841 { "__newindex", window_cursor_newindex },
1842 { "to", window_cursor_to },
1843 { NULL, NULL },
1846 /***
1847 * A file object.
1848 * @type File
1850 /***
1851 * File name.
1852 * @tfield string name the file name relative to current working directory or `nil` if not yet named
1854 /***
1855 * File path.
1856 * @tfield string path the absolute file path or `nil` if not yet named
1858 /***
1859 * File content by logical lines.
1861 * Assigning to array element `0` (`#lines+1`) will insert a new line at
1862 * the beginning (end) of the file.
1863 * @tfield Array(string) lines the file content accessible as 1-based array
1864 * @see content
1865 * @usage
1866 * local lines = vis.win.file.lines
1867 * for i=1, #lines do
1868 * lines[i] = i .. ": " .. lines[i]
1869 * end
1871 /***
1872 * File size in bytes.
1873 * @tfield int size the current file size in bytes
1875 /***
1876 * File state.
1877 * @tfield bool modified whether the file contains unsaved changes
1879 /***
1880 * File marks.
1881 * @field marks array to access the marks of this file by single letter name
1883 static int file_index(lua_State *L) {
1884 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
1886 if (lua_isstring(L, 2)) {
1887 const char *key = lua_tostring(L, 2);
1888 if (strcmp(key, "name") == 0) {
1889 lua_pushstring(L, file_name_get(file));
1890 return 1;
1893 if (strcmp(key, "path") == 0) {
1894 lua_pushstring(L, file->name);
1895 return 1;
1898 if (strcmp(key, "lines") == 0) {
1899 obj_ref_new(L, file->text, VIS_LUA_TYPE_TEXT);
1900 return 1;
1903 if (strcmp(key, "size") == 0) {
1904 lua_pushunsigned(L, text_size(file->text));
1905 return 1;
1908 if (strcmp(key, "modified") == 0) {
1909 lua_pushboolean(L, text_modified(file->text));
1910 return 1;
1913 if (strcmp(key, "marks") == 0) {
1914 obj_ref_new(L, file->marks, VIS_LUA_TYPE_MARKS);
1915 return 1;
1919 return index_common(L);
1922 /***
1923 * Insert data at position.
1924 * @function insert
1925 * @tparam int pos the 0-based file position in bytes
1926 * @tparam string data the data to insert
1927 * @treturn bool whether the file content was successfully changed
1929 static int file_insert(lua_State *L) {
1930 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
1931 size_t pos = checkpos(L, 2);
1932 size_t len;
1933 luaL_checkstring(L, 3);
1934 const char *data = lua_tolstring(L, 3, &len);
1935 lua_pushboolean(L, text_insert(file->text, pos, data, len));
1936 return 1;
1939 /***
1940 * Delete data at position.
1942 * @function delete
1943 * @tparam int pos the 0-based file position in bytes
1944 * @tparam int len the length in bytes to delete
1945 * @treturn bool whether the file content was successfully changed
1947 /***
1948 * Delete file range.
1950 * @function delete
1951 * @tparam Range range the range to delete
1952 * @treturn bool whether the file content was successfully changed
1954 static int file_delete(lua_State *L) {
1955 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
1956 Filerange range = getrange(L, 2);
1957 lua_pushboolean(L, text_delete_range(file->text, &range));
1958 return 1;
1961 /***
1962 * Create an iterator over all lines of the file.
1964 * For large files this is probably faster than @{lines}.
1965 * @function lines_iterator
1966 * @return the new iterator
1967 * @see lines
1968 * @usage
1969 * for line in file:lines_iterator() do
1970 * -- do something with line
1971 * end
1973 static int file_lines_iterator_it(lua_State *L);
1974 static int file_lines_iterator(lua_State *L) {
1975 /* need to check second parameter first, because obj_ref_check_get
1976 * modifies the stack */
1977 size_t line = luaL_optunsigned(L, 2, 1);
1978 File *file = obj_ref_check_get(L, 1, VIS_LUA_TYPE_FILE);
1979 size_t *pos = lua_newuserdata(L, sizeof *pos);
1980 *pos = text_pos_by_lineno(file->text, line);
1981 lua_pushcclosure(L, file_lines_iterator_it, 2);
1982 return 1;
1985 static int file_lines_iterator_it(lua_State *L) {
1986 File *file = *(File**)lua_touserdata(L, lua_upvalueindex(1));
1987 size_t *start = lua_touserdata(L, lua_upvalueindex(2));
1988 if (*start == text_size(file->text))
1989 return 0;
1990 size_t end = text_line_end(file->text, *start);
1991 size_t len = end - *start;
1992 char *buf = malloc(len);
1993 if (!buf && len)
1994 return 0;
1995 len = text_bytes_get(file->text, *start, len, buf);
1996 lua_pushlstring(L, buf, len);
1997 free(buf);
1998 *start = text_line_next(file->text, end);
1999 return 1;
2002 /***
2003 * Get file content of position and length.
2005 * @function content
2006 * @tparam int pos the 0-based file position in bytes
2007 * @tparam int len the length in bytes to read
2008 * @treturn string the file content corresponding to the range
2009 * @see lines
2010 * @usage
2011 * local file = vis.win.file
2012 * local text = file:content(0, file.size)
2014 /***
2015 * Get file content of range.
2017 * @function content
2018 * @tparam Range range the range to read
2019 * @treturn string the file content corresponding to the range
2021 static int file_content(lua_State *L) {
2022 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
2023 Filerange range = getrange(L, 2);
2024 if (!text_range_valid(&range))
2025 goto err;
2026 size_t len = text_range_size(&range);
2027 char *data = malloc(len);
2028 if (!data)
2029 goto err;
2030 len = text_bytes_get(file->text, range.start, len, data);
2031 lua_pushlstring(L, data, len);
2032 free(data);
2033 return 1;
2034 err:
2035 lua_pushnil(L);
2036 return 1;
2039 /***
2040 * Set mark.
2041 * @function mark_set
2042 * @tparam int pos the position to set the mark to, must be in [0, file.size]
2043 * @treturn Mark mark the mark which can be looked up later
2045 static int file_mark_set(lua_State *L) {
2046 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
2047 size_t pos = checkpos(L, 2);
2048 Mark mark = text_mark_set(file->text, pos);
2049 if (mark)
2050 obj_lightref_new(L, (void*)mark, VIS_LUA_TYPE_MARK);
2051 else
2052 lua_pushnil(L);
2053 return 1;
2056 /***
2057 * Get position of mark.
2058 * @function mark_get
2059 * @tparam Mark mark the mark to look up
2060 * @treturn int pos the position of the mark, or `nil` if invalid
2062 static int file_mark_get(lua_State *L) {
2063 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
2064 Mark mark = (Mark)obj_lightref_check(L, 2, VIS_LUA_TYPE_MARK);
2065 size_t pos = text_mark_get(file->text, mark);
2066 if (pos == EPOS)
2067 lua_pushnil(L);
2068 else
2069 lua_pushunsigned(L, pos);
2070 return 1;
2073 /***
2074 * Word text object.
2076 * @function text_object_word
2077 * @tparam int pos the position which must be part of the word
2078 * @treturn Range range the range
2081 static int file_text_object(lua_State *L) {
2082 Filerange range = text_range_empty();
2083 File *file = obj_ref_check(L, 1, VIS_LUA_TYPE_FILE);
2084 size_t pos = checkpos(L, 2);
2085 size_t idx = lua_tointeger(L, lua_upvalueindex(1));
2086 if (idx < LENGTH(vis_textobjects)) {
2087 const TextObject *txtobj = &vis_textobjects[idx];
2088 if (txtobj->txt)
2089 range = txtobj->txt(file->text, pos);
2091 pushrange(L, &range);
2092 return 1;
2095 static const struct luaL_Reg file_funcs[] = {
2096 { "__index", file_index },
2097 { "__newindex", newindex_common },
2098 { "insert", file_insert },
2099 { "delete", file_delete },
2100 { "lines_iterator", file_lines_iterator },
2101 { "content", file_content },
2102 { "mark_set", file_mark_set },
2103 { "mark_get", file_mark_get },
2104 { NULL, NULL },
2107 static int file_lines_index(lua_State *L) {
2108 Text *txt = obj_ref_check(L, 1, VIS_LUA_TYPE_TEXT);
2109 size_t line = luaL_checkunsigned(L, 2);
2110 size_t start = text_pos_by_lineno(txt, line);
2111 size_t end = text_line_end(txt, start);
2112 if (start != EPOS && end != EPOS) {
2113 size_t size = end - start;
2114 char *data = malloc(size);
2115 if (!data && size)
2116 goto err;
2117 size = text_bytes_get(txt, start, size, data);
2118 lua_pushlstring(L, data, size);
2119 free(data);
2120 return 1;
2122 err:
2123 lua_pushnil(L);
2124 return 1;
2127 static int file_lines_newindex(lua_State *L) {
2128 Text *txt = obj_ref_check(L, 1, VIS_LUA_TYPE_TEXT);
2129 size_t line = luaL_checkunsigned(L, 2);
2130 size_t size;
2131 const char *data = luaL_checklstring(L, 3, &size);
2132 if (line == 0) {
2133 text_insert(txt, 0, data, size);
2134 text_insert_newline(txt, size);
2135 return 0;
2137 size_t start = text_pos_by_lineno(txt, line);
2138 size_t end = text_line_end(txt, start);
2139 if (start != EPOS && end != EPOS) {
2140 text_delete(txt, start, end - start);
2141 text_insert(txt, start, data, size);
2142 if (text_size(txt) == start + size)
2143 text_insert_newline(txt, text_size(txt));
2145 return 0;
2148 static int file_lines_len(lua_State *L) {
2149 Text *txt = obj_ref_check(L, 1, VIS_LUA_TYPE_TEXT);
2150 size_t lines = 0;
2151 char lastchar;
2152 size_t size = text_size(txt);
2153 if (size > 0)
2154 lines = text_lineno_by_pos(txt, size);
2155 if (lines > 1 && text_byte_get(txt, size-1, &lastchar) && lastchar == '\n')
2156 lines--;
2157 lua_pushunsigned(L, lines);
2158 return 1;
2161 static const struct luaL_Reg file_lines_funcs[] = {
2162 { "__index", file_lines_index },
2163 { "__newindex", file_lines_newindex },
2164 { "__len", file_lines_len },
2165 { NULL, NULL },
2168 static int file_marks_index(lua_State *L) {
2169 size_t pos = EPOS;
2170 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
2171 File *file = obj_ref_check_containerof(L, 1, VIS_LUA_TYPE_MARKS, offsetof(File, marks));
2172 if (!file)
2173 goto err;
2174 const char *symbol = luaL_checkstring(L, 2);
2175 if (strlen(symbol) != 1)
2176 goto err;
2177 enum VisMark mark = vis_mark_from(vis, symbol[0]);
2178 if (mark == VIS_MARK_INVALID)
2179 goto err;
2180 pos = text_mark_get(file->text, file->marks[mark]);
2181 err:
2182 pushpos(L, pos);
2183 return 1;
2186 static int file_marks_newindex(lua_State *L) {
2187 Vis *vis = lua_touserdata(L, lua_upvalueindex(1));
2188 File *file = obj_ref_check_containerof(L, 1, VIS_LUA_TYPE_MARKS, offsetof(File, marks));
2189 if (!file)
2190 return 0;
2191 const char *symbol = luaL_checkstring(L, 2);
2192 if (strlen(symbol) != 1)
2193 return 0;
2194 enum VisMark mark = vis_mark_from(vis, symbol[0]);
2195 size_t pos = luaL_checkunsigned(L, 3);
2196 if (mark < LENGTH(file->marks))
2197 file->marks[mark] = text_mark_set(file->text, pos);
2198 return 0;
2201 static int file_marks_len(lua_State *L) {
2202 File *file = obj_ref_check_containerof(L, 1, VIS_LUA_TYPE_MARKS, offsetof(File, marks));
2203 lua_pushunsigned(L, file ? LENGTH(file->marks) : 0);
2204 return 1;
2207 static const struct luaL_Reg file_marks_funcs[] = {
2208 { "__index", file_marks_index },
2209 { "__newindex", file_marks_newindex },
2210 { "__len", file_marks_len },
2211 { NULL, NULL },
2214 /***
2215 * The user interface.
2217 * @type Ui
2219 /***
2220 * Number of available colors.
2221 * @tfield int colors
2224 /***
2225 * A file range.
2227 * For a valid range `start <= finish` holds.
2228 * An invalid range is represented as `nil`.
2229 * @type Range
2231 /***
2232 * The being of the range.
2233 * @tfield int start
2235 /***
2236 * The end of the range.
2237 * @tfield int finish
2240 /***
2241 * Modes.
2242 * @section Modes
2245 /***
2246 * Mode constants.
2247 * @table modes
2248 * @tfield int NORMAL
2249 * @tfield int OPERATOR_PENDING
2250 * @tfield int INSERT
2251 * @tfield int REPLACE
2252 * @tfield int VISUAL
2253 * @tfield int VISUAL_LINE
2254 * @see Vis:map
2255 * @see Window:map
2258 /***
2259 * Key Handling.
2261 * This section describes the contract between the editor core and Lua
2262 * key handling functions mapped to symbolic keys using either @{Vis:map}
2263 * or @{Window:map}.
2265 * @section Key_Handling
2268 /***
2269 * Example of a key handling function.
2271 * The keyhandler is invoked with the pending content of the input queue
2272 * given as argument. This might be the empty string if no further input
2273 * is available.
2275 * The function is expected to return the number of *bytes* it has
2276 * consumed from the passed input keys. A negative return value is
2277 * interpreted as an indication that not enough input was available. The
2278 * function will be called again once the user has provided more input. A
2279 * missing return value (i.e. `nil`) is interpreted as zero, meaning
2280 * no further input was consumed but the function completed successfully.
2282 * @function keyhandler
2283 * @tparam string keys the keys following the mapping
2284 * @treturn int the number of *bytes* being consumed by the function (see above)
2285 * @see Vis:action_register
2286 * @see Vis:map
2287 * @see Window:map
2288 * @usage
2289 * vis:map(vis.modes.INSERT, "<C-k>", function(keys)
2290 * if #keys < 2 then
2291 * return -1 -- need more input
2292 * end
2293 * local digraph = keys:sub(1, 2)
2294 * if digraph == "l*" then
2295 * vis:feedkeys('λ')
2296 * return 2 -- consume 2 bytes of input
2297 * end
2298 * end, "Insert digraph")
2301 /***
2302 * Core Events.
2304 * These events are invoked from the editor core.
2305 * The following functions are invoked if they are registered in the
2306 * `vis.events` table. Users scripts should generally use the [Events](#events)
2307 * mechanism instead which multiplexes these core events.
2309 * @section Core_Events
2312 static void vis_lua_event_get(lua_State *L, const char *name) {
2313 lua_getglobal(L, "vis");
2314 lua_getfield(L, -1, "events");
2315 if (lua_istable(L, -1)) {
2316 lua_getfield(L, -1, name);
2318 lua_remove(L, -2);
2321 static void vis_lua_event_call(Vis *vis, const char *name) {
2322 lua_State *L = vis->lua;
2323 vis_lua_event_get(L, name);
2324 if (lua_isfunction(L, -1))
2325 pcall(vis, L, 0, 0);
2326 lua_pop(L, 1);
2329 static bool vis_lua_path_strip(Vis *vis) {
2330 lua_State *L = vis->lua;
2331 lua_getglobal(L, "package");
2333 for (const char **var = (const char*[]){ "path", "cpath", NULL }; *var; var++) {
2335 lua_getfield(L, -1, *var);
2336 const char *path = lua_tostring(L, -1);
2337 lua_pop(L, 1);
2338 if (!path)
2339 return false;
2341 char *copy = strdup(path), *stripped = calloc(1, strlen(path)+2);
2342 if (!copy || !stripped) {
2343 free(copy);
2344 free(stripped);
2345 return false;
2348 for (char *elem = copy, *stripped_elem = stripped, *next; elem; elem = next) {
2349 if ((next = strstr(elem, ";")))
2350 *next++ = '\0';
2351 if (strstr(elem, "./"))
2352 continue; /* skip relative path entries */
2353 stripped_elem += sprintf(stripped_elem, "%s;", elem);
2356 lua_pushstring(L, stripped);
2357 lua_setfield(L, -2, *var);
2359 free(copy);
2360 free(stripped);
2363 lua_pop(L, 1); /* package */
2364 return true;
2367 bool vis_lua_path_add(Vis *vis, const char *path) {
2368 lua_State *L = vis->lua;
2369 if (!L || !path)
2370 return false;
2371 lua_getglobal(L, "package");
2372 lua_pushstring(L, path);
2373 lua_pushstring(L, "/?.lua;");
2374 lua_getfield(L, -3, "path");
2375 lua_concat(L, 3);
2376 lua_setfield(L, -2, "path");
2377 lua_pop(L, 1); /* package */
2378 return true;
2381 bool vis_lua_paths_get(Vis *vis, char **lpath, char **cpath) {
2382 lua_State *L = vis->lua;
2383 if (!L)
2384 return false;
2385 const char *s;
2386 lua_getglobal(L, "package");
2387 lua_getfield(L, -1, "path");
2388 s = lua_tostring(L, -1);
2389 *lpath = s ? strdup(s) : NULL;
2390 lua_getfield(L, -2, "cpath");
2391 s = lua_tostring(L, -1);
2392 *cpath = s ? strdup(s) : NULL;
2393 return true;
2396 static bool package_exist(Vis *vis, lua_State *L, const char *name) {
2397 const char lua[] =
2398 "local name = ...\n"
2399 "for _, searcher in ipairs(package.searchers or package.loaders) do\n"
2400 "local loader = searcher(name)\n"
2401 "if type(loader) == 'function' then\n"
2402 "return true\n"
2403 "end\n"
2404 "end\n"
2405 "return false\n";
2406 if (luaL_loadstring(L, lua) != LUA_OK)
2407 return false;
2408 lua_pushstring(L, name);
2409 /* an error indicates package exists */
2410 bool ret = lua_pcall(L, 1, 1, 0) != LUA_OK || lua_toboolean(L, -1);
2411 lua_pop(L, 1);
2412 return ret;
2415 static void *alloc_lua(void *ud, void *ptr, size_t osize, size_t nsize) {
2416 if (nsize == 0) {
2417 free(ptr);
2418 return NULL;
2419 } else {
2420 return realloc(ptr, nsize);
2424 /***
2425 * Editor initialization completed.
2426 * This event is emitted immediately after `visrc.lua` has been sourced, but
2427 * before any other events have occured, in particular the command line arguments
2428 * have not yet been processed.
2430 * Can be used to set *global* configuration options.
2431 * @function init
2433 void vis_lua_init(Vis *vis) {
2434 lua_State *L = lua_newstate(alloc_lua, vis);
2435 if (!L)
2436 return;
2437 vis->lua = L;
2438 lua_atpanic(L, &panic_handler);
2440 luaL_openlibs(L);
2442 #if CONFIG_LPEG
2443 extern int luaopen_lpeg(lua_State *L);
2444 lua_getglobal(L, "package");
2445 lua_getfield(L, -1, "preload");
2446 lua_pushcfunction(L, luaopen_lpeg);
2447 lua_setfield(L, -2, "lpeg");
2448 lua_pop(L, 2);
2449 #endif
2451 /* remove any relative paths from lua's default package.path */
2452 vis_lua_path_strip(vis);
2454 /* extends lua's package.path with:
2455 * - $VIS_PATH
2456 * - ./lua (relative path to the binary location)
2457 * - $XDG_CONFIG_HOME/vis (defaulting to $HOME/.config/vis)
2458 * - /etc/vis (for system-wide configuration provided by administrator)
2459 * - /usr/(local/)?share/vis (or whatever is specified during ./configure)
2460 * - package.path (standard lua search path)
2462 char path[PATH_MAX];
2464 vis_lua_path_add(vis, VIS_PATH);
2466 /* try to get users home directory */
2467 const char *home = getenv("HOME");
2468 if (!home || !*home) {
2469 struct passwd *pw = getpwuid(getuid());
2470 if (pw)
2471 home = pw->pw_dir;
2474 vis_lua_path_add(vis, "/etc/vis");
2476 const char *xdg_config = getenv("XDG_CONFIG_HOME");
2477 if (xdg_config) {
2478 snprintf(path, sizeof path, "%s/vis", xdg_config);
2479 vis_lua_path_add(vis, path);
2480 } else if (home && *home) {
2481 snprintf(path, sizeof path, "%s/.config/vis", home);
2482 vis_lua_path_add(vis, path);
2485 ssize_t len = readlink("/proc/self/exe", path, sizeof(path)-1);
2486 if (len > 0) {
2487 path[len] = '\0';
2488 /* some idotic dirname(3) implementations return pointers to statically
2489 * allocated memory, hence we use memmove to copy it back */
2490 char *dir = dirname(path);
2491 if (dir) {
2492 size_t len = strlen(dir)+1;
2493 if (len < sizeof(path) - sizeof("/lua")) {
2494 memmove(path, dir, len);
2495 strcat(path, "/lua");
2496 vis_lua_path_add(vis, path);
2501 vis_lua_path_add(vis, getenv("VIS_PATH"));
2503 /* table in registry to lookup object type, stores metatable -> type mapping */
2504 lua_newtable(L);
2505 lua_setfield(L, LUA_REGISTRYINDEX, "vis.types");
2506 /* table in registry to track lifetimes of C objects */
2507 lua_newtable(L);
2508 lua_setfield(L, LUA_REGISTRYINDEX, "vis.objects");
2509 /* table in registry to store references to Lua functions */
2510 lua_newtable(L);
2511 lua_setfield(L, LUA_REGISTRYINDEX, "vis.functions");
2512 /* metatable used to type check user data */
2513 obj_type_new(L, VIS_LUA_TYPE_VIS);
2514 luaL_setfuncs(L, vis_lua, 0);
2515 lua_newtable(L);
2516 lua_setfield(L, -2, "types");
2517 /* create reference to main vis object, such that the further
2518 * calls to obj_type_new can register the type meta tables in
2519 * vis.types[name] */
2520 obj_ref_new(L, vis, "vis");
2521 lua_setglobal(L, "vis");
2523 obj_type_new(L, VIS_LUA_TYPE_FILE);
2525 const struct {
2526 enum VisTextObject id;
2527 const char *name;
2528 } textobjects[] = {
2529 { VIS_TEXTOBJECT_INNER_WORD, "text_object_word" },
2532 for (size_t i = 0; i < LENGTH(textobjects); i++) {
2533 lua_pushunsigned(L, textobjects[i].id);
2534 lua_pushcclosure(L, file_text_object, 1);
2535 lua_setfield(L, -2, textobjects[i].name);
2538 luaL_setfuncs(L, file_funcs, 0);
2540 obj_type_new(L, VIS_LUA_TYPE_TEXT);
2541 luaL_setfuncs(L, file_lines_funcs, 0);
2542 obj_type_new(L, VIS_LUA_TYPE_WINDOW);
2543 luaL_setfuncs(L, window_funcs, 0);
2545 const struct {
2546 enum UiStyle id;
2547 const char *name;
2548 } styles[] = {
2549 { UI_STYLE_DEFAULT, "STYLE_DEFAULT" },
2550 { UI_STYLE_CURSOR, "STYLE_CURSOR" },
2551 { UI_STYLE_CURSOR_PRIMARY, "STYLE_CURSOR_PRIMARY" },
2552 { UI_STYLE_CURSOR_LINE, "STYLE_CURSOR_LINE" },
2553 { UI_STYLE_SELECTION, "STYLE_SELECTION" },
2554 { UI_STYLE_LINENUMBER, "STYLE_LINENUMBER" },
2555 { UI_STYLE_COLOR_COLUMN, "STYLE_COLOR_COLUMN" },
2556 { UI_STYLE_STATUS, "STYLE_STATUS" },
2557 { UI_STYLE_STATUS_FOCUSED, "STYLE_STATUS_FOCUSED" },
2558 { UI_STYLE_SEPARATOR, "STYLE_SEPARATOR" },
2559 { UI_STYLE_INFO, "STYLE_INFO" },
2560 { UI_STYLE_EOF, "STYLE_EOF" },
2563 for (size_t i = 0; i < LENGTH(styles); i++) {
2564 lua_pushunsigned(L, styles[i].id);
2565 lua_setfield(L, -2, styles[i].name);
2568 obj_type_new(L, VIS_LUA_TYPE_MARK);
2569 obj_type_new(L, VIS_LUA_TYPE_MARKS);
2570 lua_pushlightuserdata(L, vis);
2571 luaL_setfuncs(L, file_marks_funcs, 1);
2573 obj_type_new(L, VIS_LUA_TYPE_CURSOR);
2574 luaL_setfuncs(L, window_cursor_funcs, 0);
2575 obj_type_new(L, VIS_LUA_TYPE_CURSORS);
2576 luaL_setfuncs(L, window_cursors_funcs, 0);
2578 obj_type_new(L, VIS_LUA_TYPE_UI);
2579 luaL_setfuncs(L, ui_funcs, 0);
2580 lua_pushunsigned(L, vis->ui->colors(vis->ui));
2581 lua_setfield(L, -2, "colors");
2583 obj_type_new(L, VIS_LUA_TYPE_REGISTERS);
2584 lua_pushlightuserdata(L, vis);
2585 luaL_setfuncs(L, registers_funcs, 1);
2587 obj_type_new(L, VIS_LUA_TYPE_KEYACTION);
2589 lua_getglobal(L, "vis");
2590 lua_getmetatable(L, -1);
2592 lua_pushstring(L, VERSION);
2593 lua_setfield(L, -2, "VERSION");
2595 lua_newtable(L);
2597 static const struct {
2598 enum VisMode id;
2599 const char *name;
2600 } modes[] = {
2601 { VIS_MODE_NORMAL, "NORMAL" },
2602 { VIS_MODE_OPERATOR_PENDING, "OPERATOR_PENDING" },
2603 { VIS_MODE_VISUAL, "VISUAL" },
2604 { VIS_MODE_VISUAL_LINE, "VISUAL_LINE" },
2605 { VIS_MODE_INSERT, "INSERT" },
2606 { VIS_MODE_REPLACE, "REPLACE" },
2609 for (size_t i = 0; i < LENGTH(modes); i++) {
2610 lua_pushunsigned(L, modes[i].id);
2611 lua_setfield(L, -2, modes[i].name);
2614 lua_setfield(L, -2, "modes");
2616 if (!package_exist(vis, L, "visrc")) {
2617 vis_info_show(vis, "WARNING: failed to load visrc.lua");
2618 } else {
2619 lua_getglobal(L, "require");
2620 lua_pushstring(L, "visrc");
2621 pcall(vis, L, 1, 0);
2622 vis_lua_event_call(vis, "init");
2626 /***
2627 * Editor startup completed.
2628 * This event is emitted immediately before the main loop starts.
2629 * At this point all files are loaded and corresponding windows are created.
2630 * We are about to process interactive keyboard input.
2631 * @function start
2633 void vis_lua_start(Vis *vis) {
2634 vis_lua_event_call(vis, "start");
2638 * Editor is about to terminate.
2639 * @function quit
2641 void vis_lua_quit(Vis *vis) {
2642 if (!vis->lua)
2643 return;
2644 vis_lua_event_call(vis, "quit");
2645 lua_close(vis->lua);
2646 vis->lua = NULL;
2649 /***
2650 * Input key event in either input or replace mode.
2651 * @function input
2652 * @tparam string key
2653 * @treturn bool whether the key was cosumed or not
2655 static bool vis_lua_input(Vis *vis, const char *key, size_t len) {
2656 lua_State *L = vis->lua;
2657 if (!L || vis->win->file->internal)
2658 return false;
2659 bool ret = false;
2660 vis_lua_event_get(L, "input");
2661 if (lua_isfunction(L, -1)) {
2662 lua_pushlstring(L, key, len);
2663 if (pcall(vis, L, 1, 1) == 0) {
2664 ret = lua_isboolean(L, -1) && lua_toboolean(L, -1);
2665 lua_pop(L, 1);
2668 lua_pop(L, 1);
2669 return ret;
2672 void vis_lua_mode_insert_input(Vis *vis, const char *key, size_t len) {
2673 if (!vis_lua_input(vis, key, len))
2674 vis_insert_key(vis, key, len);
2677 void vis_lua_mode_replace_input(Vis *vis, const char *key, size_t len) {
2678 if (!vis_lua_input(vis, key, len))
2679 vis_replace_key(vis, key, len);
2682 /***
2683 * File open.
2684 * @function file_open
2685 * @tparam File file the file to be opened
2687 void vis_lua_file_open(Vis *vis, File *file) {
2688 debug("event: file-open: %s %p %p\n", file->name ? file->name : "unnamed", (void*)file, (void*)file->text);
2689 lua_State *L = vis->lua;
2690 if (!L)
2691 return;
2692 vis_lua_event_get(L, "file_open");
2693 if (lua_isfunction(L, -1)) {
2694 obj_ref_new(L, file, VIS_LUA_TYPE_FILE);
2695 pcall(vis, L, 1, 0);
2697 lua_pop(L, 1);
2700 /***
2701 * File pre save.
2702 * Triggered *before* the file is being written.
2703 * @function file_save_pre
2704 * @tparam File file the file being written
2705 * @tparam string path the absolute path to which the file will be written, `nil` if standard output
2706 * @treturn bool whether the write operation should be proceeded
2708 bool vis_lua_file_save_pre(Vis *vis, File *file, const char *path) {
2709 lua_State *L = vis->lua;
2710 if (!L)
2711 return true;
2712 vis_lua_event_get(L, "file_save_pre");
2713 if (lua_isfunction(L, -1)) {
2714 obj_ref_new(L, file, VIS_LUA_TYPE_FILE);
2715 lua_pushstring(L, path);
2716 if (pcall(vis, L, 2, 1) != 0)
2717 return false;
2718 return !lua_isboolean(L, -1) || lua_toboolean(L, -1);
2720 lua_pop(L, 1);
2721 return true;
2724 /***
2725 * File post save.
2726 * Triggered *after* a successfull write operation.
2727 * @function file_save_post
2728 * @tparam File file the file which was written
2729 * @tparam string path the absolute path to which it was written, `nil` if standard output
2731 void vis_lua_file_save_post(Vis *vis, File *file, const char *path) {
2732 lua_State *L = vis->lua;
2733 if (!L)
2734 return;
2735 vis_lua_event_get(L, "file_save_post");
2736 if (lua_isfunction(L, -1)) {
2737 obj_ref_new(L, file, VIS_LUA_TYPE_FILE);
2738 lua_pushstring(L, path);
2739 pcall(vis, L, 2, 0);
2741 lua_pop(L, 1);
2744 /***
2745 * File close.
2746 * The last window displaying the file has been closed.
2747 * @function file_close
2748 * @tparam File file the file being closed
2750 void vis_lua_file_close(Vis *vis, File *file) {
2751 debug("event: file-close: %s %p %p\n", file->name ? file->name : "unnamed", (void*)file, (void*)file->text);
2752 lua_State *L = vis->lua;
2753 if (!L)
2754 return;
2755 vis_lua_event_get(L, "file_close");
2756 if (lua_isfunction(L, -1)) {
2757 obj_ref_new(L, file, VIS_LUA_TYPE_FILE);
2758 pcall(vis, L, 1, 0);
2760 obj_ref_free(L, file->marks);
2761 obj_ref_free(L, file->text);
2762 obj_ref_free(L, file);
2763 lua_pop(L, 1);
2766 /***
2767 * Window open.
2768 * A new window has been created.
2769 * @function win_open
2770 * @tparam Window win the window being opened
2772 void vis_lua_win_open(Vis *vis, Win *win) {
2773 debug("event: win-open: %s %p %p\n", win->file->name ? win->file->name : "unnamed", (void*)win, (void*)win->view);
2774 lua_State *L = vis->lua;
2775 if (!L)
2776 return;
2777 vis_lua_event_get(L, "win_open");
2778 if (lua_isfunction(L, -1)) {
2779 obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW);
2780 pcall(vis, L, 1, 0);
2782 lua_pop(L, 1);
2785 /***
2786 * Window close.
2787 * An window is being closed.
2788 * @function win_close
2789 * @tparam Window win the window being closed
2791 void vis_lua_win_close(Vis *vis, Win *win) {
2792 debug("event: win-close: %s %p %p\n", win->file->name ? win->file->name : "unnamed", (void*)win, (void*)win->view);
2793 lua_State *L = vis->lua;
2794 if (!L)
2795 return;
2796 vis_lua_event_get(L, "win_close");
2797 if (lua_isfunction(L, -1)) {
2798 obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW);
2799 pcall(vis, L, 1, 0);
2801 obj_ref_free(L, win->view);
2802 obj_ref_free(L, win);
2803 lua_pop(L, 1);
2807 * Window highlight.
2808 * The window has been redrawn and the syntax highlighting needs to be performed.
2809 * @function win_highlight
2810 * @tparam Window win the window being redrawn
2811 * @see style
2813 void vis_lua_win_highlight(Vis *vis, Win *win) {
2814 lua_State *L = vis->lua;
2815 if (!L)
2816 return;
2817 vis_lua_event_get(L, "win_highlight");
2818 if (lua_isfunction(L, -1)) {
2819 obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW);
2820 pcall(vis, L, 1, 0);
2822 lua_pop(L, 1);
2825 /***
2826 * Window status bar redraw.
2827 * @function win_status
2828 * @tparam Window win the affected window
2829 * @see status
2831 void vis_lua_win_status(Vis *vis, Win *win) {
2832 lua_State *L = vis->lua;
2833 if (!L || win->file->internal) {
2834 window_status_update(vis, win);
2835 return;
2837 vis_lua_event_get(L, "win_status");
2838 if (lua_isfunction(L, -1)) {
2839 obj_ref_new(L, win, VIS_LUA_TYPE_WINDOW);
2840 pcall(vis, L, 1, 0);
2841 } else {
2842 window_status_update(vis, win);
2844 lua_pop(L, 1);
2847 #endif