Problem:
Currently `deepcopy` hashes every single tables it copies so it can be
reused. For tables of mostly unique items that are non recursive, this
hashing is unnecessarily expensive
Solution:
Port the `noref` argument from Vimscripts `deepcopy()`.
The below benchmark demonstrates the results for two extreme cases of
tables of different sizes. One table that uses the same table lots of
times and one with all unique tables.
| test | `noref=false` (ms) | `noref=true` (ms) |
| -------------------- | ------------------ | ----------------- |
| unique tables (50) | 6.59 | 2.62 |
| shared tables (50) | 3.24 | 6.40 |
| unique tables (2000) | 23381.48 | 2884.53 |
| shared tables (2000) | 3505.54 | 14038.80 |
The results are basically the inverse of each other where `noref` is
much more performance on tables with unique fields, and `not noref` is
more performant on tables that reuse fields.
- Remove the usage of the term "defer" to avoid confusion with
`vim.defer_fn`, which also calls `vim.schedule_wrap` internally.
- Explicitly state that `vim.schedule_wrap` returns a function in the
text.
- Mention that arguments are passed along.
- Include a usage example.
- Rename param to `fn`.
The on_detect functions returned by filetype.lua set buffer local
variables which are often used by filetype plugins. For example, the
on_detect function for shell buffers sets variables such as b:is_bash or
b:is_sh, which are used by the sh ftplugin.
When called after setting the buffer's filetype, these variables cannot
be used by the ftplugin (because they are not yet defined). Instead,
call on_detect before setting the buffer filetype so that any buffer
variables set by on_detect can be used in the ftplugin.
If an iterator pipeline stage returns nil as its first return value, the
other return values are ignored and it is treated as if that stage
returned only nil (the semantics of returning nil are different between
different stages). This is consistent with how for loops work in Lua
more generally, where the for loop breaks when the first return value
from the function iterator is nil (see :h for-in for details).
Problem: luals returns stricter diagnostics with bundled luarc.json
Solution: Improve some function and type annotations:
* use recognized uv.* types
* disable diagnostic for global `vim` in shared.lua
* docs: don't start comment lines with taglink (otherwise LuaLS will interpret it as a type)
* add type alias for lpeg pattern
* fix return annotation for `vim.secure.trust`
* rename local Range object in vim.version (shadows `Range` in vim.treesitter)
* fix some "missing fields" warnings
* add missing required fields for test functions in eval.lua
* rename lsp meta files for consistency
Problem: cache paths are derived by replacing each reserved/filesystem-
path-sensitive char with a `%` char in the original path. With this
method, two different files at two different paths (each containing `%`
chars) can erroneously resolve to the very same cache path in certain
edge-cases.
Solution: derive cache paths by url-encoding the original (path) instead
using `vim.uri_encode()` with `"rfc2396"`. Increment `Loader.VERSION` to
denote this change.
- eval.lua is now the source of truth.
- Formatting is much more consistent.
- Fixed Lua type generation for polymorphic functions (get(), etc).
- Removed "Overview" section from builtin.txt
- Can generate this if we really want it.
- Moved functions from sign.txt and testing.txt into builtin.txt.
- Removed the *timer* *timers* tags since libuv timers via vim.uv should be preferred.
- Removed the temp-file-name tag from tempname()
- Moved lueval() from lua.txt to builtin.txt.
* Fix indent
* fixup!
* fixup! fixup!
* fixup! better tag formatting
* fixup: revert changes no longer needed
* fixup! CI
---------
Co-authored-by: zeertzjq <zeertzjq@outlook.com>
* docs(lua): teach lua2dox how to table
* docs(lua): teach gen_vimdoc.py about local functions
No more need to mark local functions with @private
* docs(lua): mention @nodoc and @meta in dev-lua-doc
* fixup!
Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
---------
Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
Problem:
Lua functions that return multiple results are declared by using
multiple `@return` docstring directives. But the generated docs don't
make it obvious what this represents.
Solution:
- Generate a "Return (multiple)" heading for multiple-value functions.
- Fix `@note` directives randomly placed after `@return`.
* feat(lua): allow vim.wo to be double indexed
Problem: `vim.wo` does not implement `setlocal`
Solution: Allow `vim.wo` to be double indexed
Co-authored-by: Christian Clason <c.clason@uni-graz.at>
Problem:
The parent commit added a new vim.get_visual_selection() function to
improve visual star. But that is redundant with vim.region(). Any
current limitations of vim.region() should be fixed instead of adding
a new function.
Solution:
Delete vim.get_visual_selection().
Use vim.region() to get the visual selection.
TODO: fails with visual "block" selections.
Problem:
Visual mode "*", "#" mappings don't work on text with "/", "\", "?", and
newlines.
Solution:
Get the visual selection and escape it as a search pattern.
Add functions vim.get_visual_selection and _search_for_visual_selection.
Fix#21676
Problem:
Showing an error via vim.notify() makes it awkward for callers such as
lsp/handlers.lua to avoid showing redundant errors.
Solution:
Return the message instead of showing it. Let the caller decide whether
and when to show the message.
---
Rejected experiment: move vim.ui.open() to vim.env.open()
Problem:
`vim.ui` is where user-interface "providers" live, which can be
overridden. It would also be useful to have a "providers" namespace for
platform-specific features such as "open", clipboard, python, and the other
providers listed in `:help providers`. We could overload `vim.ui` to
serve that purpose as the single "providers" namespace, but
`vim.ui.nodejs()` for example seems awkward.
Solution:
`vim.env` currently has too narrow of a purpose. Overload it to also be
a namespace for `vim.env.open`.
diff --git a/runtime/lua/vim/_meta.lua b/runtime/lua/vim/_meta.lua
index 913f1fe20348..17d05ff37595 100644
--- a/runtime/lua/vim/_meta.lua
+++ b/runtime/lua/vim/_meta.lua
@@ -37,8 +37,28 @@ local options_info = setmetatable({}, {
end,
})
-vim.env = setmetatable({}, {
- __index = function(_, k)
+vim.env = setmetatable({
+ open = setmetatable({}, {
+ __call = function(_, uri)
+ print('xxxxx'..uri)
+ return true
+ end,
+ __tostring = function()
+ local v = vim.fn.getenv('open')
+ if v == vim.NIL then
+ return nil
+ end
+ return v
+ end,
+ })
+ },
+ {
+ __index = function(t, k, ...)
+ if k == 'open' then
+ error()
+ -- vim.print({...})
+ -- return rawget(t, k)
+ end
local v = vim.fn.getenv(k)
if v == vim.NIL then
return nil
Enforce consistent terminology (defined in
`gen_help_html.lua:spell_dict`) for common misspellings.
This does not spellcheck English in general (perhaps a future TODO,
though it may be noisy).
Problem:
- `vim.json` exposes various global options which:
- affect all Nvim Lua plugins (especially the LSP client)
- are undocumented and untested
- can cause confusing problems such as: cc76ae3abe
- `vim.json` exposes redundant mechanisms:
- `vim.json.null` is redundant with `vim.NIL`.
- `array_mt` is redundant because Nvim uses a metatable
(`vim.empty_dict()`) for empty dict instead, which `vim.json` is
configured to use by default (see `as_empty_dict`).
Example:
```
:lua vim.print(vim.json.decode('{"bar":[],"foo":{}}'))
--> { bar = {}, foo = vim.empty_dict() }
```
Thus we don't need to also decorate empty arrays with `array_mt`.
Solution:
Remove the functions from the public vim.json interface.
Comment-out the implementation code to minimize drift from upstream.
TODO:
- Expose the options as arguments to `vim.json.new()`
Co-authored by: zeertzjq <zeertzjq@outlook.com>
Co-authored by: Steven Todd McIntyre II <114119064+stmii@users.noreply.github.com>
Co-authored by: nobe4 <nobe4@users.noreply.github.com>
- docs: mention --luadev-mod to run with lua runtime files
When changing a lua file in the ./runtime folder, a new contributor
might expect changes to be applied to the built Neovim binary.
feat(lua): add vim.system()
Problem:
Handling system commands in Lua is tedious and error-prone:
- vim.fn.jobstart() is vimscript and comes with all limitations attached to typval.
- vim.loop.spawn is too low level
Solution:
Add vim.system().
Partly inspired by Python's subprocess module
Does not expose any libuv objects.
vim.version.range() couldn't parse them correctly.
For example, vim.version.range('<0.9.0'):has('0.9.0') returned `true`.
fix: range:has() accepts vim.version()
So that it's possible to compare a range with:
vim.version.range(spec):has(vim.version())
Problem: Heredoc for interfaces does not support "trim".
Solution: Update the script heredoc support to be same as the :let command.
(Yegappan Lakshmanan, closesvim/vim#5916)
6c2b7b8055
Packing and unpacking return values impairs performance considerably.
In an attempt to avoid creating tables as much as possible we can
instead pass return values between functions (which does not require
knowing the number of values a function might return). This makes the
code more complex, but improves benchmark numbers non-trivially.
This was originally meant as a convenience but prevents possible
functionality. For example:
-- Get the keys of the table with even values
local t = { a = 1, b = 2, c = 3, d = 4 }
vim.iter(t):map(function(k, v)
if v % 2 == 0 then return k end
end):totable()
The example above would not work, because the map() function returns
only a single value, and cannot be converted back into a table (there
are many such examples like this).
Instead, to convert an iterator into a map-like table, users can use
fold():
vim.iter(t):fold({}, function(t, k, v)
t[k] = v
return t
end)
vim.iter wraps a table or iterator function into an `Iter` object with
methods such as `filter`, `map`, and `fold` which can be chained to
produce iterator pipelines that do not create new tables at each step.
feat(lua)!: add stricter vim.tbl_islist(), rename vim.tbl_isarray()
Problem: `vim.tbl_islist` allows gaps in tables with integer keys
("arrays").
Solution: Rename `vim.tbl_islist` to `vim.tbl_isarray`, add new
`vim.tbl.islist` that checks for consecutive integer keys that start
from 1.
* feat(lua): vim.tbl_contains supports general tables and predicates
Problem: `vim.tbl_contains` only works for list-like tables (integer
keys without gaps) and primitive values (in particular, not for nested
tables).
Solution: Rename `vim.tbl_contains` to `vim.list_contains` and add new
`vim.tbl_contains` that works for general tables and optionally allows
`value` to be a predicate function that is checked for every key.
Whenever we run fs_stat() on a path, save this information in the loader
so it can be re-used.
- Loader.loadfile: Remove arguments `hash` as it is no longer needed.
- Loader.loader: Use _G.loadstring instead of Loader.load
This allows plugins to wrap loadstring to inspection and profiling
- factor out read file logic
Problem:
- vim.split has more features than vim.gsplit.
- Cannot inspect the "separator" segments of vim.split or vim.gsplit.
Solution:
- Move common implementation from vim.split into vim.gsplit.
- TODO: deprecate vim.split in favor of vim.totable(vim.gsplit())?
- Introduce `keepsep` parameter.
Related: 84f66909e4
existing behavior of
:=
and
:[range]=
are unchanged. `|` is still allowed with this usage.
However,
:=p
and similar are changed in a way which could be construed as a breaking
change. Allowing |ex-flags| for := in the first place was a mistake as
any form of := DOES NOT MOVE THE CURSOR. So it would print one line number
and then print a completely different line contents after that.
Problem:
"tmux 3.2a" (output from "tmux -V") is not parsed easily.
Solution:
With `strict=false`, discard everything before the first digit.
- rename Semver => Version
- rename vim.version.version() => vim.version._version()
- rename matches() => has()
- remove `opts` from cmp()
Problem:
vim.deprecate() shows ":help deprecated" for third-party plugins. ":help
deprecated" only describes deprecations in Nvim, and is unrelated to any
3rd party deprecations.
Solution:
If `plugin` is specified, don't show ":help deprecated".
fix#22235
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.
also make implicit submodules "uri" and "_inspector" work with completion
this is needed for `:lua=vim.uri_<tab>` wildmenu completion
to work even before uri or _inspector functions are used.
- version.cmp(): assert valid version
- add test for loading vim.version (the other tests use shared.lua in
the test runner)
- reduce test scopes, reword test descriptions
Problem:
No easy way to find files under certain directories (ex: grab all files under
`test/`) or exclude the content of certain paths (ex. `build/`, `.git/`)
Solution:
Pass the full `path` as an arg to the predicate.
Problem:
Build is not reproducible, because generated source files (.c/.h/) are not
deterministic, mostly because Lua pairs() is unordered by design (for security).
https://github.com/LuaJIT/LuaJIT/issues/626#issuecomment-707005671https://www.lua.org/manual/5.1/manual.html#pdf-next
> The order in which the indices are enumerated is not specified [...]
>
>> The hardening of the VM deliberately randomizes string hashes. This in
>> turn randomizes the iteration order of tables with string keys.
Solution:
- Update the code generation scripts to be deterministic.
- That is only a partial solution: the exported function
(funcs_metadata.generated.h) and ui event
(ui_events_metadata.generated.h) metadata have some mpack'ed
tables, which are not serialized deterministically.
- As a workaround, introduce `PRG_GEN_LUA` cmake setting, so you can
inject a modified build of luajit (with LUAJIT_SECURITY_PRN=0)
that preserves table order.
- Longer-term we should change the mpack'ed data structure so it no
longer uses tables keyed by strings.
Closes#20124
Co-Authored-By: dundargoc <gocdundar@gmail.com>
Co-Authored-By: Arnout Engelen <arnout@bzzt.net>
Problem:
Nvim has Lua but the "nvim" CLI can't easily be used to execute Lua
scripts, especially scripts that take arguments or produce output.
Solution:
- support "nvim -l [args...]" for running scripts. closes#15749
- exit without +q
- remove lua2dox_filter
- remove Doxyfile. This wasn't used anyway, because the doxygen config
is inlined in gen_vimdoc.py (`Doxyfile` variable).
- use "nvim -l" in docs-gen CI job
Examples:
$ nvim -l scripts/lua2dox.lua --help
Lua2DoX (0.2 20130128)
...
$ echo "print(vim.inspect(_G.arg))" | nvim -l - --arg1 --arg2
$ echo 'print(vim.inspect(vim.api.nvim_buf_get_text(1,0,0,-1,-1,{})))' | nvim +"put ='text'" -l -
TODO?
-e executes Lua code
-l loads a module
-i enters REPL _after running the other arguments_.
* credit to @smolck and @theHamsta for their contributions in laying the
groundwork for this feature and for their work on some of the helper
utility functions and tests
Add introductory guide explaining how to use Lua in Neovim:
where to put Lua files, how to set variables and options, how
to create mappings, autocommands, and user commands.
Adapted with kind permission from
https://github.com/nanotee/nvim-lua-guide
Introduce vim.secure.trust() to programmatically manage the trust
database. Use this function in a new :trust ex command which can
be used as a simple frontend.
Resolves: https://github.com/neovim/neovim/issues/21092
Co-authored-by: Gregory Anders <greg@gpanders.com>
Co-authored-by: ii14 <ii14@users.noreply.github.com>
This function accepts a path to a file and prompts the user if the file
is trusted. If the user confirms that the file is trusted, the contents
of the file are returned. The user's decision is stored in a trust
database at $XDG_STATE_HOME/nvim/trust. When this function is invoked
with a path that is already marked as trusted in the trust database, the
user is not prompted for a response.
fix(vim.ui.input): return empty string when inputs nothing
The previous behavior of `vim.ui.input()` when typing <CR> with
no text input (with an intention of having the empty string as input)
was to execute `on_confirm(nil)`, conflicting with its documentation.
Inputting an empty string should now correctly execute `on_confirm('')`.
This should be clearly distinguished from cancelling or aborting the
input UI, in which case `on_confirm(nil)` is executed as before.
Problem:
- pesc() returns multiple results, it should return a single result.
- tbl_islist() returns non-boolean in some branches.
- Docstring: @generic must be declared first
Solution:
Constrain docstring annotations.
Fix return types.
Co-authored-by: Justin M. Keyes <justinkz@gmail.com>
Made obsolete by now graduated `filetype.lua` (enabled by default).
Note that changes or additions to the filetype detection still need to
be made through a PR to vim/vim as we port the _logic_ as well as tests.
- Improve generated HTML by updating parser which includes fixes for
single "'" and single "|":
https://github.com/neovim/tree-sitter-vimdoc/pull/31
- Updated parser also fixes the conceal issue for "help" highlight
queries https://github.com/neovim/tree-sitter-vimdoc/issues/23 by
NOT including whitespace in nodes.
- But this means we need to restore the getws() function which scrapes
leading whitespace from the original input (buffer).
Problem:
The {foo} parameters listed in `:help api` and similar generated docs,
are intended to be a "list" but they aren't prefixed with a list symbol.
This prevents parsers from understanding the list, which forces
generators like `gen_help_html.lua` to use hard-wrapped/preformatted
layout instead of a soft-wrapped "flow" layout.
Solution:
Modify gen_vimdoc.py to prefix {foo} parameters with a "•" symbol.