refactor!: rename vim.pretty_print => vim.print

Problem:
The function name `vim.pretty_print`:
1. is verbose, which partially defeats its purpose as sugar
2. does not draw from existing precedent or any sort of convention
   (except external projects like penlight or python?), which reduces
   discoverability, and degrades signaling about best practices.

Solution:
- Rename to `vim.print`.
- Change the behavior so that
  1. strings are printed without quotes
  2. each arg is printed on its own line
  3. tables are indented with 2 instead of 4 spaces
- Example:
  :lua ='a', 'b', 42, {a=3}
  a
  b
  42
  {
    a = 3
  }

Comparison of alternatives:
- `vim.print`:
  - pro: consistent with Lua's `print()`
  - pro: aligns with potential `nvim_print` API function which will
    replace nvim_echo, nvim_notify, etc.
  - con: behaves differently than Lua's `print()`, slightly misleading?
- `vim.echo`:
  - pro: `:echo` has similar "pretty print" behavior.
  - con: inconsistent with Lua idioms.
- `vim.p`:
  - pro: very short, fits with `vim.o`, etc.
  - con: not as discoverable as "echo"
  - con: less opportunity for `local p = vim.p` because of potential shadowing.
This commit is contained in:
Justin M. Keyes
2023-03-07 16:04:57 +01:00
parent 5aec611469
commit 673d2b52fa
11 changed files with 103 additions and 58 deletions

View File

