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.
10 * @author Marc André Tanner
21 #include <sys/types.h>
26 #include "text-motions.h"
30 #define VIS_PATH "/usr/local/share/vis"
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_SELECTION "selection"
40 #define VIS_LUA_TYPE_SELECTIONS "selections"
41 #define VIS_LUA_TYPE_UI "ui"
42 #define VIS_LUA_TYPE_REGISTERS "registers"
43 #define VIS_LUA_TYPE_KEYACTION "keyaction"
50 #define debug(...) do { printf(__VA_ARGS__); fflush(stdout); } while (0)
52 #define debug(...) do { } while (0)
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
;
74 strcpy(left_parts
[left_count
++], mode
);
76 snprintf(left_parts
[left_count
++], sizeof(left_parts
[0]), "%s%s%s",
77 filename
? filename
: "[No Name]",
78 text_modified(txt
) ? " [+]" : "",
79 vis_macro_recording(vis
) ? " @": "");
81 int count
= vis_count_get(vis
);
82 const char *keys
= buffer_content0(&vis
->input_queue
);
84 snprintf(right_parts
[right_count
++], sizeof(right_parts
[0]), "%s", keys
);
85 else if (count
!= VIS_COUNT_UNKNOWN
)
86 snprintf(right_parts
[right_count
++], sizeof(right_parts
[0]), "%d", count
);
88 int sel_count
= view_selections_count(view
);
90 Selection
*s
= view_selections_primary_get(view
);
91 int sel_number
= view_selections_number(s
) + 1;
92 snprintf(right_parts
[right_count
++], sizeof(right_parts
[0]),
93 "%d/%d", sel_number
, sel_count
);
96 size_t size
= text_size(txt
);
97 size_t pos
= view_cursor_get(view
);
100 double tmp
= ((double)pos
/(double)size
)*100;
101 percent
= (size_t)(tmp
+1);
103 snprintf(right_parts
[right_count
++], sizeof(right_parts
[0]),
106 if (!(options
& UI_OPTION_LARGE_FILE
)) {
107 Selection
*sel
= view_selections_primary_get(win
->view
);
108 size_t line
= view_cursors_line(sel
);
109 size_t col
= view_cursors_col(sel
);
110 if (col
> UI_LARGE_FILE_LINE_SIZE
) {
111 options
|= UI_OPTION_LARGE_FILE
;
112 view_options_set(win
->view
, options
);
114 snprintf(right_parts
[right_count
++], sizeof(right_parts
[0]),
115 "%zu, %zu", line
, col
);
118 int left_len
= snprintf(left
, sizeof(left
), " %s%s%s%s%s%s%s",
120 left_parts
[1][0] ? " » " : "",
122 left_parts
[2][0] ? " » " : "",
124 left_parts
[3][0] ? " » " : "",
127 int right_len
= snprintf(right
, sizeof(right
), "%s%s%s%s%s%s%s ",
129 right_parts
[1][0] ? " « " : "",
131 right_parts
[2][0] ? " « " : "",
133 right_parts
[3][0] ? " « " : "",
136 if (left_len
< 0 || right_len
< 0)
138 int left_width
= text_string_width(left
, left_len
);
139 int right_width
= text_string_width(right
, right_len
);
141 int spaces
= width
- left_width
- right_width
;
145 snprintf(status
, sizeof(status
), "%s%*s%s", left
, spaces
, " ", right
);
146 vis_window_status(win
, status
);
151 bool vis_lua_path_add(Vis
*vis
, const char *path
) { return true; }
152 bool vis_lua_paths_get(Vis
*vis
, char **lpath
, char **cpath
) { return false; }
153 void vis_lua_init(Vis
*vis
) { }
154 void vis_lua_start(Vis
*vis
) { }
155 void vis_lua_quit(Vis
*vis
) { }
156 void vis_lua_file_open(Vis
*vis
, File
*file
) { }
157 bool vis_lua_file_save_pre(Vis
*vis
, File
*file
, const char *path
) { return true; }
158 void vis_lua_file_save_post(Vis
*vis
, File
*file
, const char *path
) { }
159 void vis_lua_file_close(Vis
*vis
, File
*file
) { }
160 void vis_lua_win_open(Vis
*vis
, Win
*win
) { }
161 void vis_lua_win_close(Vis
*vis
, Win
*win
) { }
162 void vis_lua_win_highlight(Vis
*vis
, Win
*win
) { }
163 void vis_lua_win_status(Vis
*vis
, Win
*win
) { window_status_update(vis
, win
); }
168 static void stack_dump_entry(lua_State
*L
, int i
) {
169 int t
= lua_type(L
, i
);
175 printf(lua_toboolean(L
, i
) ? "true" : "false");
177 case LUA_TLIGHTUSERDATA
:
178 printf("lightuserdata(%p)", lua_touserdata(L
, i
));
181 printf("%g", lua_tonumber(L
, i
));
184 printf("`%s'", lua_tostring(L
, i
));
188 lua_pushnil(L
); /* first key */
189 while (lua_next(L
, i
> 0 ? i
: i
- 1)) {
190 stack_dump_entry(L
, -2);
192 stack_dump_entry(L
, -1);
194 lua_pop(L
, 1); /* remove value, keep key */
199 printf("userdata(%p)", lua_touserdata(L
, i
));
201 default: /* other values */
202 printf("%s", lua_typename(L
, t
));
207 static void stack_dump(lua_State
*L
, const char *format
, ...) {
209 va_start(ap
, format
);
212 int top
= lua_gettop(L
);
213 for (int i
= 1; i
<= top
; i
++) {
215 stack_dump_entry(L
, i
);
224 static int panic_handler(lua_State
*L
) {
226 lua_getallocf(L
, &ud
);
230 const char *msg
= NULL
;
231 if (lua_type(L
, -1) == LUA_TSTRING
)
232 msg
= lua_tostring(L
, -1);
233 vis_info_show(vis
, "Fatal Lua error: %s", msg
? msg
: "unknown reason");
236 siglongjmp(vis
->sigbus_jmpbuf
, 1);
241 static int error_handler(lua_State
*L
) {
242 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
243 if (vis
->errorhandler
)
245 vis
->errorhandler
= true;
247 const char *msg
= lua_tostring(L
, 1);
249 luaL_traceback(L
, L
, msg
, 1);
250 msg
= lua_tolstring(L
, 1, &len
);
251 vis_message_show(vis
, msg
);
252 vis
->errorhandler
= false;
256 static int pcall(Vis
*vis
, lua_State
*L
, int nargs
, int nresults
) {
257 /* insert a custom error function below all arguments */
258 int msgh
= lua_gettop(L
) - nargs
;
259 lua_pushlightuserdata(L
, vis
);
260 lua_pushcclosure(L
, error_handler
, 1);
262 int ret
= lua_pcall(L
, nargs
, nresults
, msgh
);
267 /* expects a lua function at stack position `narg` and stores a
268 * reference to it in the registry. The return value can be used
271 * registry["vis.functions"][(void*)(function)] = function
273 static const void *func_ref_new(lua_State
*L
, int narg
) {
274 const void *addr
= lua_topointer(L
, narg
);
275 if (!lua_isfunction(L
, narg
) || !addr
)
276 luaL_argerror(L
, narg
, "function expected");
277 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.functions");
278 lua_pushlightuserdata(L
, (void*)addr
);
279 lua_pushvalue(L
, narg
);
285 /* retrieve function from registry and place it at the top of the stack */
286 static bool func_ref_get(lua_State
*L
, const void *addr
) {
289 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.functions");
290 lua_pushlightuserdata(L
, (void*)addr
);
293 if (!lua_isfunction(L
, -1)) {
300 /* creates a new metatable for a given type and stores a mapping:
302 * registry["vis.types"][metatable] = type
304 * leaves the metatable at the top of the stack.
306 static void obj_type_new(lua_State
*L
, const char *type
) {
307 luaL_newmetatable(L
, type
);
308 lua_getglobal(L
, "vis");
309 if (!lua_isnil(L
, -1)) {
310 lua_getfield(L
, -1, "types");
311 lua_pushvalue(L
, -3);
312 lua_setfield(L
, -2, type
);
316 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.types");
317 lua_pushvalue(L
, -2);
318 lua_pushstring(L
, type
);
323 /* get type of userdatum at the top of the stack:
325 * return registry["vis.types"][getmetatable(userdata)]
327 const char *obj_type_get(lua_State
*L
) {
328 if (lua_isnil(L
, -1))
330 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.types");
331 lua_getmetatable(L
, -2);
333 // XXX: in theory string might become invalid when poped from stack
334 const char *type
= lua_tostring(L
, -1);
339 static void *obj_new(lua_State
*L
, size_t size
, const char *type
) {
340 void *obj
= lua_newuserdata(L
, size
);
341 luaL_getmetatable(L
, type
);
342 lua_setmetatable(L
, -2);
344 lua_setuservalue(L
, -2);
348 /* returns registry["vis.objects"][addr] if it is of correct type */
349 static void *obj_ref_get(lua_State
*L
, void *addr
, const char *type
) {
350 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.objects");
351 lua_pushlightuserdata(L
, addr
);
354 if (lua_isnil(L
, -1)) {
355 debug("get: vis.objects[%p] = nil\n", addr
);
360 const char *actual_type
= obj_type_get(L
);
361 if (strcmp(type
, actual_type
) != 0)
362 debug("get: vis.objects[%p] = %s (BUG: expected %s)\n", addr
, actual_type
, type
);
363 void **handle
= luaL_checkudata(L
, -1, type
);
365 debug("get: vis.objects[%p] = %s (BUG: invalid handle)\n", addr
, type
);
366 else if (*handle
!= addr
)
367 debug("get: vis.objects[%p] = %s (BUG: handle mismatch %p)\n", addr
, type
, *handle
);
369 return luaL_checkudata(L
, -1, type
);
372 /* expects a userdatum at the top of the stack and sets
374 * registry["vis.objects"][addr] = userdata
376 static void obj_ref_set(lua_State
*L
, void *addr
) {
377 //debug("set: vis.objects[%p] = %s\n", addr, obj_type_get(L));
378 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.objects");
379 lua_pushlightuserdata(L
, addr
);
380 lua_pushvalue(L
, -3);
385 /* invalidates an object reference
387 * registry["vis.objects"][addr] = nil
389 static void obj_ref_free(lua_State
*L
, void *addr
) {
391 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.objects");
392 lua_pushlightuserdata(L
, addr
);
395 if (lua_isnil(L
, -1))
396 debug("free-unused: %p\n", addr
);
398 debug("free: vis.objects[%p] = %s\n", addr
, obj_type_get(L
));
402 obj_ref_set(L
, addr
);
405 /* creates a new object reference of given type if it does not already exist in the registry:
407 * if (registry["vis.types"][metatable(registry["vis.objects"][addr])] != type) {
408 * // XXX: should not happen
409 * registry["vis.objects"][addr] = new_obj(addr, type)
411 * return registry["vis.objects"][addr];
413 static void *obj_ref_new(lua_State
*L
, void *addr
, const char *type
) {
418 lua_getfield(L
, LUA_REGISTRYINDEX
, "vis.objects");
419 lua_pushlightuserdata(L
, addr
);
422 const char *old_type
= obj_type_get(L
);
423 if (strcmp(type
, old_type
) == 0) {
424 debug("new: vis.objects[%p] = %s (returning existing object)\n", addr
, old_type
);
425 void **handle
= luaL_checkudata(L
, -1, type
);
427 debug("new: vis.objects[%p] = %s (BUG: invalid handle)\n", addr
, old_type
);
428 else if (*handle
!= addr
)
429 debug("new: vis.objects[%p] = %s (BUG: handle mismatch %p)\n", addr
, old_type
, *handle
);
432 if (!lua_isnil(L
, -1))
433 debug("new: vis.objects[%p] = %s (WARNING: changing object type from %s)\n", addr
, type
, old_type
);
435 debug("new: vis.objects[%p] = %s (creating new object)\n", addr
, type
);
437 void **handle
= obj_new(L
, sizeof(addr
), type
);
438 obj_ref_set(L
, addr
);
443 /* retrieve object stored in reference at stack location `idx' */
444 static void *obj_ref_check_get(lua_State
*L
, int idx
, const char *type
) {
445 void **addr
= luaL_checkudata(L
, idx
, type
);
446 if (!obj_ref_get(L
, *addr
, type
))
451 /* (type) check validity of object reference at stack location `idx' */
452 static void *obj_ref_check(lua_State
*L
, int idx
, const char *type
) {
453 void *obj
= obj_ref_check_get(L
, idx
, type
);
457 luaL_argerror(L
, idx
, "invalid object reference");
461 static void *obj_ref_check_containerof(lua_State
*L
, int idx
, const char *type
, size_t offset
) {
462 void *obj
= obj_ref_check(L
, idx
, type
);
463 return obj
? ((char*)obj
-offset
) : obj
;
466 static void *obj_lightref_new(lua_State
*L
, void *addr
, const char *type
) {
469 void **handle
= obj_new(L
, sizeof(addr
), type
);
474 static void *obj_lightref_check(lua_State
*L
, int idx
, const char *type
) {
475 void **addr
= luaL_checkudata(L
, idx
, type
);
479 static int index_common(lua_State
*L
) {
480 lua_getmetatable(L
, 1);
483 if (lua_isnil(L
, -1)) {
484 lua_getuservalue(L
, 1);
491 static int newindex_common(lua_State
*L
) {
492 lua_getuservalue(L
, 1);
499 static size_t getpos(lua_State
*L
, int narg
) {
500 return lua_tounsigned(L
, narg
);
503 static size_t checkpos(lua_State
*L
, int narg
) {
504 lua_Number n
= luaL_checknumber(L
, narg
);
505 if (n
>= 0 && n
<= SIZE_MAX
&& n
== (size_t)n
)
507 return luaL_argerror(L
, narg
, "expected position, got number");
510 static void pushpos(lua_State
*L
, size_t pos
) {
514 lua_pushunsigned(L
, pos
);
517 static void pushrange(lua_State
*L
, Filerange
*r
) {
518 if (!r
|| !text_range_valid(r
)) {
522 lua_createtable(L
, 0, 2);
523 lua_pushstring(L
, "start");
524 lua_pushunsigned(L
, r
->start
);
526 lua_pushstring(L
, "finish");
527 lua_pushunsigned(L
, r
->end
);
531 static Filerange
getrange(lua_State
*L
, int index
) {
532 Filerange range
= text_range_empty();
533 if (lua_istable(L
, index
)) {
534 lua_getfield(L
, index
, "start");
535 range
.start
= checkpos(L
, -1);
537 lua_getfield(L
, index
, "finish");
538 range
.end
= checkpos(L
, -1);
541 range
.start
= checkpos(L
, index
);
542 range
.end
= range
.start
+ checkpos(L
, index
+1);
547 static const char *keymapping(Vis
*vis
, const char *keys
, const Arg
*arg
) {
548 lua_State
*L
= vis
->lua
;
549 if (!func_ref_get(L
, arg
->v
))
551 lua_pushstring(L
, keys
);
552 if (pcall(vis
, L
, 1, 1) != 0)
554 if (lua_type(L
, -1) != LUA_TNUMBER
)
555 return keys
; /* invalid or no return value, assume zero */
556 lua_Number number
= lua_tonumber(L
, -1);
557 lua_Integer integer
= lua_tointeger(L
, -1);
558 if (number
!= integer
)
561 return NULL
; /* need more input */
562 size_t len
= integer
;
563 size_t max
= strlen(keys
);
564 return (len
<= max
) ? keys
+len
: keys
;
568 * The main editor object.
573 * Version information.
574 * @tfield string VERSION
575 * version information in `git describe` format, same as reported by `vis -v`.
578 * Lua API object types
579 * @field types meta tables of userdata objects used for type checking
584 * @tfield Ui ui the user interface being used
588 * @tfield modes modes
592 * @tfield events events
596 * @field registers array to access the register by single letter name
599 * Scintillua lexer module.
600 * @field lexers might be `nil` if module is not found
604 * @field lpeg might be `nil` if module is not found
608 * @tfield int count the specified count for the current command or `nil` if none was given
612 * Create an iterator over all windows.
614 * @return the new iterator
617 * for win in vis:windows() do
618 * -- do something with win
621 static int windows_iter(lua_State
*L
);
622 static int windows(lua_State
*L
) {
623 Vis
*vis
= obj_ref_check(L
, 1, "vis");
624 Win
**handle
= lua_newuserdata(L
, sizeof *handle
), *next
;
625 for (next
= vis
->windows
; next
&& next
->file
->internal
; next
= next
->next
);
627 lua_pushcclosure(L
, windows_iter
, 1);
631 static int windows_iter(lua_State
*L
) {
632 Win
**handle
= lua_touserdata(L
, lua_upvalueindex(1));
635 Win
*win
= obj_ref_new(L
, *handle
, VIS_LUA_TYPE_WINDOW
), *next
;
637 for (next
= win
->next
; next
&& next
->file
->internal
; next
= next
->next
);
644 * Create an iterator over all files.
646 * @return the new iterator
648 * for file in vis:files() do
649 * -- do something with file
652 static int files_iter(lua_State
*L
);
653 static int files(lua_State
*L
) {
654 Vis
*vis
= obj_ref_check(L
, 1, "vis");
655 File
**handle
= lua_newuserdata(L
, sizeof *handle
);
656 *handle
= vis
->files
;
657 lua_pushcclosure(L
, files_iter
, 1);
661 static int files_iter(lua_State
*L
) {
662 File
**handle
= lua_touserdata(L
, lua_upvalueindex(1));
665 File
*file
= obj_ref_new(L
, *handle
, VIS_LUA_TYPE_FILE
);
667 *handle
= file
->next
;
672 * Create an iterator over all mark names.
673 * @function mark_names
674 * @return the new iterator
676 * local marks = vis.win.marks
677 * for name in vis:mark_names() do
678 * local mark = marks[name]
679 * for i = 1, #mark do
680 * -- do somthing with: name, mark[i].start, mark[i].finish
684 static int mark_names_iter(lua_State
*L
);
685 static int mark_names(lua_State
*L
) {
686 enum VisMark
*handle
= lua_newuserdata(L
, sizeof *handle
);
688 lua_pushcclosure(L
, mark_names_iter
, 1);
692 static int mark_names_iter(lua_State
*L
) {
694 enum VisMark
*handle
= lua_touserdata(L
, lua_upvalueindex(1));
695 if (*handle
< LENGTH(vis_marks
))
696 mark
= vis_marks
[*handle
].name
;
697 else if (VIS_MARK_a
<= *handle
&& *handle
<= VIS_MARK_z
)
698 mark
= 'a' + *handle
- VIS_MARK_a
;
700 char name
[2] = { mark
, '\0' };
701 lua_pushstring(L
, name
);
709 * Create an iterator over all register names.
710 * @function register_names
711 * @return the new iterator
713 * for name in vis:register_names() do
714 * local reg = vis.registers[name]
716 * -- do something with register value reg[i]
720 static int register_names_iter(lua_State
*L
);
721 static int register_names(lua_State
*L
) {
722 enum VisRegister
*handle
= lua_newuserdata(L
, sizeof *handle
);
724 lua_pushcclosure(L
, register_names_iter
, 1);
728 static int register_names_iter(lua_State
*L
) {
730 enum VisRegister
*handle
= lua_touserdata(L
, lua_upvalueindex(1));
731 if (*handle
< LENGTH(vis_registers
))
732 reg
= vis_registers
[*handle
].name
;
733 else if (VIS_REG_a
<= *handle
&& *handle
<= VIS_REG_z
)
734 reg
= 'a' + *handle
- VIS_REG_a
;
736 char name
[2] = { reg
, '\0' };
737 lua_pushstring(L
, name
);
745 * Execute a `:`-command.
747 * @tparam string command the command to execute
748 * @treturn bool whether the command succeeded
750 * vis:command("set number")
752 static int command(lua_State
*L
) {
753 Vis
*vis
= obj_ref_check(L
, 1, "vis");
754 const char *cmd
= luaL_checkstring(L
, 2);
755 bool ret
= vis_cmd(vis
, cmd
);
756 lua_pushboolean(L
, ret
);
761 * Display a short message.
763 * The single line message will be displayed at the bottom of
764 * the scren and automatically hidden once a key is pressed.
767 * @tparam string message the message to display
769 static int info(lua_State
*L
) {
770 Vis
*vis
= obj_ref_check(L
, 1, "vis");
771 const char *msg
= luaL_checkstring(L
, 2);
772 vis_info_show(vis
, "%s", msg
);
777 * Display a multi line message.
779 * Opens a new window and displays an arbitrarily long message.
782 * @tparam string message the message to display
784 static int message(lua_State
*L
) {
785 Vis
*vis
= obj_ref_check(L
, 1, "vis");
786 const char *msg
= luaL_checkstring(L
, 2);
787 vis_message_show(vis
, msg
);
792 * Register a Lua function as key action.
793 * @function action_register
794 * @tparam string name the name of the action, can be referred to in key bindings as `<name>` pseudo key
795 * @tparam Function func the lua function implementing the key action (see @{keyhandler})
796 * @tparam[opt] string help the single line help text as displayed in `:help`
797 * @treturn KeyAction action the registered key action
801 static int action_register(lua_State
*L
) {
802 Vis
*vis
= obj_ref_check(L
, 1, "vis");
803 const char *name
= luaL_checkstring(L
, 2);
804 const void *func
= func_ref_new(L
, 3);
805 const char *help
= luaL_optstring(L
, 4, NULL
);
806 KeyAction
*action
= vis_action_new(vis
, name
, help
, keymapping
, (Arg
){ .v
= func
});
809 if (!vis_action_register(vis
, action
))
811 obj_ref_new(L
, action
, VIS_LUA_TYPE_KEYACTION
);
814 vis_action_free(vis
, action
);
819 static int keymap(lua_State
*L
, Vis
*vis
, Win
*win
) {
820 int mode
= luaL_checkint(L
, 2);
821 const char *key
= luaL_checkstring(L
, 3);
822 const char *help
= luaL_optstring(L
, 5, NULL
);
823 KeyBinding
*binding
= vis_binding_new(vis
);
826 if (lua_isstring(L
, 4)) {
827 const char *alias
= luaL_checkstring(L
, 4);
828 if (!(binding
->alias
= strdup(alias
)))
830 } else if (lua_isfunction(L
, 4)) {
831 const void *func
= func_ref_new(L
, 4);
832 if (!(binding
->action
= vis_action_new(vis
, NULL
, help
, keymapping
, (Arg
){ .v
= func
})))
834 } else if (lua_isuserdata(L
, 4)) {
835 binding
->action
= obj_ref_check(L
, 4, VIS_LUA_TYPE_KEYACTION
);
839 if (!vis_window_mode_map(win
, mode
, true, key
, binding
))
842 if (!vis_mode_map(vis
, mode
, true, key
, binding
))
846 lua_pushboolean(L
, true);
849 vis_binding_free(vis
, binding
);
850 lua_pushboolean(L
, false);
855 * Map a key to a Lua function.
857 * Creates a new key mapping in a given mode.
860 * @tparam int mode the mode to which the mapping should be added
861 * @tparam string key the key to map
862 * @tparam function func the Lua function to handle the key mapping (see @{keyhandler})
863 * @tparam[opt] string help the single line help text as displayed in `:help`
864 * @treturn bool whether the mapping was successfully established
867 * vis:map(vis.modes.INSERT, "<C-k>", function(keys)
869 * return -1 -- need more input
871 * local digraph = keys:sub(1, 2)
872 * if digraph == "l*" then
874 * return 2 -- consume 2 bytes of input
876 * end, "Insert digraph")
881 * This is equivalent to `vis:command('map! mode key alias')`.
883 * Mappings are always recursive!
885 * @tparam int mode the mode to which the mapping should be added
886 * @tparam string key the key to map
887 * @tparam string alias the key to map to
888 * @treturn bool whether the mapping was successfully established
891 * vis:map(vis.modes.NORMAL, "j", "k")
894 * Map a key to a key action.
897 * @tparam int mode the mode to which the mapping should be added
898 * @tparam string key the key to map
899 * @param action the action to map
900 * @treturn bool whether the mapping was successfully established
903 * local action = vis:action_register("info", function()
904 * vis:info("Mapping works!")
905 * end, "Info message help text")
906 * vis:map(vis.modes.NORMAL, "gh", action)
907 * vis:map(vis.modes.NORMAL, "gl", action)
909 static int map(lua_State
*L
) {
910 Vis
*vis
= obj_ref_check(L
, 1, "vis");
911 return keymap(L
, vis
, NULL
);
915 * Unmap a global key binding.
918 * @tparam int mode the mode from which the mapping should be removed
919 * @tparam string key the mapping to remove
920 * @treturn bool whether the mapping was successfully removed
923 static int keyunmap(lua_State
*L
, Vis
*vis
, Win
*win
) {
924 enum VisMode mode
= luaL_checkint(L
, 2);
925 const char *key
= luaL_checkstring(L
, 3);
928 ret
= vis_mode_unmap(vis
, mode
, key
);
930 ret
= vis_window_mode_unmap(win
, mode
, key
);
931 lua_pushboolean(L
, ret
);
935 static int unmap(lua_State
*L
) {
936 Vis
*vis
= obj_ref_check(L
, 1, "vis");
937 return keyunmap(L
, vis
, NULL
);
941 * Get all currently active mappings of a mode.
944 * @tparam int mode the mode to query
945 * @treturn table the active mappings and their associated help texts
947 * local bindings = vis:mappings(vis.modes.NORMAL)
948 * for key, help in pairs(bindings) do
953 static bool binding_collect(const char *key
, void *value
, void *ctx
) {
955 KeyBinding
*binding
= value
;
956 lua_getfield(L
, -1, key
);
957 bool new = lua_isnil(L
, -1);
960 const char *help
= binding
->alias
? binding
->alias
: VIS_HELP_USE(binding
->action
->help
);
961 lua_pushstring(L
, help
? help
: "");
962 lua_setfield(L
, -2, key
);
967 static int mappings(lua_State
*L
) {
968 Vis
*vis
= obj_ref_check(L
, 1, "vis");
970 for (Mode
*mode
= mode_get(vis
, luaL_checkint(L
, 2)); mode
; mode
= mode
->parent
) {
973 map_iterate(mode
->bindings
, binding_collect
, vis
->lua
);
982 * @tparam int id the id of the motion to execute
983 * @treturn bool whether the id was valid
986 static int motion(lua_State
*L
) {
987 Vis
*vis
= obj_ref_check(L
, 1, "vis");
988 enum VisMotion id
= luaL_checkunsigned(L
, 2);
989 // TODO handle var args?
990 lua_pushboolean(L
, vis
&& vis_motion(vis
, id
));
994 static size_t motion_lua(Vis
*vis
, Win
*win
, void *data
, size_t pos
) {
995 lua_State
*L
= vis
->lua
;
996 if (!L
|| !func_ref_get(L
, data
) || !obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
))
999 lua_pushunsigned(L
, pos
);
1000 if (pcall(vis
, L
, 2, 1) != 0)
1002 return getpos(L
, -1);
1006 * Register a custom motion.
1008 * @function motion_register
1009 * @tparam function motion the Lua function implementing the motion
1010 * @treturn int the associated motion id, or `-1` on failure
1011 * @see motion, motion_new
1014 * -- custom motion advancing to the next byte
1015 * local id = vis:motion_register(function(win, pos)
1019 static int motion_register(lua_State
*L
) {
1020 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1021 const void *func
= func_ref_new(L
, 2);
1022 int id
= vis_motion_register(vis
, (void*)func
, motion_lua
);
1023 lua_pushinteger(L
, id
);
1028 * Execute an operator.
1030 * @function operator
1031 * @tparam int id the id of the operator to execute
1032 * @treturn bool whether the id was valid
1035 static int operator(lua_State
*L
) {
1036 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1037 enum VisOperator id
= luaL_checkunsigned(L
, 2);
1038 // TODO handle var args?
1039 lua_pushboolean(L
, vis
&& vis_operator(vis
, id
));
1043 static size_t operator_lua(Vis
*vis
, Text
*text
, OperatorContext
*c
) {
1044 lua_State
*L
= vis
->lua
;
1045 if (!L
|| !func_ref_get(L
, c
->context
))
1047 File
*file
= vis
->files
;
1048 while (file
&& (file
->internal
|| file
->text
!= text
))
1050 if (!file
|| !obj_ref_new(L
, file
, VIS_LUA_TYPE_FILE
))
1052 pushrange(L
, &c
->range
);
1054 if (pcall(vis
, L
, 3, 1) != 0)
1056 return getpos(L
, -1);
1060 * Register a custom operator.
1062 * @function operator_register
1063 * @tparam function operator the Lua function implementing the operator
1064 * @treturn int the associated operator id, or `-1` on failure
1065 * @see operator, operator_new
1068 * -- custom operator replacing every 'a' with 'b'
1069 * local id = vis:operator_register(function(file, range, pos)
1070 * local data = file:content(range)
1071 * data = data:gsub("a", "b")
1072 * file:delete(range)
1073 * file:insert(range.start, data)
1074 * return range.start -- new cursor location
1077 static int operator_register(lua_State
*L
) {
1078 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1079 const void *func
= func_ref_new(L
, 2);
1080 int id
= vis_operator_register(vis
, operator_lua
, (void*)func
);
1081 lua_pushinteger(L
, id
);
1086 * Execute a text object.
1088 * @function textobject
1089 * @tparam int id the id of the text object to execute
1090 * @treturn bool whether the id was valid
1091 * @see textobject_register, textobject_new
1094 static int textobject(lua_State
*L
) {
1095 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1096 enum VisTextObject id
= luaL_checkunsigned(L
, 2);
1097 lua_pushboolean(L
, vis_textobject(vis
, id
));
1101 static Filerange
textobject_lua(Vis
*vis
, Win
*win
, void *data
, size_t pos
) {
1102 lua_State
*L
= vis
->lua
;
1103 if (!L
|| !func_ref_get(L
, data
) || !obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
))
1104 return text_range_empty();
1105 lua_pushunsigned(L
, pos
);
1106 if (pcall(vis
, L
, 2, 2) != 0 || lua_isnil(L
, -1))
1107 return text_range_empty();
1108 return text_range_new(getpos(L
, -2), getpos(L
, -1));
1112 * Register a custom text object.
1114 * @function textobject_register
1115 * @tparam function textobject the Lua function implementing the text object
1116 * @treturn int the associated text object id, or `-1` on failure
1117 * @see textobject, textobject_new
1120 * -- custom text object covering the next byte
1121 * local id = vis:textobject_register(function(win, pos)
1125 static int textobject_register(lua_State
*L
) {
1126 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1127 const void *func
= func_ref_new(L
, 2);
1128 int id
= vis_textobject_register(vis
, 0, (void*)func
, textobject_lua
);
1129 lua_pushinteger(L
, id
);
1133 static bool option_lua(Vis
*vis
, Win
*win
, void *context
, bool toggle
,
1134 enum VisOption flags
, const char *name
, Arg
*value
) {
1135 lua_State
*L
= vis
->lua
;
1136 if (!L
|| !func_ref_get(L
, context
))
1138 if (flags
& VIS_OPTION_TYPE_BOOL
)
1139 lua_pushboolean(L
, value
->b
);
1140 else if (flags
& VIS_OPTION_TYPE_STRING
)
1141 lua_pushstring(L
, value
->s
);
1142 else if (flags
& VIS_OPTION_TYPE_NUMBER
)
1143 lua_pushnumber(L
, value
->i
);
1146 lua_pushboolean(L
, toggle
);
1147 return pcall(vis
, L
, 2, 2) == 0 && (!lua_isboolean(L
, -1) || lua_toboolean(L
, -1));
1151 * Register a custom `:set` option.
1153 * @function option_register
1154 * @tparam string name the option name
1155 * @tparam string type the option type (`bool`, `string` or `number`)
1156 * @tparam function handler the Lua function being called when the option is changed
1157 * @tparam[opt] string help the single line help text as displayed in `:help`
1158 * @treturn bool whether the option was successfully registered
1160 * vis:option_register("foo", "bool", function(value, toogle)
1161 * if not vis.win then return false end
1162 * vis.win.foo = toogle and not vis.win.foo or value
1163 * vis:info("Option foo = " .. tostring(vis.win.foo))
1165 * end, "Foo enables superpowers")
1167 static int option_register(lua_State
*L
) {
1168 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1169 const char *name
= luaL_checkstring(L
, 2);
1170 const char *type
= luaL_checkstring(L
, 3);
1171 const void *func
= func_ref_new(L
, 4);
1172 const char *help
= luaL_optstring(L
, 5, NULL
);
1173 const char *names
[] = { name
, NULL
};
1174 enum VisOption flags
= 0;
1175 if (strcmp(type
, "string") == 0)
1176 flags
|= VIS_OPTION_TYPE_STRING
;
1177 else if (strcmp(type
, "number") == 0)
1178 flags
|= VIS_OPTION_TYPE_NUMBER
;
1180 flags
|= VIS_OPTION_TYPE_BOOL
;
1181 bool ret
= vis_option_register(vis
, names
, flags
, option_lua
, (void*)func
, help
);
1182 lua_pushboolean(L
, ret
);
1187 * Unregister a `:set` option.
1189 * @function option_unregister
1190 * @tparam string name the option name
1191 * @treturn bool whether the option was successfully unregistered
1193 static int option_unregister(lua_State
*L
) {
1194 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1195 const char *name
= luaL_checkstring(L
, 2);
1196 bool ret
= vis_option_unregister(vis
, name
);
1197 lua_pushboolean(L
, ret
);
1201 static bool command_lua(Vis
*vis
, Win
*win
, void *data
, bool force
, const char *argv
[], Selection
*sel
, Filerange
*range
) {
1202 lua_State
*L
= vis
->lua
;
1203 if (!L
|| !func_ref_get(L
, data
))
1206 for (size_t i
= 0; argv
[i
]; i
++) {
1207 lua_pushunsigned(L
, i
);
1208 lua_pushstring(L
, argv
[i
]);
1209 lua_settable(L
, -3);
1211 lua_pushboolean(L
, force
);
1212 if (!obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
))
1215 sel
= view_selections_primary_get(win
->view
);
1216 if (!obj_lightref_new(L
, sel
, VIS_LUA_TYPE_SELECTION
))
1218 pushrange(L
, range
);
1219 if (pcall(vis
, L
, 5, 1) != 0)
1221 return lua_toboolean(L
, -1);
1225 * Register a custom `:`-command.
1227 * @function command_register
1228 * @tparam string name the command name
1229 * @tparam function command the Lua function implementing the command
1230 * @tparam[opt] string help the single line help text as displayed in `:help`
1231 * @treturn bool whether the command has been successfully registered
1233 * vis:command_register("foo", function(argv, force, win, selection, range)
1234 * for i,arg in ipairs(argv) do
1235 * print(i..": "..arg)
1237 * print("was command forced with ! "..(force and "yes" or "no"))
1238 * print(win.file.name)
1239 * print(selection.pos)
1240 * print(range ~= nil and ('['..range.start..', '..range.finish..']') or "invalid range")
1244 static int command_register(lua_State
*L
) {
1245 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1246 const char *name
= luaL_checkstring(L
, 2);
1247 const void *func
= func_ref_new(L
, 3);
1248 const char *help
= luaL_optstring(L
, 4, "");
1249 bool ret
= vis_cmd_register(vis
, name
, help
, (void*)func
, command_lua
);
1250 lua_pushboolean(L
, ret
);
1255 * Push keys to input queue and interpret them.
1257 * The keys are processed as if they were read from the keyboard.
1259 * @function feedkeys
1260 * @tparam string keys the keys to interpret
1262 static int feedkeys(lua_State
*L
) {
1263 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1264 const char *keys
= luaL_checkstring(L
, 2);
1265 vis_keys_feed(vis
, keys
);
1270 * Insert keys at all cursor positions of active window.
1272 * This function behaves as if the keys were entered in insert mode,
1273 * but in contrast to @{Vis:feedkeys} it bypasses the input queue,
1274 * meaning mappings do not apply and the keys will not be recorded in macros.
1277 * @tparam string keys the keys to insert
1280 static int insert(lua_State
*L
) {
1281 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1283 const char *keys
= luaL_checklstring(L
, 2, &len
);
1284 vis_insert_key(vis
, keys
, len
);
1289 * Replace keys at all cursor positions of active window.
1291 * This function behaves as if the keys were entered in replace mode,
1292 * but in contrast to @{Vis:feedkeys} it bypasses the input queue,
1293 * meaning mappings do not apply and the keys will not be recorded in macros.
1296 * @tparam string keys the keys to insert
1299 static int replace(lua_State
*L
) {
1300 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1302 const char *keys
= luaL_checklstring(L
, 2, &len
);
1303 vis_replace_key(vis
, keys
, len
);
1308 * Terminate editor process.
1310 * Termination happens upon the next iteration of the main event loop.
1311 * This means the calling Lua code will be executed further until it
1312 * eventually hands over control to the editor core. The exit status
1313 * of the most recent call is used.
1315 * All unsaved chanes will be lost!
1318 * @tparam int code the exit status returned to the operating system
1320 static int exit_func(lua_State
*L
) {
1321 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1322 int code
= luaL_checkint(L
, 2);
1323 vis_exit(vis
, code
);
1328 * Pipe file range to external process and collect output.
1330 * The editor core will be blocked while the external process is running.
1333 * @tparam File file the file to which the range applies
1334 * @tparam Range range the range to pipe
1335 * @tparam string command the command to execute
1336 * @treturn int code the exit status of the executed command
1337 * @treturn string stdout the data written to stdout
1338 * @treturn string stderr the data written to stderr
1340 static int pipe_func(lua_State
*L
) {
1341 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1342 File
*file
= obj_ref_check(L
, 2, VIS_LUA_TYPE_FILE
);
1343 Filerange range
= getrange(L
, 3);
1344 const char *cmd
= luaL_checkstring(L
, 4);
1345 char *out
= NULL
, *err
= NULL
;
1346 int status
= vis_pipe_collect(vis
, file
, &range
, (const char*[]){ cmd
, NULL
}, &out
, &err
);
1347 lua_pushinteger(L
, status
);
1349 lua_pushstring(L
, out
);
1354 lua_pushstring(L
, err
);
1362 * Redraw complete user interface.
1364 * Will trigger redraw events, make sure to avoid recursive events.
1368 static int redraw(lua_State
*L
) {
1369 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1374 * Currently active window.
1375 * @tfield Window win
1379 * Currently active mode.
1380 * @tfield modes mode
1383 * Whether a macro is being recorded.
1384 * @tfield bool recording
1387 * Currently unconsumed keys in the input queue.
1388 * @tfield string input_queue
1390 static int vis_index(lua_State
*L
) {
1391 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1393 if (lua_isstring(L
, 2)) {
1394 const char *key
= lua_tostring(L
, 2);
1395 if (strcmp(key
, "win") == 0) {
1397 obj_ref_new(L
, vis
->win
, VIS_LUA_TYPE_WINDOW
);
1403 if (strcmp(key
, "mode") == 0) {
1404 lua_pushunsigned(L
, vis
->mode
->id
);
1408 if (strcmp(key
, "input_queue") == 0) {
1409 lua_pushstring(L
, buffer_content0(&vis
->input_queue
));
1413 if (strcmp(key
, "recording") == 0) {
1414 lua_pushboolean(L
, vis_macro_recording(vis
));
1418 if (strcmp(key
, "count") == 0) {
1419 int count
= vis_count_get(vis
);
1420 if (count
== VIS_COUNT_UNKNOWN
)
1423 lua_pushunsigned(L
, count
);
1427 if (strcmp(key
, "registers") == 0) {
1428 obj_ref_new(L
, vis
->ui
, VIS_LUA_TYPE_REGISTERS
);
1432 if (strcmp(key
, "ui") == 0) {
1433 obj_ref_new(L
, vis
->ui
, VIS_LUA_TYPE_UI
);
1438 return index_common(L
);
1441 static int vis_newindex(lua_State
*L
) {
1442 Vis
*vis
= obj_ref_check(L
, 1, "vis");
1443 if (lua_isstring(L
, 2)) {
1444 const char *key
= lua_tostring(L
, 2);
1445 if (strcmp(key
, "mode") == 0) {
1446 enum VisMode mode
= luaL_checkunsigned(L
, 3);
1447 vis_mode_switch(vis
, mode
);
1451 if (strcmp(key
, "count") == 0) {
1453 if (lua_isnil(L
, 3))
1454 count
= VIS_COUNT_UNKNOWN
;
1456 count
= luaL_checkunsigned(L
, 3);
1457 vis_count_set(vis
, count
);
1461 if (strcmp(key
, "win") == 0) {
1462 vis_window_focus(obj_ref_check(L
, 3, VIS_LUA_TYPE_WINDOW
));
1466 return newindex_common(L
);
1469 static const struct luaL_Reg vis_lua
[] = {
1471 { "windows", windows
},
1472 { "mark_names", mark_names
},
1473 { "register_names", register_names
},
1474 { "command", command
},
1476 { "message", message
},
1479 { "mappings", mappings
},
1480 { "operator", operator },
1481 { "operator_register", operator_register
},
1482 { "motion", motion
},
1483 { "motion_register", motion_register
},
1484 { "textobject", textobject
},
1485 { "textobject_register", textobject_register
},
1486 { "option_register", option_register
},
1487 { "option_unregister", option_unregister
},
1488 { "command_register", command_register
},
1489 { "feedkeys", feedkeys
},
1490 { "insert", insert
},
1491 { "replace", replace
},
1492 { "action_register", action_register
},
1493 { "exit", exit_func
},
1494 { "pipe", pipe_func
},
1495 { "redraw", redraw
},
1496 { "__index", vis_index
},
1497 { "__newindex", vis_newindex
},
1501 static const struct luaL_Reg ui_funcs
[] = {
1502 { "__index", index_common
},
1506 static int registers_index(lua_State
*L
) {
1508 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
1509 const char *symbol
= luaL_checkstring(L
, 2);
1510 if (strlen(symbol
) != 1)
1512 enum VisRegister reg
= vis_register_from(vis
, symbol
[0]);
1513 if (reg
>= VIS_REG_INVALID
)
1515 Array data
= vis_register_get(vis
, reg
);
1516 for (size_t i
= 0, len
= array_length(&data
); i
< len
; i
++) {
1517 TextString
*string
= array_get(&data
, i
);
1518 lua_pushunsigned(L
, i
+1);
1519 lua_pushlstring(L
, string
->data
, string
->len
);
1520 lua_settable(L
, -3);
1522 array_release(&data
);
1526 static int registers_newindex(lua_State
*L
) {
1527 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
1528 const char *symbol
= luaL_checkstring(L
, 2);
1529 if (strlen(symbol
) != 1)
1531 enum VisRegister reg
= vis_register_from(vis
, symbol
[0]);
1533 array_init_sized(&data
, sizeof(TextString
));
1535 if (lua_istable(L
, 3)) {
1537 while (lua_next(L
, 3)) {
1539 string
.data
= luaL_checklstring(L
, -1, &string
.len
);
1540 array_add(&data
, &string
);
1545 vis_register_set(vis
, reg
, &data
);
1546 array_release(&data
);
1550 static int registers_len(lua_State
*L
) {
1551 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
1552 lua_pushunsigned(L
, LENGTH(vis
->registers
));
1556 static const struct luaL_Reg registers_funcs
[] = {
1557 { "__index", registers_index
},
1558 { "__newindex", registers_newindex
},
1559 { "__len", registers_len
},
1569 * Viewport currently being displayed.
1570 * @tfield Range viewport
1577 * The window height.
1578 * @tfield int height
1581 * The file being displayed in this window.
1585 * The primary selection of this window.
1586 * @tfield Selection selection
1589 * The selections of this window.
1590 * @tfield Array(Selection) selections
1594 * Most of these marks are stored in the associated File object, meaning they
1595 * are the same in all windows displaying the same file.
1596 * @field marks array to access the marks of this window by single letter name
1597 * @see Vis:marks_names
1599 static int window_index(lua_State
*L
) {
1600 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1602 if (lua_isstring(L
, 2)) {
1603 const char *key
= lua_tostring(L
, 2);
1605 if (strcmp(key
, "viewport") == 0) {
1606 Filerange r
= view_viewport_get(win
->view
);
1611 if (strcmp(key
, "width") == 0) {
1612 lua_pushunsigned(L
, vis_window_width_get(win
));
1616 if (strcmp(key
, "height") == 0) {
1617 lua_pushunsigned(L
, vis_window_height_get(win
));
1621 if (strcmp(key
, "file") == 0) {
1622 obj_ref_new(L
, win
->file
, VIS_LUA_TYPE_FILE
);
1626 if (strcmp(key
, "selection") == 0) {
1627 Selection
*sel
= view_selections_primary_get(win
->view
);
1628 obj_lightref_new(L
, sel
, VIS_LUA_TYPE_SELECTION
);
1632 if (strcmp(key
, "selections") == 0) {
1633 obj_ref_new(L
, win
->view
, VIS_LUA_TYPE_SELECTIONS
);
1637 if (strcmp(key
, "marks") == 0) {
1638 obj_ref_new(L
, &win
->saved_selections
, VIS_LUA_TYPE_MARKS
);
1643 return index_common(L
);
1646 static int window_selections_iterator_next(lua_State
*L
) {
1647 Selection
**handle
= lua_touserdata(L
, lua_upvalueindex(1));
1650 Selection
*sel
= obj_lightref_new(L
, *handle
, VIS_LUA_TYPE_SELECTION
);
1653 *handle
= view_selections_next(sel
);
1658 * Create an iterator over all selections of this window.
1659 * @function selections_iterator
1660 * @return the new iterator
1662 static int window_selections_iterator(lua_State
*L
) {
1663 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1664 Selection
**handle
= lua_newuserdata(L
, sizeof *handle
);
1665 *handle
= view_selections(win
->view
);
1666 lua_pushcclosure(L
, window_selections_iterator_next
, 1);
1671 * Set up a window local key mapping.
1672 * The function signatures are the same as for @{Vis:map}.
1677 static int window_map(lua_State
*L
) {
1678 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1679 return keymap(L
, win
->vis
, win
);
1683 * Remove a window local key mapping.
1684 * The function signature is the same as for @{Vis:unmap}.
1689 static int window_unmap(lua_State
*L
) {
1690 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1691 return keyunmap(L
, win
->vis
, win
);
1695 * Define a display style.
1696 * @function style_define
1697 * @tparam int id the style id to use
1698 * @tparam string style the style definition
1699 * @treturn bool whether the style definition has been successfully
1700 * associated with the given id
1703 * win:style_define(win.STYLE_DEFAULT, "fore:red")
1705 static int window_style_define(lua_State
*L
) {
1706 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1707 enum UiStyle id
= luaL_checkunsigned(L
, 2);
1708 const char *style
= luaL_checkstring(L
, 3);
1709 bool ret
= view_style_define(win
->view
, id
, style
);
1710 lua_pushboolean(L
, ret
);
1715 * Style a window range.
1717 * The style will be cleared after every window redraw.
1719 * @tparam int id the display style as registered with @{style_define}
1720 * @tparam int start the absolute file position in bytes
1721 * @tparam int finish the end position
1724 * win:style(win.STYLE_DEFAULT, 0, 10)
1726 static int window_style(lua_State
*L
) {
1727 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1728 enum UiStyle style
= luaL_checkunsigned(L
, 2);
1729 size_t start
= checkpos(L
, 3);
1730 size_t end
= checkpos(L
, 4);
1731 view_style(win
->view
, style
, start
, end
);
1736 * Set window status line.
1739 * @tparam string left the left aligned part of the status line
1740 * @tparam[opt] string right the right aligned part of the status line
1742 static int window_status(lua_State
*L
) {
1743 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1744 char status
[1024] = "";
1745 int width
= vis_window_width_get(win
);
1746 const char *left
= luaL_checkstring(L
, 2);
1747 const char *right
= luaL_optstring(L
, 3, "");
1748 int left_width
= text_string_width(left
, strlen(left
));
1749 int right_width
= text_string_width(right
, strlen(right
));
1750 int spaces
= width
- left_width
- right_width
;
1753 snprintf(status
, sizeof(status
)-1, "%s%*s%s", left
, spaces
, " ", right
);
1754 vis_window_status(win
, status
);
1759 * Redraw window content.
1763 static int window_draw(lua_State
*L
) {
1764 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1765 view_draw(win
->view
);
1772 * After a successful call the Window reference becomes invalid and
1773 * must no longer be used. Attempting to close the last window will
1778 * @tparam bool force whether unsaved changes should be discarded
1779 * @treturn bool whether the window was closed
1781 static int window_close(lua_State
*L
) {
1782 Win
*win
= obj_ref_check(L
, 1, VIS_LUA_TYPE_WINDOW
);
1784 for (Win
*w
= win
->vis
->windows
; w
; w
= w
->next
) {
1785 if (!w
->file
->internal
)
1788 bool force
= lua_isboolean(L
, 2) && lua_toboolean(L
, 2);
1789 bool close
= count
> 1 && (force
|| vis_window_closable(win
));
1791 vis_window_close(win
);
1792 lua_pushboolean(L
, close
);
1796 static const struct luaL_Reg window_funcs
[] = {
1797 { "__index", window_index
},
1798 { "__newindex", newindex_common
},
1799 { "selections_iterator", window_selections_iterator
},
1800 { "map", window_map
},
1801 { "unmap", window_unmap
},
1802 { "style_define", window_style_define
},
1803 { "style", window_style
},
1804 { "status", window_status
},
1805 { "draw", window_draw
},
1806 { "close", window_close
},
1810 static int window_selections_index(lua_State
*L
) {
1811 View
*view
= obj_ref_check(L
, 1, VIS_LUA_TYPE_SELECTIONS
);
1812 size_t index
= luaL_checkunsigned(L
, 2);
1813 size_t count
= view_selections_count(view
);
1814 if (index
== 0 || index
> count
)
1816 for (Selection
*s
= view_selections(view
); s
; s
= view_selections_next(s
)) {
1818 obj_lightref_new(L
, s
, VIS_LUA_TYPE_SELECTION
);
1827 static int window_selections_len(lua_State
*L
) {
1828 View
*view
= obj_ref_check(L
, 1, VIS_LUA_TYPE_SELECTIONS
);
1829 lua_pushunsigned(L
, view_selections_count(view
));
1833 static const struct luaL_Reg window_selections_funcs
[] = {
1834 { "__index", window_selections_index
},
1835 { "__len", window_selections_len
},
1840 * A selection object.
1842 * A selection is a non-empty, directed range with two endpoints called
1843 * *cursor* and *anchor*. A selection can be anchored in which case
1844 * the anchor remains fixed while only the position of the cursor is
1845 * adjusted. For non-anchored selections both endpoints are updated. A
1846 * singleton selection covers one character on which both cursor and
1847 * anchor reside. There always exists a primary selection which remains
1848 * visible (i.e. changes to its position will adjust the viewport).
1850 * The range covered by a selection is represented as an interval whose
1851 * endpoints are absolute byte offsets from the start of the file.
1852 * Valid addresses are within the closed interval `[0, file.size]`.
1854 * Selections are currently implemented using character marks into
1855 * the underlying persistent
1856 * [text management data structure](https://github.com/martanne/vis/wiki/Text-management-using-a-piece-chain).
1858 * This has a few consequences you should be aware of:
1860 * - A selection becomes invalid when the delimiting boundaries of the underlying
1861 * text it is referencing is deleted:
1863 * -- leaves selection in an invalid state
1864 * win.file:delete(win.selection.pos, 1)
1865 * assert(win.selection.pos == nil)
1867 * Like a regular mark it will become valid again when the text is reverted
1868 * to the state before the deletion.
1870 * - Inserts after the selection position (`> selection.pos`) will not affect the
1871 * selection postion.
1873 * local pos = win.selection.pos
1874 * win.file:insert(pos+1, "-")
1875 * assert(win.selection.pos == pos)
1877 * - Non-cached inserts before the selection position (`<= selection.pos`) will
1878 * affect the mark and adjust the selection postion by the number of bytes
1879 * which were inserted.
1881 * local pos = win.selection.pos
1882 * win.file:insert(pos, "-")
1883 * assert(win.selection.pos == pos+1)
1885 * - Cached inserts before the selection position (`<= selection.pos`) will
1886 * not affect the selection position because the underlying text is replaced
1889 * For these reasons it is generally recommended to update the selection position
1890 * after a modification. The general procedure amounts to:
1892 * 1. Read out the current selection position
1893 * 2. Perform text modifications
1894 * 3. Update the selection postion
1896 * This is what @{Vis:insert} and @{Vis:replace} do internally.
1900 * local data = "new text"
1901 * local pos = win.selection.pos
1902 * win.file:insert(pos, data)
1903 * win.selection.pos = pos + #data
1907 * The zero based byte position in the file.
1909 * Might be `nil` if the selection is in an invalid state.
1910 * Setting this field will move the cursor endpoint of the
1911 * selection to the given position.
1915 * The 1-based line the cursor of this selection resides on.
1921 * The 1-based column position the cursor of this selection resides on.
1926 * The 1-based selection index.
1927 * @tfield int number
1930 * The range covered by this selection.
1931 * @tfield Range range
1934 * Whether this selection is anchored.
1935 * @tfield bool anchored
1937 static int window_selection_index(lua_State
*L
) {
1938 Selection
*sel
= obj_lightref_check(L
, 1, VIS_LUA_TYPE_SELECTION
);
1944 if (lua_isstring(L
, 2)) {
1945 const char *key
= lua_tostring(L
, 2);
1946 if (strcmp(key
, "pos") == 0) {
1947 pushpos(L
, view_cursors_pos(sel
));
1951 if (strcmp(key
, "line") == 0) {
1952 lua_pushunsigned(L
, view_cursors_line(sel
));
1956 if (strcmp(key
, "col") == 0) {
1957 lua_pushunsigned(L
, view_cursors_col(sel
));
1961 if (strcmp(key
, "number") == 0) {
1962 lua_pushunsigned(L
, view_selections_number(sel
)+1);
1966 if (strcmp(key
, "range") == 0) {
1967 Filerange range
= view_selections_get(sel
);
1968 pushrange(L
, &range
);
1972 if (strcmp(key
, "anchored") == 0) {
1973 lua_pushboolean(L
, view_selections_anchored(sel
));
1979 return index_common(L
);
1982 static int window_selection_newindex(lua_State
*L
) {
1983 Selection
*sel
= obj_lightref_check(L
, 1, VIS_LUA_TYPE_SELECTION
);
1986 if (lua_isstring(L
, 2)) {
1987 const char *key
= lua_tostring(L
, 2);
1988 if (strcmp(key
, "pos") == 0) {
1989 size_t pos
= checkpos(L
, 3);
1990 view_cursors_to(sel
, pos
);
1994 if (strcmp(key
, "range") == 0) {
1995 Filerange range
= getrange(L
, 3);
1996 if (text_range_valid(&range
)) {
1997 view_selections_set(sel
, &range
);
1998 view_selections_anchor(sel
, true);
2000 view_selection_clear(sel
);
2005 if (strcmp(key
, "anchored") == 0) {
2006 view_selections_anchor(sel
, lua_toboolean(L
, 3));
2010 return newindex_common(L
);
2014 * Move cursor of selection.
2016 * @tparam int line the 1-based line number
2017 * @tparam int col the 1-based column number
2019 static int window_selection_to(lua_State
*L
) {
2020 Selection
*sel
= obj_lightref_check(L
, 1, VIS_LUA_TYPE_SELECTION
);
2022 size_t line
= checkpos(L
, 2);
2023 size_t col
= checkpos(L
, 3);
2024 view_cursors_place(sel
, line
, col
);
2029 static const struct luaL_Reg window_selection_funcs
[] = {
2030 { "__index", window_selection_index
},
2031 { "__newindex", window_selection_newindex
},
2032 { "to", window_selection_to
},
2042 * @tfield string name the file name relative to current working directory or `nil` if not yet named
2046 * @tfield string path the absolute file path or `nil` if not yet named
2049 * File content by logical lines.
2051 * Assigning to array element `0` (`#lines+1`) will insert a new line at
2052 * the beginning (end) of the file.
2053 * @tfield Array(string) lines the file content accessible as 1-based array
2056 * local lines = vis.win.file.lines
2057 * for i=1, #lines do
2058 * lines[i] = i .. ": " .. lines[i]
2062 * File size in bytes.
2063 * @tfield int size the current file size in bytes
2067 * @tfield bool modified whether the file contains unsaved changes
2069 static int file_index(lua_State
*L
) {
2070 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2072 if (lua_isstring(L
, 2)) {
2073 const char *key
= lua_tostring(L
, 2);
2074 if (strcmp(key
, "name") == 0) {
2075 lua_pushstring(L
, file_name_get(file
));
2079 if (strcmp(key
, "path") == 0) {
2080 lua_pushstring(L
, file
->name
);
2084 if (strcmp(key
, "lines") == 0) {
2085 obj_ref_new(L
, file
->text
, VIS_LUA_TYPE_TEXT
);
2089 if (strcmp(key
, "size") == 0) {
2090 lua_pushunsigned(L
, text_size(file
->text
));
2094 if (strcmp(key
, "modified") == 0) {
2095 lua_pushboolean(L
, text_modified(file
->text
));
2100 return index_common(L
);
2104 * Insert data at position.
2106 * @tparam int pos the 0-based file position in bytes
2107 * @tparam string data the data to insert
2108 * @treturn bool whether the file content was successfully changed
2110 static int file_insert(lua_State
*L
) {
2111 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2112 size_t pos
= checkpos(L
, 2);
2114 luaL_checkstring(L
, 3);
2115 const char *data
= lua_tolstring(L
, 3, &len
);
2116 lua_pushboolean(L
, text_insert(file
->text
, pos
, data
, len
));
2121 * Delete data at position.
2124 * @tparam int pos the 0-based file position in bytes
2125 * @tparam int len the length in bytes to delete
2126 * @treturn bool whether the file content was successfully changed
2129 * Delete file range.
2132 * @tparam Range range the range to delete
2133 * @treturn bool whether the file content was successfully changed
2135 static int file_delete(lua_State
*L
) {
2136 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2137 Filerange range
= getrange(L
, 2);
2138 lua_pushboolean(L
, text_delete_range(file
->text
, &range
));
2143 * Create an iterator over all lines of the file.
2145 * For large files this is probably faster than @{lines}.
2146 * @function lines_iterator
2147 * @return the new iterator
2150 * for line in file:lines_iterator() do
2151 * -- do something with line
2154 static int file_lines_iterator_it(lua_State
*L
);
2155 static int file_lines_iterator(lua_State
*L
) {
2156 /* need to check second parameter first, because obj_ref_check_get
2157 * modifies the stack */
2158 size_t line
= luaL_optunsigned(L
, 2, 1);
2159 File
*file
= obj_ref_check_get(L
, 1, VIS_LUA_TYPE_FILE
);
2160 size_t *pos
= lua_newuserdata(L
, sizeof *pos
);
2161 *pos
= text_pos_by_lineno(file
->text
, line
);
2162 lua_pushcclosure(L
, file_lines_iterator_it
, 2);
2166 static int file_lines_iterator_it(lua_State
*L
) {
2167 File
*file
= *(File
**)lua_touserdata(L
, lua_upvalueindex(1));
2168 size_t *start
= lua_touserdata(L
, lua_upvalueindex(2));
2169 if (*start
== text_size(file
->text
))
2171 size_t end
= text_line_end(file
->text
, *start
);
2172 size_t len
= end
- *start
;
2173 char *buf
= lua_newuserdata(L
, len
);
2176 len
= text_bytes_get(file
->text
, *start
, len
, buf
);
2177 lua_pushlstring(L
, buf
, len
);
2178 *start
= text_line_next(file
->text
, end
);
2183 * Get file content of position and length.
2186 * @tparam int pos the 0-based file position in bytes
2187 * @tparam int len the length in bytes to read
2188 * @treturn string the file content corresponding to the range
2191 * local file = vis.win.file
2192 * local text = file:content(0, file.size)
2195 * Get file content of range.
2198 * @tparam Range range the range to read
2199 * @treturn string the file content corresponding to the range
2201 static int file_content(lua_State
*L
) {
2202 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2203 Filerange range
= getrange(L
, 2);
2204 if (!text_range_valid(&range
))
2206 size_t len
= text_range_size(&range
);
2207 char *data
= lua_newuserdata(L
, len
);
2210 len
= text_bytes_get(file
->text
, range
.start
, len
, data
);
2211 lua_pushlstring(L
, data
, len
);
2220 * @function mark_set
2221 * @tparam int pos the position to set the mark to, must be in [0, file.size]
2222 * @treturn Mark mark the mark which can be looked up later
2224 static int file_mark_set(lua_State
*L
) {
2225 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2226 size_t pos
= checkpos(L
, 2);
2227 Mark mark
= text_mark_set(file
->text
, pos
);
2229 obj_lightref_new(L
, (void*)mark
, VIS_LUA_TYPE_MARK
);
2236 * Get position of mark.
2237 * @function mark_get
2238 * @tparam Mark mark the mark to look up
2239 * @treturn int pos the position of the mark, or `nil` if invalid
2241 static int file_mark_get(lua_State
*L
) {
2242 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2243 Mark mark
= (Mark
)obj_lightref_check(L
, 2, VIS_LUA_TYPE_MARK
);
2244 size_t pos
= text_mark_get(file
->text
, mark
);
2248 lua_pushunsigned(L
, pos
);
2255 * @function text_object_word
2256 * @tparam int pos the position which must be part of the word
2257 * @treturn Range range the range
2263 * @function text_object_longword
2264 * @tparam int pos the position which must be part of the word
2265 * @treturn Range range the range
2268 static int file_text_object(lua_State
*L
) {
2269 Filerange range
= text_range_empty();
2270 File
*file
= obj_ref_check(L
, 1, VIS_LUA_TYPE_FILE
);
2271 size_t pos
= checkpos(L
, 2);
2272 size_t idx
= lua_tointeger(L
, lua_upvalueindex(1));
2273 if (idx
< LENGTH(vis_textobjects
)) {
2274 const TextObject
*txtobj
= &vis_textobjects
[idx
];
2276 range
= txtobj
->txt(file
->text
, pos
);
2278 pushrange(L
, &range
);
2282 static const struct luaL_Reg file_funcs
[] = {
2283 { "__index", file_index
},
2284 { "__newindex", newindex_common
},
2285 { "insert", file_insert
},
2286 { "delete", file_delete
},
2287 { "lines_iterator", file_lines_iterator
},
2288 { "content", file_content
},
2289 { "mark_set", file_mark_set
},
2290 { "mark_get", file_mark_get
},
2294 static int file_lines_index(lua_State
*L
) {
2295 Text
*txt
= obj_ref_check(L
, 1, VIS_LUA_TYPE_TEXT
);
2296 size_t line
= luaL_checkunsigned(L
, 2);
2297 size_t start
= text_pos_by_lineno(txt
, line
);
2298 size_t end
= text_line_end(txt
, start
);
2299 if (start
!= EPOS
&& end
!= EPOS
) {
2300 size_t size
= end
- start
;
2301 char *data
= lua_newuserdata(L
, size
);
2304 size
= text_bytes_get(txt
, start
, size
, data
);
2305 lua_pushlstring(L
, data
, size
);
2313 static int file_lines_newindex(lua_State
*L
) {
2314 Text
*txt
= obj_ref_check(L
, 1, VIS_LUA_TYPE_TEXT
);
2315 size_t line
= luaL_checkunsigned(L
, 2);
2317 const char *data
= luaL_checklstring(L
, 3, &size
);
2319 text_insert(txt
, 0, data
, size
);
2320 text_insert(txt
, size
, "\n", 1);
2323 size_t start
= text_pos_by_lineno(txt
, line
);
2324 size_t end
= text_line_end(txt
, start
);
2325 if (start
!= EPOS
&& end
!= EPOS
) {
2326 text_delete(txt
, start
, end
- start
);
2327 text_insert(txt
, start
, data
, size
);
2328 if (text_size(txt
) == start
+ size
)
2329 text_insert(txt
, text_size(txt
), "\n", 1);
2334 static int file_lines_len(lua_State
*L
) {
2335 Text
*txt
= obj_ref_check(L
, 1, VIS_LUA_TYPE_TEXT
);
2338 size_t size
= text_size(txt
);
2340 lines
= text_lineno_by_pos(txt
, size
);
2341 if (lines
> 1 && text_byte_get(txt
, size
-1, &lastchar
) && lastchar
== '\n')
2343 lua_pushunsigned(L
, lines
);
2347 static const struct luaL_Reg file_lines_funcs
[] = {
2348 { "__index", file_lines_index
},
2349 { "__newindex", file_lines_newindex
},
2350 { "__len", file_lines_len
},
2354 static int window_marks_index(lua_State
*L
) {
2356 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
2357 Win
*win
= obj_ref_check_containerof(L
, 1, VIS_LUA_TYPE_MARKS
, offsetof(Win
, saved_selections
));
2360 const char *symbol
= luaL_checkstring(L
, 2);
2361 if (strlen(symbol
) != 1)
2363 enum VisMark mark
= vis_mark_from(vis
, symbol
[0]);
2364 if (mark
== VIS_MARK_INVALID
)
2367 Array arr
= vis_mark_get(win
, mark
);
2368 for (size_t i
= 0, len
= array_length(&arr
); i
< len
; i
++) {
2369 Filerange
*range
= array_get(&arr
, i
);
2370 lua_pushunsigned(L
, i
+1);
2371 pushrange(L
, range
);
2372 lua_settable(L
, -3);
2374 array_release(&arr
);
2378 static int window_marks_newindex(lua_State
*L
) {
2379 Vis
*vis
= lua_touserdata(L
, lua_upvalueindex(1));
2380 Win
*win
= obj_ref_check_containerof(L
, 1, VIS_LUA_TYPE_MARKS
, offsetof(Win
, saved_selections
));
2383 const char *symbol
= luaL_checkstring(L
, 2);
2384 if (strlen(symbol
) != 1)
2386 enum VisMark mark
= vis_mark_from(vis
, symbol
[0]);
2387 if (mark
== VIS_MARK_INVALID
)
2391 array_init_sized(&ranges
, sizeof(Filerange
));
2393 if (lua_istable(L
, 3)) {
2395 while (lua_next(L
, 3)) {
2396 Filerange range
= getrange(L
, -1);
2397 if (text_range_valid(&range
))
2398 array_add(&ranges
, &range
);
2403 vis_mark_set(win
, mark
, &ranges
);
2404 array_release(&ranges
);
2408 static int window_marks_len(lua_State
*L
) {
2409 lua_pushunsigned(L
, VIS_MARK_INVALID
);
2413 static const struct luaL_Reg window_marks_funcs
[] = {
2414 { "__index", window_marks_index
},
2415 { "__newindex", window_marks_newindex
},
2416 { "__len", window_marks_len
},
2421 * The user interface.
2426 * Number of available colors.
2427 * @tfield int colors
2433 * For a valid range `start <= finish` holds.
2434 * An invalid range is represented as `nil`.
2438 * The beginning of the range.
2442 * The end of the range.
2443 * @tfield int finish
2454 * @tfield int NORMAL
2455 * @tfield int OPERATOR_PENDING
2456 * @tfield int INSERT
2457 * @tfield int REPLACE
2458 * @tfield int VISUAL
2459 * @tfield int VISUAL_LINE
2467 * This section describes the contract between the editor core and Lua
2468 * key handling functions mapped to symbolic keys using either @{Vis:map}
2471 * @section Key_Handling
2475 * Example of a key handling function.
2477 * The keyhandler is invoked with the pending content of the input queue
2478 * given as argument. This might be the empty string if no further input
2481 * The function is expected to return the number of *bytes* it has
2482 * consumed from the passed input keys. A negative return value is
2483 * interpreted as an indication that not enough input was available. The
2484 * function will be called again once the user has provided more input. A
2485 * missing return value (i.e. `nil`) is interpreted as zero, meaning
2486 * no further input was consumed but the function completed successfully.
2488 * @function keyhandler
2489 * @tparam string keys the keys following the mapping
2490 * @treturn int the number of *bytes* being consumed by the function (see above)
2491 * @see Vis:action_register
2495 * vis:map(vis.modes.INSERT, "<C-k>", function(keys)
2497 * return -1 -- need more input
2499 * local digraph = keys:sub(1, 2)
2500 * if digraph == "l*" then
2502 * return 2 -- consume 2 bytes of input
2504 * end, "Insert digraph")
2510 * These events are invoked from the editor core.
2511 * The following functions are invoked if they are registered in the
2512 * `vis.events` table. Users scripts should generally use the [Events](#events)
2513 * mechanism instead which multiplexes these core events.
2515 * @section Core_Events
2518 static void vis_lua_event_get(lua_State
*L
, const char *name
) {
2519 lua_getglobal(L
, "vis");
2520 lua_getfield(L
, -1, "events");
2521 if (lua_istable(L
, -1)) {
2522 lua_getfield(L
, -1, name
);
2527 static void vis_lua_event_call(Vis
*vis
, const char *name
) {
2528 lua_State
*L
= vis
->lua
;
2529 vis_lua_event_get(L
, name
);
2530 if (lua_isfunction(L
, -1))
2531 pcall(vis
, L
, 0, 0);
2535 static bool vis_lua_path_strip(Vis
*vis
) {
2536 lua_State
*L
= vis
->lua
;
2537 lua_getglobal(L
, "package");
2539 for (const char **var
= (const char*[]){ "path", "cpath", NULL
}; *var
; var
++) {
2541 lua_getfield(L
, -1, *var
);
2542 const char *path
= lua_tostring(L
, -1);
2547 char *copy
= strdup(path
), *stripped
= calloc(1, strlen(path
)+2);
2548 if (!copy
|| !stripped
) {
2554 for (char *elem
= copy
, *stripped_elem
= stripped
, *next
; elem
; elem
= next
) {
2555 if ((next
= strstr(elem
, ";")))
2557 if (strstr(elem
, "./"))
2558 continue; /* skip relative path entries */
2559 stripped_elem
+= sprintf(stripped_elem
, "%s;", elem
);
2562 lua_pushstring(L
, stripped
);
2563 lua_setfield(L
, -2, *var
);
2569 lua_pop(L
, 1); /* package */
2573 bool vis_lua_path_add(Vis
*vis
, const char *path
) {
2574 lua_State
*L
= vis
->lua
;
2577 lua_getglobal(L
, "package");
2578 lua_pushstring(L
, path
);
2579 lua_pushstring(L
, "/?.lua;");
2580 lua_pushstring(L
, path
);
2581 lua_pushstring(L
, "/?/init.lua;");
2582 lua_getfield(L
, -5, "path");
2584 lua_setfield(L
, -2, "path");
2585 lua_pop(L
, 1); /* package */
2589 bool vis_lua_paths_get(Vis
*vis
, char **lpath
, char **cpath
) {
2590 lua_State
*L
= vis
->lua
;
2594 lua_getglobal(L
, "package");
2595 lua_getfield(L
, -1, "path");
2596 s
= lua_tostring(L
, -1);
2597 *lpath
= s
? strdup(s
) : NULL
;
2598 lua_getfield(L
, -2, "cpath");
2599 s
= lua_tostring(L
, -1);
2600 *cpath
= s
? strdup(s
) : NULL
;
2604 static bool package_exist(Vis
*vis
, lua_State
*L
, const char *name
) {
2606 "local name = ...\n"
2607 "for _, searcher in ipairs(package.searchers or package.loaders) do\n"
2608 "local loader = searcher(name)\n"
2609 "if type(loader) == 'function' then\n"
2614 if (luaL_loadstring(L
, lua
) != LUA_OK
)
2616 lua_pushstring(L
, name
);
2617 /* an error indicates package exists */
2618 bool ret
= lua_pcall(L
, 1, 1, 0) != LUA_OK
|| lua_toboolean(L
, -1);
2623 static void *alloc_lua(void *ud
, void *ptr
, size_t osize
, size_t nsize
) {
2628 return realloc(ptr
, nsize
);
2633 * Editor initialization completed.
2634 * This event is emitted immediately after `visrc.lua` has been sourced, but
2635 * before any other events have occured, in particular the command line arguments
2636 * have not yet been processed.
2638 * Can be used to set *global* configuration options.
2641 void vis_lua_init(Vis
*vis
) {
2642 lua_State
*L
= lua_newstate(alloc_lua
, vis
);
2646 lua_atpanic(L
, &panic_handler
);
2651 extern int luaopen_lpeg(lua_State
*L
);
2652 lua_getglobal(L
, "package");
2653 lua_getfield(L
, -1, "preload");
2654 lua_pushcfunction(L
, luaopen_lpeg
);
2655 lua_setfield(L
, -2, "lpeg");
2659 /* remove any relative paths from lua's default package.path */
2660 vis_lua_path_strip(vis
);
2662 /* extends lua's package.path with:
2664 * - ./lua (relative path to the binary location)
2665 * - $XDG_CONFIG_HOME/vis (defaulting to $HOME/.config/vis)
2666 * - /etc/vis (for system-wide configuration provided by administrator)
2667 * - /usr/(local/)?share/vis (or whatever is specified during ./configure)
2668 * - package.path (standard lua search path)
2670 char path
[PATH_MAX
];
2672 vis_lua_path_add(vis
, VIS_PATH
);
2674 /* try to get users home directory */
2675 const char *home
= getenv("HOME");
2676 if (!home
|| !*home
) {
2677 struct passwd
*pw
= getpwuid(getuid());
2682 vis_lua_path_add(vis
, "/etc/vis");
2684 const char *xdg_config
= getenv("XDG_CONFIG_HOME");
2686 snprintf(path
, sizeof path
, "%s/vis", xdg_config
);
2687 vis_lua_path_add(vis
, path
);
2688 } else if (home
&& *home
) {
2689 snprintf(path
, sizeof path
, "%s/.config/vis", home
);
2690 vis_lua_path_add(vis
, path
);
2693 ssize_t len
= readlink("/proc/self/exe", path
, sizeof(path
)-1);
2696 /* some idotic dirname(3) implementations return pointers to statically
2697 * allocated memory, hence we use memmove to copy it back */
2698 char *dir
= dirname(path
);
2700 size_t len
= strlen(dir
)+1;
2701 if (len
< sizeof(path
) - sizeof("/lua")) {
2702 memmove(path
, dir
, len
);
2703 strcat(path
, "/lua");
2704 vis_lua_path_add(vis
, path
);
2709 vis_lua_path_add(vis
, getenv("VIS_PATH"));
2711 /* table in registry to lookup object type, stores metatable -> type mapping */
2713 lua_setfield(L
, LUA_REGISTRYINDEX
, "vis.types");
2714 /* table in registry to track lifetimes of C objects */
2716 lua_setfield(L
, LUA_REGISTRYINDEX
, "vis.objects");
2717 /* table in registry to store references to Lua functions */
2719 lua_setfield(L
, LUA_REGISTRYINDEX
, "vis.functions");
2720 /* metatable used to type check user data */
2721 obj_type_new(L
, VIS_LUA_TYPE_VIS
);
2722 luaL_setfuncs(L
, vis_lua
, 0);
2724 lua_setfield(L
, -2, "types");
2725 /* create reference to main vis object, such that the further
2726 * calls to obj_type_new can register the type meta tables in
2727 * vis.types[name] */
2728 obj_ref_new(L
, vis
, "vis");
2729 lua_setglobal(L
, "vis");
2731 obj_type_new(L
, VIS_LUA_TYPE_FILE
);
2734 enum VisTextObject id
;
2737 { VIS_TEXTOBJECT_INNER_WORD
, "text_object_word" },
2738 { VIS_TEXTOBJECT_INNER_LONGWORD
, "text_object_longword" },
2741 for (size_t i
= 0; i
< LENGTH(textobjects
); i
++) {
2742 lua_pushunsigned(L
, textobjects
[i
].id
);
2743 lua_pushcclosure(L
, file_text_object
, 1);
2744 lua_setfield(L
, -2, textobjects
[i
].name
);
2747 luaL_setfuncs(L
, file_funcs
, 0);
2749 obj_type_new(L
, VIS_LUA_TYPE_TEXT
);
2750 luaL_setfuncs(L
, file_lines_funcs
, 0);
2751 obj_type_new(L
, VIS_LUA_TYPE_WINDOW
);
2752 luaL_setfuncs(L
, window_funcs
, 0);
2758 { UI_STYLE_DEFAULT
, "STYLE_DEFAULT" },
2759 { UI_STYLE_CURSOR
, "STYLE_CURSOR" },
2760 { UI_STYLE_CURSOR_PRIMARY
, "STYLE_CURSOR_PRIMARY" },
2761 { UI_STYLE_CURSOR_LINE
, "STYLE_CURSOR_LINE" },
2762 { UI_STYLE_SELECTION
, "STYLE_SELECTION" },
2763 { UI_STYLE_LINENUMBER
, "STYLE_LINENUMBER" },
2764 { UI_STYLE_LINENUMBER_CURSOR
, "STYLE_LINENUMBER_CURSOR" },
2765 { UI_STYLE_COLOR_COLUMN
, "STYLE_COLOR_COLUMN" },
2766 { UI_STYLE_STATUS
, "STYLE_STATUS" },
2767 { UI_STYLE_STATUS_FOCUSED
, "STYLE_STATUS_FOCUSED" },
2768 { UI_STYLE_SEPARATOR
, "STYLE_SEPARATOR" },
2769 { UI_STYLE_INFO
, "STYLE_INFO" },
2770 { UI_STYLE_EOF
, "STYLE_EOF" },
2773 for (size_t i
= 0; i
< LENGTH(styles
); i
++) {
2774 lua_pushunsigned(L
, styles
[i
].id
);
2775 lua_setfield(L
, -2, styles
[i
].name
);
2778 obj_type_new(L
, VIS_LUA_TYPE_MARK
);
2779 obj_type_new(L
, VIS_LUA_TYPE_MARKS
);
2780 lua_pushlightuserdata(L
, vis
);
2781 luaL_setfuncs(L
, window_marks_funcs
, 1);
2783 obj_type_new(L
, VIS_LUA_TYPE_SELECTION
);
2784 luaL_setfuncs(L
, window_selection_funcs
, 0);
2785 obj_type_new(L
, VIS_LUA_TYPE_SELECTIONS
);
2786 luaL_setfuncs(L
, window_selections_funcs
, 0);
2788 obj_type_new(L
, VIS_LUA_TYPE_UI
);
2789 luaL_setfuncs(L
, ui_funcs
, 0);
2790 lua_pushunsigned(L
, vis
->ui
->colors(vis
->ui
));
2791 lua_setfield(L
, -2, "colors");
2793 obj_type_new(L
, VIS_LUA_TYPE_REGISTERS
);
2794 lua_pushlightuserdata(L
, vis
);
2795 luaL_setfuncs(L
, registers_funcs
, 1);
2797 obj_type_new(L
, VIS_LUA_TYPE_KEYACTION
);
2799 lua_getglobal(L
, "vis");
2800 lua_getmetatable(L
, -1);
2802 lua_pushstring(L
, VERSION
);
2803 lua_setfield(L
, -2, "VERSION");
2807 static const struct {
2811 { VIS_MODE_NORMAL
, "NORMAL" },
2812 { VIS_MODE_OPERATOR_PENDING
, "OPERATOR_PENDING" },
2813 { VIS_MODE_VISUAL
, "VISUAL" },
2814 { VIS_MODE_VISUAL_LINE
, "VISUAL_LINE" },
2815 { VIS_MODE_INSERT
, "INSERT" },
2816 { VIS_MODE_REPLACE
, "REPLACE" },
2819 for (size_t i
= 0; i
< LENGTH(modes
); i
++) {
2820 lua_pushunsigned(L
, modes
[i
].id
);
2821 lua_setfield(L
, -2, modes
[i
].name
);
2824 lua_setfield(L
, -2, "modes");
2826 if (!package_exist(vis
, L
, "visrc")) {
2827 vis_info_show(vis
, "WARNING: failed to load visrc.lua");
2829 lua_getglobal(L
, "require");
2830 lua_pushstring(L
, "visrc");
2831 pcall(vis
, L
, 1, 0);
2832 vis_lua_event_call(vis
, "init");
2837 * Editor startup completed.
2838 * This event is emitted immediately before the main loop starts.
2839 * At this point all files are loaded and corresponding windows are created.
2840 * We are about to process interactive keyboard input.
2843 void vis_lua_start(Vis
*vis
) {
2844 vis_lua_event_call(vis
, "start");
2848 * Editor is about to terminate.
2851 void vis_lua_quit(Vis
*vis
) {
2854 vis_lua_event_call(vis
, "quit");
2855 lua_close(vis
->lua
);
2860 * Input key event in either input or replace mode.
2862 * @tparam string key
2863 * @treturn bool whether the key was cosumed or not
2865 static bool vis_lua_input(Vis
*vis
, const char *key
, size_t len
) {
2866 lua_State
*L
= vis
->lua
;
2867 if (!L
|| !vis
->win
|| vis
->win
->file
->internal
)
2870 vis_lua_event_get(L
, "input");
2871 if (lua_isfunction(L
, -1)) {
2872 lua_pushlstring(L
, key
, len
);
2873 if (pcall(vis
, L
, 1, 1) == 0) {
2874 ret
= lua_isboolean(L
, -1) && lua_toboolean(L
, -1);
2882 void vis_lua_mode_insert_input(Vis
*vis
, const char *key
, size_t len
) {
2883 if (!vis_lua_input(vis
, key
, len
))
2884 vis_insert_key(vis
, key
, len
);
2887 void vis_lua_mode_replace_input(Vis
*vis
, const char *key
, size_t len
) {
2888 if (!vis_lua_input(vis
, key
, len
))
2889 vis_replace_key(vis
, key
, len
);
2894 * @function file_open
2895 * @tparam File file the file to be opened
2897 void vis_lua_file_open(Vis
*vis
, File
*file
) {
2898 debug("event: file-open: %s %p %p\n", file
->name
? file
->name
: "unnamed", (void*)file
, (void*)file
->text
);
2899 lua_State
*L
= vis
->lua
;
2902 vis_lua_event_get(L
, "file_open");
2903 if (lua_isfunction(L
, -1)) {
2904 obj_ref_new(L
, file
, VIS_LUA_TYPE_FILE
);
2905 pcall(vis
, L
, 1, 0);
2912 * Triggered *before* the file is being written.
2913 * @function file_save_pre
2914 * @tparam File file the file being written
2915 * @tparam string path the absolute path to which the file will be written, `nil` if standard output
2916 * @treturn bool whether the write operation should be proceeded
2918 bool vis_lua_file_save_pre(Vis
*vis
, File
*file
, const char *path
) {
2919 lua_State
*L
= vis
->lua
;
2922 vis_lua_event_get(L
, "file_save_pre");
2923 if (lua_isfunction(L
, -1)) {
2924 obj_ref_new(L
, file
, VIS_LUA_TYPE_FILE
);
2925 lua_pushstring(L
, path
);
2926 if (pcall(vis
, L
, 2, 1) != 0)
2928 return !lua_isboolean(L
, -1) || lua_toboolean(L
, -1);
2936 * Triggered *after* a successfull write operation.
2937 * @function file_save_post
2938 * @tparam File file the file which was written
2939 * @tparam string path the absolute path to which it was written, `nil` if standard output
2941 void vis_lua_file_save_post(Vis
*vis
, File
*file
, const char *path
) {
2942 lua_State
*L
= vis
->lua
;
2945 vis_lua_event_get(L
, "file_save_post");
2946 if (lua_isfunction(L
, -1)) {
2947 obj_ref_new(L
, file
, VIS_LUA_TYPE_FILE
);
2948 lua_pushstring(L
, path
);
2949 pcall(vis
, L
, 2, 0);
2956 * The last window displaying the file has been closed.
2957 * @function file_close
2958 * @tparam File file the file being closed
2960 void vis_lua_file_close(Vis
*vis
, File
*file
) {
2961 debug("event: file-close: %s %p %p\n", file
->name
? file
->name
: "unnamed", (void*)file
, (void*)file
->text
);
2962 lua_State
*L
= vis
->lua
;
2965 vis_lua_event_get(L
, "file_close");
2966 if (lua_isfunction(L
, -1)) {
2967 obj_ref_new(L
, file
, VIS_LUA_TYPE_FILE
);
2968 pcall(vis
, L
, 1, 0);
2970 obj_ref_free(L
, file
->marks
);
2971 obj_ref_free(L
, file
->text
);
2972 obj_ref_free(L
, file
);
2978 * A new window has been created.
2979 * @function win_open
2980 * @tparam Window win the window being opened
2982 void vis_lua_win_open(Vis
*vis
, Win
*win
) {
2983 debug("event: win-open: %s %p %p\n", win
->file
->name
? win
->file
->name
: "unnamed", (void*)win
, (void*)win
->view
);
2984 lua_State
*L
= vis
->lua
;
2987 vis_lua_event_get(L
, "win_open");
2988 if (lua_isfunction(L
, -1)) {
2989 obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
);
2990 pcall(vis
, L
, 1, 0);
2997 * An window is being closed.
2998 * @function win_close
2999 * @tparam Window win the window being closed
3001 void vis_lua_win_close(Vis
*vis
, Win
*win
) {
3002 debug("event: win-close: %s %p %p\n", win
->file
->name
? win
->file
->name
: "unnamed", (void*)win
, (void*)win
->view
);
3003 lua_State
*L
= vis
->lua
;
3006 vis_lua_event_get(L
, "win_close");
3007 if (lua_isfunction(L
, -1)) {
3008 obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
);
3009 pcall(vis
, L
, 1, 0);
3011 obj_ref_free(L
, win
->view
);
3012 obj_ref_free(L
, win
);
3018 * The window has been redrawn and the syntax highlighting needs to be performed.
3019 * @function win_highlight
3020 * @tparam Window win the window being redrawn
3023 void vis_lua_win_highlight(Vis
*vis
, Win
*win
) {
3024 lua_State
*L
= vis
->lua
;
3027 vis_lua_event_get(L
, "win_highlight");
3028 if (lua_isfunction(L
, -1)) {
3029 obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
);
3030 pcall(vis
, L
, 1, 0);
3036 * Window status bar redraw.
3037 * @function win_status
3038 * @tparam Window win the affected window
3041 void vis_lua_win_status(Vis
*vis
, Win
*win
) {
3042 lua_State
*L
= vis
->lua
;
3043 if (!L
|| win
->file
->internal
) {
3044 window_status_update(vis
, win
);
3047 vis_lua_event_get(L
, "win_status");
3048 if (lua_isfunction(L
, -1)) {
3049 obj_ref_new(L
, win
, VIS_LUA_TYPE_WINDOW
);
3050 pcall(vis
, L
, 1, 0);
3052 window_status_update(vis
, win
);