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
- *vim.register_keystroke_callback()* Use |vim.on_key()| instead.
- *vim.pretty_print()* Use |vim.print()| instead.
NORMAL COMMANDS
- *]f* *[f* Same as "gf".

View File

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

View File

@ -10,16 +10,16 @@
==============================================================================
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
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
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
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
|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*
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:
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|
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|.
3. The "Lua API" written in and specifically for Lua. These are any other
functions accessible through `vim.*` not mentioned already; see |lua-stdlib|.
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
passed as `nil`); and Vim API functions can use 0-based indexing even if Lua
arrays are 1-indexed by default.
@ -58,7 +58,7 @@ convenient to use from 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
:lua print("Hello!")
<
@ -69,10 +69,10 @@ local keyword are not accessible outside of the command. This won't work:
:lua print(foo)
" prints "nil" instead of "1"
<
You can also use `:lua=`, which is the same as `:lua vim.pretty_print(...)`,
to conveniently check the value of a variable or a table:
You can also use `:lua=`, which is equivalent to `:lua vim.print(...)`, to
conveniently check the value of a variable or a table:
>vim
:lua=package
:lua =package
<
To run a Lua script in an external file, you can use the |:source| command
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*
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,
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`
@ -279,7 +279,7 @@ Note that you cannot directly change fields of array variables. This won't
work:
>lua
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 }
<
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
temp_table.key2 = 400
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 }
<
To delete a variable, simply set it to `nil`:
@ -350,7 +350,7 @@ use |vim.opt:get()|:
--> {...} (big table)
print(vim.opt.smarttab:get())
--> false
vim.pretty_print(vim.opt.listchars:get())
vim.print(vim.opt.listchars:get())
--> { space = '_', tab = '>~' }
<
------------------------------------------------------------------------------
@ -488,7 +488,7 @@ Autocommands *lua-guide-autocommands*
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
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*
@ -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
• `match`: a string that matched the `pattern` (see |<amatch>|)
• `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*
User commands can be created through the Neovim API with
`vim.api.`|nvim_create_user_command()|. This function takes three mandatory
arguments:
User commands can be created through with |nvim_create_user_command()|. This
function takes three mandatory arguments:
• a string that is the name of the command (which must start with an uppercase
letter to distinguish it from builtin commands);
• 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)
<
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
@ -1258,7 +1258,7 @@ Option:get()
the values as entries in the array: >lua
vim.cmd [[set wildignore=*.pyc,*.o]]
vim.pretty_print(vim.opt.wildignore:get())
vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
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
vim.cmd [[set listchars=space:_,tab:>~]]
vim.pretty_print(vim.opt.listchars:get())
vim.print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
@ -1282,7 +1282,7 @@ Option:get()
as keys and `true` as entries. >lua
vim.cmd [[set formatoptions=njtcroql]]
vim.pretty_print(vim.opt.formatoptions:get())
vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
@ -1496,10 +1496,11 @@ paste({lines}, {phase}) *vim.paste()*
See also: ~
|paste| @alias paste_phase -1 | 1 | 2 | 3
pretty_print({...}) *vim.pretty_print()*
Prints given arguments in human-readable format. Example: >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))
print({...}) *vim.print()*
"Pretty prints" the given arguments and returns them unmodified.
Example: >lua
local hl_normal = vim.print(vim.api.nvim_get_hl_by_name('Normal', true))
<
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.
- Invalid ranges now cause an error instead of returning `nil`.
• Renamed vim.pretty_print to vim.print. |deprecated|
==============================================================================
NEW FEATURES *news-features*

View File

@ -778,22 +778,37 @@ do
end
end
---Prints given arguments in human-readable format.
---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.
---@private
function vim.pretty_print(...)
local objects = {}
for i = 1, select('#', ...) do
local v = select(i, ...)
table.insert(objects, vim.inspect(v))
vim.deprecate('vim.pretty_print', 'vim.print', '0.10')
return vim.print(...)
end
--- "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
print(table.concat(objects, ' '))
return ...
end

View File

@ -1,6 +1,6 @@
vim.api.nvim_create_user_command('Inspect', function(cmd)
if cmd.bang then
vim.pretty_print(vim.inspect_pos())
vim.print(vim.inspect_pos())
else
vim.show_pos()
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))
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.
// 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, "vim.pretty_print(%s)", code + 1);
vim_snprintf(code_buf, len + 1, "vim.print(%s)", code + 1);
xfree(code);
code = code_buf;
}

View File

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

View File

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

View File

@ -6,6 +6,7 @@ local nvim_prog = helpers.nvim_prog
local funcs = helpers.funcs
local meths = helpers.meths
local command = helpers.command
local dedent = helpers.dedent
local insert = helpers.insert
local clear = helpers.clear
local eq = helpers.eq
@ -2269,7 +2270,7 @@ describe('lua stdlib', function()
describe('vim.region', function()
it('charwise', function()
insert(helpers.dedent( [[
insert(dedent( [[
text tααt tααt text
text tαxt txtα tex
text tαxt tαxt
@ -2923,6 +2924,24 @@ describe('lua stdlib', function()
{4:-- Omni completion (^O^N^P) }{5:match 1 of 2} |
]]}
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)
describe('lua: builtin modules', function()