@@ -129,6 +129,7 @@ TREESITTER FUNCTIONS
LUA LUA
- *vim.register_keystroke_callback()* Use |vim.on_key()| instead. - *vim.register_keystroke_callback()* Use |vim.on_key()| instead.
- *vim.pretty_print()* Use |vim.print()| instead.
NORMAL COMMANDS NORMAL COMMANDS
- *]f* *[f* Same as "gf". - *]f* *[f* Same as "gf".

View File

@@ -325,7 +325,7 @@ Example: >lua
vim.api.nvim_create_autocmd('DiagnosticChanged', { vim.api.nvim_create_autocmd('DiagnosticChanged', {
callback = function(args) callback = function(args)
local diagnostics = args.data.diagnostics local diagnostics = args.data.diagnostics
vim.pretty_print(diagnostics) vim.print(diagnostics)
end, end,
}) })
< <

View File

@@ -10,16 +10,16 @@
============================================================================== ==============================================================================
Introduction *lua-guide* Introduction *lua-guide*
This guide will go through the basics of using Lua in Neovim. It is not meant This guide will go through the basics of using Lua in Nvim. It is not meant
to be a comprehensive encyclopedia of all available features, nor will it to be a comprehensive encyclopedia of all available features, nor will it
detail all intricacies. Think of it as a survival kit -- the bare minimum detail all intricacies. Think of it as a survival kit -- the bare minimum
needed to know to comfortably get started on using Lua in Neovim. needed to know to comfortably get started on using Lua in Nvim.
An important thing to note is that this isn't a guide to the Lua language An important thing to note is that this isn't a guide to the Lua language
itself. Rather, this is a guide on how to configure and modify Neovim through itself. Rather, this is a guide on how to configure and modify Nvim through
the Lua language and the functions we provide to help with this. Take a look the Lua language and the functions we provide to help with this. Take a look
at |luaref| and |lua-concepts| if you'd like to learn more about Lua itself. at |luaref| and |lua-concepts| if you'd like to learn more about Lua itself.
Similarly, this guide assumes some familiarity with the basics of Neovim Similarly, this guide assumes some familiarity with the basics of Nvim
(commands, options, mappings, autocommands), which are covered in the (commands, options, mappings, autocommands), which are covered in the
|user-manual|. |user-manual|.
@@ -27,7 +27,7 @@ Similarly, this guide assumes some familiarity with the basics of Neovim
Some words on the API *lua-guide-api* Some words on the API *lua-guide-api*
The purpose of this guide is to introduce the different ways of interacting The purpose of this guide is to introduce the different ways of interacting
with Neovim through Lua (the "API"). This API consists of three different with Nvim through Lua (the "API"). This API consists of three different
layers: layers:
1. The "Vim API" inherited from Vim: |ex-commands| and |builtin-functions| as 1. The "Vim API" inherited from Vim: |ex-commands| and |builtin-functions| as
@@ -35,14 +35,14 @@ well as |user-function|s in Vimscript. These are accessed through |vim.cmd()|
and |vim.fn| respectively, which are discussed under |lua-guide-vimscript| and |vim.fn| respectively, which are discussed under |lua-guide-vimscript|
below. below.
2. The "Neovim API" written in C for use in remote plugins and GUIs; see |api|. 2. The "Nvim API" written in C for use in remote plugins and GUIs; see |api|.
These functions are accessed through |vim.api|. These functions are accessed through |vim.api|.
3. The "Lua API" written in and specifically for Lua. These are any other 3. The "Lua API" written in and specifically for Lua. These are any other
functions accessible through `vim.*` not mentioned already; see |lua-stdlib|. functions accessible through `vim.*` not mentioned already; see |lua-stdlib|.
This distinction is important, as API functions inherit behavior from their This distinction is important, as API functions inherit behavior from their
original layer: For example, Neovim API functions always need all arguments to original layer: For example, Nvim API functions always need all arguments to
be specified even if Lua itself allows omitting arguments (which are then be specified even if Lua itself allows omitting arguments (which are then
passed as `nil`); and Vim API functions can use 0-based indexing even if Lua passed as `nil`); and Vim API functions can use 0-based indexing even if Lua
arrays are 1-indexed by default. arrays are 1-indexed by default.
@@ -58,7 +58,7 @@ convenient to use from Lua.
============================================================================== ==============================================================================
Using Lua *lua-guide-using-Lua* Using Lua *lua-guide-using-Lua*
To run Lua code from the Neovim command line, use the |:lua| command: To run Lua code from the Nvim command line, use the |:lua| command:
>vim >vim
:lua print("Hello!") :lua print("Hello!")
< <
@@ -69,10 +69,10 @@ local keyword are not accessible outside of the command. This won't work:
:lua print(foo) :lua print(foo)
" prints "nil" instead of "1" " prints "nil" instead of "1"
< <
You can also use `:lua=`, which is the same as `:lua vim.pretty_print(...)`, You can also use `:lua=`, which is equivalent to `:lua vim.print(...)`, to
to conveniently check the value of a variable or a table: conveniently check the value of a variable or a table:
>vim >vim
:lua=package :lua =package
< <
To run a Lua script in an external file, you can use the |:source| command To run a Lua script in an external file, you can use the |:source| command
exactly like for a Vimscript file: exactly like for a Vimscript file:
@@ -92,7 +92,7 @@ Finally, you can include Lua code in a Vimscript file by putting it inside a
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Using Lua files on startup *lua-guide-config* Using Lua files on startup *lua-guide-config*
Neovim supports using `init.vim` or `init.lua` as the configuration file, but Nvim supports using `init.vim` or `init.lua` as the configuration file, but
not both at the same time. This should be placed in your |config| directory, not both at the same time. This should be placed in your |config| directory,
which is typically `~/.config/nvim` for Linux, BSD, or macOS, and which is typically `~/.config/nvim` for Linux, BSD, or macOS, and
`~/AppData/Local/nvim/` for Windows. Note that you can use Lua in `init.vim` `~/AppData/Local/nvim/` for Windows. Note that you can use Lua in `init.vim`
@@ -279,7 +279,7 @@ Note that you cannot directly change fields of array variables. This won't
work: work:
>lua >lua
vim.g.some_global_variable.key2 = 400 vim.g.some_global_variable.key2 = 400
vim.pretty_print(vim.g.some_global_variable) vim.print(vim.g.some_global_variable)
--> { key1 = "value", key2 = 300 } --> { key1 = "value", key2 = 300 }
< <
Instead, you need to create an intermediate Lua table and change this: Instead, you need to create an intermediate Lua table and change this:
@@ -287,7 +287,7 @@ Instead, you need to create an intermediate Lua table and change this:
local temp_table = vim.g.some_global_variable local temp_table = vim.g.some_global_variable
temp_table.key2 = 400 temp_table.key2 = 400
vim.g.some_global_variable = temp_table vim.g.some_global_variable = temp_table
vim.pretty_print(vim.g.some_global_variable) vim.print(vim.g.some_global_variable)
--> { key1 = "value", key2 = 400 } --> { key1 = "value", key2 = 400 }
< <
To delete a variable, simply set it to `nil`: To delete a variable, simply set it to `nil`:
@@ -350,7 +350,7 @@ use |vim.opt:get()|:
--> {...} (big table) --> {...} (big table)
print(vim.opt.smarttab:get()) print(vim.opt.smarttab:get())
--> false --> false
vim.pretty_print(vim.opt.listchars:get()) vim.print(vim.opt.listchars:get())
--> { space = '_', tab = '>~' } --> { space = '_', tab = '>~' }
< <
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
@@ -488,7 +488,7 @@ Autocommands *lua-guide-autocommands*
An |autocommand| is a Vim command or a Lua function that is automatically An |autocommand| is a Vim command or a Lua function that is automatically
executed whenever one or more |events| are triggered, e.g., when a file is executed whenever one or more |events| are triggered, e.g., when a file is
read or written, or when a window is created. These are accessible from Lua read or written, or when a window is created. These are accessible from Lua
through the Neovim API. through the Nvim API.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Creating autocommands *lua-guide-autocommand-create* Creating autocommands *lua-guide-autocommand-create*
@@ -530,7 +530,7 @@ Examples:
}) })
< <
Neovim will always call a Lua function with a single table containing information Nvim will always call a Lua function with a single table containing information
about the triggered autocommand. The most useful keys are about the triggered autocommand. The most useful keys are
• `match`: a string that matched the `pattern` (see |<amatch>|) • `match`: a string that matched the `pattern` (see |<amatch>|)
• `buf`: the number of the buffer the event was triggered in (see |<abuf>|) • `buf`: the number of the buffer the event was triggered in (see |<abuf>|)
@@ -667,9 +667,8 @@ cover only the basics of this advanced topic.
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Creating user commands *lua-guide-commands-create* Creating user commands *lua-guide-commands-create*
User commands can be created through the Neovim API with User commands can be created through with |nvim_create_user_command()|. This
`vim.api.`|nvim_create_user_command()|. This function takes three mandatory function takes three mandatory arguments:
arguments:
• a string that is the name of the command (which must start with an uppercase • a string that is the name of the command (which must start with an uppercase
letter to distinguish it from builtin commands); letter to distinguish it from builtin commands);
• a string containing Vim commands or a Lua function that is executed when the • a string containing Vim commands or a Lua function that is executed when the

