Merge pull request #16912 from shadmansaleh/enhance/lua_cmd_inspect

feat(lua): make :lua =expr print result of expr
This commit is contained in:
Björn Linse 2022-01-04 14:34:42 +01:00 committed by GitHub
commit e79a588937
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 3 deletions

View File

@ -249,13 +249,15 @@ arguments separated by " " (space) instead of "\t" (tab).
*:lua*
:[range]lua {chunk}
Executes Lua chunk {chunk}.
if {chunk} starts with "=" the rest of the chunk is
evaluated as an expression and printed. `:lua =expr`
is equivalent to `:lua print(vim.inspect(expr))`
Examples: >
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
< To see the Lua version: >
:lua print(_VERSION)
< To see the LuaJIT version: >
:lua print(jit.version)
:lua =jit.version
<
*:lua-heredoc*
:[range]lua << [endmarker]

View File

@ -1115,11 +1115,23 @@ void ex_lua(exarg_T *const eap)
FUNC_ATTR_NONNULL_ALL
{
size_t len;
char *const code = script_get(eap, &len);
char *code = script_get(eap, &len);
if (eap->skip) {
xfree(code);
return;
}
// When =expr is used transform it to print(vim.inspect(expr))
if (code[0] == '=') {
len += sizeof("print(vim.inspect())") - sizeof("=");
// code_buf needs to be 1 char larger then len for null byte in the end.
// lua nlua_typval_exec doesn't expect null terminated string so len
// needs to end before null byte.
char *code_buf = xmallocz(len);
vim_snprintf(code_buf, len+1, "print(vim.inspect(%s))", code+1);
xfree(code);
code = code_buf;
}
nlua_typval_exec(code, len, ":lua", NULL, 0, false, NULL);
xfree(code);

View File

@ -141,6 +141,15 @@ describe(':lua command', function()
{4:Press ENTER or type command to continue}^ |
]]}
end)
it('Can print results of =expr', function()
helpers.exec_lua("x = 5")
eq("5", helpers.exec_capture(':lua =x'))
helpers.exec_lua("function x() return 'hello' end")
eq([["hello"]], helpers.exec_capture(':lua = x()'))
helpers.exec_lua("x = {a = 1, b = 2}")
eq("{\n a = 1,\n b = 2\n}", helpers.exec_capture(':lua =x'))
end)
end)
describe(':luado command', function()