View File

@@ -1239,7 +1239,7 @@ which is accessed through |vim.opt:get()|:
print(vim.o.wildignore) print(vim.o.wildignore)
< <
In Lua using `vim.opt`: >lua In Lua using `vim.opt`: >lua
vim.pretty_print(vim.opt.wildignore:get()) vim.print(vim.opt.wildignore:get())
< <
In any of the above examples, to replicate the behavior |:setlocal|, use In any of the above examples, to replicate the behavior |:setlocal|, use
@@ -1258,7 +1258,7 @@ Option:get()
the values as entries in the array: >lua the values as entries in the array: >lua
vim.cmd [[set wildignore=*.pyc,*.o]] vim.cmd [[set wildignore=*.pyc,*.o]]
vim.pretty_print(vim.opt.wildignore:get()) vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", } -- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
@@ -1271,7 +1271,7 @@ Option:get()
the names as keys and the values as entries: >lua the names as keys and the values as entries: >lua
vim.cmd [[set listchars=space:_,tab:>~]] vim.cmd [[set listchars=space:_,tab:>~]]
vim.pretty_print(vim.opt.listchars:get()) vim.print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", } -- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do for char, representation in pairs(vim.opt.listchars:get()) do
@@ -1282,7 +1282,7 @@ Option:get()
as keys and `true` as entries. >lua as keys and `true` as entries. >lua
vim.cmd [[set formatoptions=njtcroql]] vim.cmd [[set formatoptions=njtcroql]]
vim.pretty_print(vim.opt.formatoptions:get()) vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... } -- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get() local format_opts = vim.opt.formatoptions:get()
@@ -1496,10 +1496,11 @@ paste({lines}, {phase}) *vim.paste()*
See also: ~ See also: ~
|paste| @alias paste_phase -1 | 1 | 2 | 3 |paste| @alias paste_phase -1 | 1 | 2 | 3
pretty_print({...}) *vim.pretty_print()* print({...}) *vim.print()*
Prints given arguments in human-readable format. Example: >lua "Pretty prints" the given arguments and returns them unmodified.
-- Print highlight group Normal and store it's contents in a variable.
local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true)) Example: >lua
local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
< <
Return: ~ Return: ~

View File

@@ -55,6 +55,8 @@ The following changes may require adaptations in user config or plugins.
- The `concat` option has been removed as it was not consistently applied. - The `concat` option has been removed as it was not consistently applied.
- Invalid ranges now cause an error instead of returning `nil`. - Invalid ranges now cause an error instead of returning `nil`.
• Renamed vim.pretty_print to vim.print. |deprecated|
============================================================================== ==============================================================================
NEW FEATURES *news-features* NEW FEATURES *news-features*

View File

@@ -778,22 +778,37 @@ do
end end
end end
---Prints given arguments in human-readable format. ---@private
---Example:
---<pre>lua
--- -- Print highlight group Normal and store it's contents in a variable.
--- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
---</pre>
---@see |vim.inspect()|
---@return any # given arguments.
function vim.pretty_print(...) function vim.pretty_print(...)
local objects = {} vim.deprecate('vim.pretty_print', 'vim.print', '0.10')
for i = 1, select('#', ...) do return vim.print(...)
local v = select(i, ...) end
table.insert(objects, vim.inspect(v))
--- "Pretty prints" the given arguments and returns them unmodified.
---
--- Example:
--- <pre>lua
--- local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
--- </pre>
---
--- @see |vim.inspect()|
--- @return any # given arguments.
function vim.print(...)
if vim.in_fast_event() then
print(...)
return ...
end
for i = 1, select('#', ...) do
local o = select(i, ...)
if type(o) == 'string' then
vim.api.nvim_out_write(o)
else
vim.api.nvim_out_write(vim.inspect(o, { newline = '\n', indent = ' ' }))
end
vim.api.nvim_out_write('\n')
end end
print(table.concat(objects, ' '))
return ... return ...
end end

View File

@@ -1,6 +1,6 @@
vim.api.nvim_create_user_command('Inspect', function(cmd) vim.api.nvim_create_user_command('Inspect', function(cmd)
if cmd.bang then if cmd.bang then
vim.pretty_print(vim.inspect_pos()) vim.print(vim.inspect_pos())
else else
vim.show_pos() vim.show_pos()
end end

View File

@@ -1623,12 +1623,12 @@ void ex_lua(exarg_T *const eap)
} }
// When =expr is used transform it to print(vim.inspect(expr)) // When =expr is used transform it to print(vim.inspect(expr))
if (code[0] == '=') { if (code[0] == '=') {
len += sizeof("vim.pretty_print()") - sizeof("="); len += sizeof("vim.print()") - sizeof("=");
// code_buf needs to be 1 char larger then len for null byte in the end. // 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 // lua nlua_typval_exec doesn't expect null terminated string so len
// needs to end before null byte. // needs to end before null byte.
char *code_buf = xmallocz(len); char *code_buf = xmallocz(len);
vim_snprintf(code_buf, len + 1, "vim.pretty_print(%s)", code + 1); vim_snprintf(code_buf, len + 1, "vim.print(%s)", code + 1);
xfree(code); xfree(code);
code = code_buf; code = code_buf;
} }

View File

@@ -4042,7 +4042,7 @@ describe('API', function()
it('splits arguments correctly for Lua callback', function() it('splits arguments correctly for Lua callback', function()
meths.exec_lua([[ meths.exec_lua([[
local function FooFunc(opts) local function FooFunc(opts)
vim.pretty_print(opts.fargs) vim.print(opts.fargs)
end end
vim.api.nvim_create_user_command("Foo", FooFunc, { nargs = '+' }) vim.api.nvim_create_user_command("Foo", FooFunc, { nargs = '+' })

View File

@@ -8,6 +8,8 @@ local eval = helpers.eval
local feed = helpers.feed local feed = helpers.feed
local clear = helpers.clear local clear = helpers.clear
local meths = helpers.meths local meths = helpers.meths
local exec_lua = helpers.exec_lua
local exec_capture = helpers.exec_capture
local funcs = helpers.funcs local funcs = helpers.funcs
local source = helpers.source local source = helpers.source
local dedent = helpers.dedent local dedent = helpers.dedent
@@ -15,7 +17,6 @@ local command = helpers.command
local exc_exec = helpers.exc_exec local exc_exec = helpers.exc_exec
local pcall_err = helpers.pcall_err local pcall_err = helpers.pcall_err
local write_file = helpers.write_file local write_file = helpers.write_file
local exec_capture = helpers.exec_capture
local curbufmeths = helpers.curbufmeths local curbufmeths = helpers.curbufmeths
local remove_trace = helpers.remove_trace local remove_trace = helpers.remove_trace
@@ -142,22 +143,29 @@ describe(':lua command', function()
]]} ]]}
end) end)
it('Can print results of =expr', function() it('prints result of =expr', function()
helpers.exec_lua("x = 5") exec_lua("x = 5")
eq("5", helpers.exec_capture(':lua =x')) eq("5", exec_capture(':lua =x'))
helpers.exec_lua("function x() return 'hello' end") exec_lua("function x() return 'hello' end")
eq([["hello"]], helpers.exec_capture(':lua = x()')) eq('hello', exec_capture(':lua = x()'))
helpers.exec_lua("x = {a = 1, b = 2}") exec_lua("x = {a = 1, b = 2}")
eq("{\n a = 1,\n b = 2\n}", helpers.exec_capture(':lua =x')) eq("{\n a = 1,\n b = 2\n}", exec_capture(':lua =x'))
helpers.exec_lua([[function x(success) exec_lua([[function x(success)
if success then if success then
return true, "Return value" return true, "Return value"
else else
return false, nil, "Error message" return false, nil, "Error message"
end end
end]]) end]])
eq([[true "Return value"]], helpers.exec_capture(':lua =x(true)')) eq(dedent[[
eq([[false nil "Error message"]], helpers.exec_capture(':lua =x(false)')) true
Return value]],
exec_capture(':lua =x(true)'))
eq(dedent[[
false
nil
Error message]],
exec_capture(':lua =x(false)'))
end) end)
end) end)

View File

@@ -6,6 +6,7 @@ local nvim_prog = helpers.nvim_prog
local funcs = helpers.funcs local funcs = helpers.funcs
local meths = helpers.meths local meths = helpers.meths
local command = helpers.command local command = helpers.command
local dedent = helpers.dedent
local insert = helpers.insert local insert = helpers.insert
local clear = helpers.clear local clear = helpers.clear
local eq = helpers.eq local eq = helpers.eq
@@ -2269,7 +2270,7 @@ describe('lua stdlib', function()
describe('vim.region', function() describe('vim.region', function()
it('charwise', function() it('charwise', function()
insert(helpers.dedent( [[ insert(dedent( [[
text tααt tααt text text tααt tααt text
text tαxt txtα tex text tαxt txtα tex
text tαxt tαxt text tαxt tαxt
@@ -2923,6 +2924,24 @@ describe('lua stdlib', function()
{4:-- Omni completion (^O^N^P) }{5:match 1 of 2} | {4:-- Omni completion (^O^N^P) }{5:match 1 of 2} |
]]} ]]}
end) end)
it('vim.print', function()
-- vim.print() returns its args.
eq({42, 'abc', { a = { b = 77 }}},
exec_lua[[return {vim.print(42, 'abc', { a = { b = 77 }})}]])
-- vim.print() pretty-prints the args.
eq(dedent[[
42
abc
{
a = {
b = 77
}
}]],
eval[[execute('lua vim.print(42, "abc", { a = { b = 77 }})')]])
end)
end) end)
describe('lua: builtin modules', function() describe('lua: builtin modules', function()