aboutsummaryrefslogtreecommitdiff
path: root/runtime/lua
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/lua')
-rw-r--r--runtime/lua/editorconfig.lua2
-rw-r--r--runtime/lua/man.lua1
-rw-r--r--runtime/lua/nvim/health.lua2
-rw-r--r--runtime/lua/provider/health.lua916
-rw-r--r--runtime/lua/vim/_editor.lua22
-rw-r--r--runtime/lua/vim/diagnostic.lua2
-rw-r--r--runtime/lua/vim/highlight.lua19
-rw-r--r--runtime/lua/vim/loader.lua22
-rw-r--r--runtime/lua/vim/lsp.lua5
-rw-r--r--runtime/lua/vim/lsp/_snippet.lua4
-rw-r--r--runtime/lua/vim/lsp/buf.lua1
-rw-r--r--runtime/lua/vim/lsp/codelens.lua2
-rw-r--r--runtime/lua/vim/lsp/handlers.lua1
-rw-r--r--runtime/lua/vim/lsp/log.lua1
-rw-r--r--runtime/lua/vim/lsp/protocol.lua1
-rw-r--r--runtime/lua/vim/lsp/rpc.lua1
-rw-r--r--runtime/lua/vim/lsp/util.lua3
-rw-r--r--runtime/lua/vim/shared.lua93
-rw-r--r--runtime/lua/vim/treesitter/query.lua2
-rw-r--r--runtime/lua/vim/uri.lua1
20 files changed, 1049 insertions, 52 deletions
diff --git a/runtime/lua/editorconfig.lua b/runtime/lua/editorconfig.lua
index 5b09126788..5188c13284 100644
--- a/runtime/lua/editorconfig.lua
+++ b/runtime/lua/editorconfig.lua
@@ -26,7 +26,7 @@ end
function M.properties.charset(bufnr, val)
assert(
- vim.tbl_contains({ 'utf-8', 'utf-8-bom', 'latin1', 'utf-16be', 'utf-16le' }, val),
+ vim.list_contains({ 'utf-8', 'utf-8-bom', 'latin1', 'utf-16be', 'utf-16le' }, val),
'charset must be one of "utf-8", "utf-8-bom", "latin1", "utf-16be", or "utf-16le"'
)
if val == 'utf-8' or val == 'utf-8-bom' then
diff --git a/runtime/lua/man.lua b/runtime/lua/man.lua
index cca9434e9c..1158d80941 100644
--- a/runtime/lua/man.lua
+++ b/runtime/lua/man.lua
@@ -64,6 +64,7 @@ local function system(cmd_, silent, env)
local cmd_str = table.concat(cmd, ' ')
man_error(string.format('command error: %s', cmd_str))
end
+ return ''
end
vim.wait(30000, function()
diff --git a/runtime/lua/nvim/health.lua b/runtime/lua/nvim/health.lua
index b6d84404ec..6f544e9407 100644
--- a/runtime/lua/nvim/health.lua
+++ b/runtime/lua/nvim/health.lua
@@ -325,7 +325,7 @@ local function check_tmux()
-- check for RGB capabilities
local info = vim.fn.system({ 'tmux', 'display-message', '-p', '#{client_termfeatures}' })
info = vim.split(vim.trim(info), ',', { trimempty = true })
- if not vim.tbl_contains(info, 'RGB') then
+ if not vim.list_contains(info, 'RGB') then
local has_rgb = false
if #info == 0 then
-- client_termfeatures may not be supported; fallback to checking show-messages
diff --git a/runtime/lua/provider/health.lua b/runtime/lua/provider/health.lua
new file mode 100644
index 0000000000..a5fe14732c
--- /dev/null
+++ b/runtime/lua/provider/health.lua
@@ -0,0 +1,916 @@
+local M = {}
+
+local start = vim.health.report_start
+local ok = vim.health.report_ok
+local info = vim.health.report_info
+local warn = vim.health.report_warn
+local error = vim.health.report_error
+local iswin = vim.loop.os_uname().sysname == 'Windows_NT'
+
+local shell_error_code = 0
+local function shell_error()
+ return shell_error_code ~= 0
+end
+
+-- Returns true if `cmd` exits with success, else false.
+local function cmd_ok(cmd)
+ vim.fn.system(cmd)
+ return vim.v.shell_error == 0
+end
+
+local function executable(exe)
+ return vim.fn.executable(exe) == 1
+end
+
+local function is_blank(s)
+ return s:find('^%s*$') ~= nil
+end
+
+local function isdir(path)
+ if not path then
+ return false
+ end
+ local stat = vim.loop.fs_stat(path)
+ if not stat then
+ return false
+ end
+ return stat.type == 'directory'
+end
+
+local function isfile(path)
+ if not path then
+ return false
+ end
+ local stat = vim.loop.fs_stat(path)
+ if not stat then
+ return false
+ end
+ return stat.type == 'file'
+end
+
+-- Handler for s:system() function.
+local function system_handler(self, _, data, event)
+ if event == 'stderr' then
+ if self.add_stderr_to_output then
+ self.output = self.output .. vim.fn.join(data, '')
+ else
+ self.stderr = self.stderr .. vim.fn.join(data, '')
+ end
+ elseif event == 'stdout' then
+ self.output = self.output .. vim.fn.join(data, '')
+ elseif event == 'exit' then
+ shell_error_code = data
+ end
+end
+
+-- Attempts to construct a shell command from an args list.
+-- Only for display, to help users debug a failed command.
+local function shellify(cmd)
+ if type(cmd) ~= 'table' then
+ return cmd
+ end
+ return vim.fn.join(
+ vim.fn.map(vim.fn.copy(cmd), [[v:val =~# ''\m[^\-.a-zA-Z_/]'' ? shellescape(v:val) : v:val]]),
+ ' '
+ )
+end
+
+-- Run a system command and timeout after 30 seconds.
+local function system(cmd, ...)
+ local args = { ... }
+ local args_count = vim.tbl_count(args)
+
+ local stdin = (args_count > 0 and args[1] or '')
+ local stderr = (args_count > 1 and args[2] or false)
+ local ignore_error = (args_count > 2 and args[3] or false)
+
+ local opts = {
+ add_stderr_to_output = stderr,
+ output = '',
+ stderr = '',
+ on_stdout = system_handler,
+ on_stderr = system_handler,
+ on_exit = system_handler,
+ }
+ local jobid = vim.fn.jobstart(cmd, opts)
+
+ if jobid < 1 then
+ local message = 'Command error (job='
+ .. jobid
+ .. '): `'
+ .. shellify(cmd)
+ .. '` (in '
+ .. vim.fn.string(vim.fn.getcwd())
+ .. ')'
+
+ error(message)
+ shell_error_code = 1
+ return opts.output
+ end
+
+ if not is_blank(stdin) then
+ vim.cmd([[call jobsend(jobid, stdin)]])
+ end
+
+ local res = vim.fn.jobwait({ jobid }, 30000)
+ if res[1] == -1 then
+ error('Command timed out: ' .. shellify(cmd))
+ vim.cmd([[call jobstop(jobid)]])
+ elseif shell_error() and not ignore_error then
+ local emsg = 'Command error (job='
+ .. jobid
+ .. ', exit code '
+ .. shell_error_code
+ .. '): `'
+ .. shellify(cmd)
+ .. '` (in '
+ .. vim.fn.string(vim.fn.getcwd())
+ .. ')'
+ if not is_blank(opts.output) then
+ emsg = emsg .. '\noutput: ' .. opts.output
+ end
+ if not is_blank(opts.stderr) then
+ emsg = emsg .. '\nstderr: ' .. opts.stderr
+ end
+ error(emsg)
+ end
+
+ -- return opts.output
+ local _ = ...
+ return vim.trim(vim.fn.system(cmd))
+end
+
+local function clipboard()
+ start('Clipboard (optional)')
+
+ if
+ os.getenv('TMUX')
+ and executable('tmux')
+ and executable('pbpaste')
+ and not cmd_ok('pbpaste')
+ then
+ local tmux_version = string.match(vim.fn.system('tmux -V'), '%d+%.%d+')
+ local advice = {
+ 'Install tmux 2.6+. https://superuser.com/q/231130',
+ 'or use tmux with reattach-to-user-namespace. https://superuser.com/a/413233',
+ }
+ error('pbcopy does not work with tmux version: ' .. tmux_version, advice)
+ end
+
+ local clipboard_tool = vim.fn['provider#clipboard#Executable']()
+ if vim.g.clipboard and is_blank(clipboard_tool) then
+ local error_message = vim.fn['provider#clipboard#Error']()
+ error(
+ error_message,
+ "Use the example in :help g:clipboard as a template, or don't set g:clipboard at all."
+ )
+ elseif is_blank(clipboard_tool) then
+ warn(
+ 'No clipboard tool found. Clipboard registers (`"+` and `"*`) will not work.',
+ ':help clipboard'
+ )
+ else
+ ok('Clipboard tool found: ' .. clipboard_tool)
+ end
+end
+
+local function disabled_via_loaded_var(provider)
+ local loaded_var = 'loaded_' .. provider .. '_provider'
+ local v = vim.g[loaded_var]
+ if v == 0 then
+ info('Disabled (' .. loaded_var .. '=' .. v .. ').')
+ return true
+ end
+ return false
+end
+
+-- Check if pyenv is available and a valid pyenv root can be found, then return
+-- their respective paths. If either of those is invalid, return two empty
+-- strings, effectively ignoring pyenv.
+local function check_for_pyenv()
+ local pyenv_path = vim.fn.resolve(vim.fn.exepath('pyenv'))
+
+ if is_blank(pyenv_path) then
+ return { '', '' }
+ end
+
+ info('pyenv: Path: ' .. pyenv_path)
+
+ local pyenv_root = os.getenv('PYENV_ROOT') and vim.fn.resolve('$PYENV_ROOT') or ''
+
+ if is_blank(pyenv_root) then
+ pyenv_root = vim.trim(system({ pyenv_path, 'root' }))
+ info('pyenv: $PYENV_ROOT is not set. Infer from `pyenv root`.')
+ end
+
+ if not isdir(pyenv_root) then
+ local message = 'pyenv: Root does not exist: '
+ .. pyenv_root
+ .. '. Ignoring pyenv for all following checks.'
+ warn(message)
+ return { '', '' }
+ end
+
+ info('pyenv: Root: ' .. pyenv_root)
+
+ return { pyenv_path, pyenv_root }
+end
+
+-- Check the Python interpreter's usability.
+local function check_bin(bin)
+ if not isfile(bin) and (not iswin or not isfile(bin .. '.exe')) then
+ error('"' .. bin .. '" was not found.')
+ return false
+ elseif not executable(bin) then
+ error('"' .. bin .. '" is not executable.')
+ return false
+ end
+ return true
+end
+
+-- Fetch the contents of a URL.
+local function download(url)
+ local has_curl = executable('curl')
+ if has_curl and vim.fn.system({ 'curl', '-V' }):find('Protocols:.*https') then
+ local rv = system({ 'curl', '-sL', url }, '', 1, 1)
+ if shell_error() then
+ return 'curl error with ' .. url .. ': ' .. shell_error_code
+ else
+ return rv
+ end
+ elseif executable('python') then
+ local script = "try:\n\
+ from urllib.request import urlopen\n\
+ except ImportError:\n\
+ from urllib2 import urlopen\n\
+ response = urlopen('" .. url .. "')\n\
+ print(response.read().decode('utf8'))\n"
+ local rv = system({ 'python', '-c', script })
+ if is_blank(rv) and shell_error() then
+ return 'python urllib.request error: ' .. shell_error_code
+ else
+ return rv
+ end
+ end
+
+ local message = 'missing `curl` '
+
+ if has_curl then
+ message = message .. '(with HTTPS support) '
+ end
+ message = message .. 'and `python`, cannot make web request'
+
+ return message
+end
+
+-- Get the latest Nvim Python client (pynvim) version from PyPI.
+local function latest_pypi_version()
+ local pypi_version = 'unable to get pypi response'
+ local pypi_response = download('https://pypi.python.org/pypi/pynvim/json')
+ if not is_blank(pypi_response) then
+ local pcall_ok, output = pcall(vim.fn.json_decode, pypi_response)
+ local pypi_data
+ if pcall_ok then
+ pypi_data = output
+ else
+ return 'error: ' .. pypi_response
+ end
+
+ local pypi_element = pypi_data['info'] or {}
+ pypi_version = pypi_element['version'] or 'unable to parse'
+ end
+ return pypi_version
+end
+
+local function is_bad_response(s)
+ local lower = s:lower()
+ return vim.startswith(lower, 'unable')
+ or vim.startswith(lower, 'error')
+ or vim.startswith(lower, 'outdated')
+end
+
+-- Get version information using the specified interpreter. The interpreter is
+-- used directly in case breaking changes were introduced since the last time
+-- Nvim's Python client was updated.
+--
+-- Returns: {
+-- {python executable version},
+-- {current nvim version},
+-- {current pypi nvim status},
+-- {installed version status}
+-- }
+local function version_info(python)
+ local pypi_version = latest_pypi_version()
+
+ local python_version = vim.trim(system({
+ python,
+ '-c',
+ 'import sys; print(".".join(str(x) for x in sys.version_info[:3]))',
+ }))
+
+ if is_blank(python_version) then
+ python_version = 'unable to parse ' .. python .. ' response'
+ end
+
+ local nvim_path = vim.trim(system({
+ python,
+ '-c',
+ 'import sys; sys.path = [p for p in sys.path if p != ""]; import neovim; print(neovim.__file__)',
+ }))
+ if shell_error() or is_blank(nvim_path) then
+ return { python_version, 'unable to load neovim Python module', pypi_version, nvim_path }
+ end
+
+ -- Assuming that multiple versions of a package are installed, sort them
+ -- numerically in descending order.
+ local function compare(metapath1, metapath2)
+ local a = vim.fn.matchstr(vim.fn.fnamemodify(metapath1, ':p:h:t'), [[[0-9.]\+]])
+ local b = vim.fn.matchstr(vim.fn.fnamemodify(metapath2, ':p:h:t'), [[[0-9.]\+]])
+ if a == b then
+ return 0
+ elseif a > b then
+ return 1
+ else
+ return -1
+ end
+ end
+
+ -- Try to get neovim.VERSION (added in 0.1.11dev).
+ local nvim_version = system({
+ python,
+ '-c',
+ 'from neovim import VERSION as v; print("{}.{}.{}{}".format(v.major, v.minor, v.patch, v.prerelease))',
+ }, '', 1, 1)
+ if is_blank(nvim_version) then
+ nvim_version = 'unable to find pynvim module version'
+ local base = vim.fs.basename(nvim_path, ':h')
+ local metas = vim.fn.glob(base .. '-*/METADATA', 1, 1)
+ vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', 1, 1))
+ vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', 1, 1))
+ metas = table.sort(metas, compare)
+
+ if metas and next(metas) ~= nil then
+ for _, meta_line in ipairs(vim.fn.readfile(metas[1])) do
+ if vim.startswith(meta_line, 'Version:') then
+ nvim_version = vim.fn.matchstr(meta_line, [[^Version: \zs\S\+]])
+ break
+ end
+ end
+ end
+ end
+
+ local nvim_path_base = vim.fn.fnamemodify(nvim_path, [[:~:h]])
+ local version_status = 'unknown; ' .. nvim_path_base
+ if is_bad_response(nvim_version) and is_bad_response(pypi_version) then
+ if vim.version.lt(nvim_version, pypi_version) then
+ version_status = 'outdated; from ' .. nvim_path_base
+ else
+ version_status = 'up to date'
+ end
+ end
+
+ return { python_version, nvim_version, pypi_version, version_status }
+end
+
+-- Resolves Python executable path by invoking and checking `sys.executable`.
+local function python_exepath(invocation)
+ return vim.fs.normalize(
+ system(vim.fn.fnameescape(invocation) .. ' -c "import sys; sys.stdout.write(sys.executable)"')
+ )
+end
+
+local function python()
+ start('Python 3 provider (optional)')
+
+ local pyname = 'python3'
+ local python_exe = ''
+ local virtual_env = os.getenv('VIRTUAL_ENV')
+ local venv = virtual_env and vim.fn.resolve(virtual_env) or ''
+ local host_prog_var = pyname .. '_host_prog'
+ local python_multiple = {}
+
+ if disabled_via_loaded_var(pyname) then
+ return
+ end
+
+ local pyenv_table = check_for_pyenv()
+ local pyenv = pyenv_table[1]
+ local pyenv_root = pyenv_table[2]
+
+ if vim.g[host_prog_var] then
+ local message = 'Using: g:' .. host_prog_var .. ' = "' .. vim.g[host_prog_var] .. '"'
+ info(message)
+ end
+
+ local python_table = vim.fn['provider#pythonx#Detect'](3)
+ pyname = python_table[1]
+ local pythonx_warnings = python_table[2]
+
+ if is_blank(pyname) then
+ warn(
+ 'No Python executable found that can `import neovim`. '
+ .. 'Using the first available executable for diagnostics.'
+ )
+ elseif vim.g[host_prog_var] then
+ python_exe = pyname
+ end
+
+ -- No Python executable could `import neovim`, or host_prog_var was used.
+ if not is_blank(pythonx_warnings) then
+ warn(pythonx_warnings, {
+ 'See :help provider-python for more information.',
+ 'You may disable this provider (and warning) by adding `let g:loaded_python3_provider = 0` to your init.vim',
+ })
+ elseif not is_blank(pyname) and is_blank(python_exe) then
+ if not vim.g[host_prog_var] then
+ local message = '`g:'
+ .. host_prog_var
+ .. '` is not set. Searching for '
+ .. pyname
+ .. ' in the environment.'
+ info(message)
+ end
+
+ if not is_blank(pyenv) then
+ python_exe = vim.trim(system({ pyenv, 'which', pyname }, '', 1))
+ if is_blank(python_exe) then
+ warn('pyenv could not find ' .. pyname .. '.')
+ end
+ end
+
+ if is_blank(python_exe) then
+ python_exe = vim.fn.exepath(pyname)
+
+ if os.getenv('PATH') then
+ local path_sep = iswin and ';' or ':'
+ local paths = vim.split(os.getenv('PATH') or '', path_sep)
+
+ for _, path in ipairs(paths) do
+ local path_bin = vim.fs.normalize(path .. '/' .. pyname)
+ if
+ path_bin ~= vim.fs.normalize(python_exe)
+ and vim.list_contains(python_multiple, path_bin)
+ and executable(path_bin)
+ then
+ python_multiple[#python_multiple + 1] = path_bin
+ end
+ end
+
+ if vim.tbl_count(python_multiple) > 0 then
+ -- This is worth noting since the user may install something
+ -- that changes $PATH, like homebrew.
+ local message = 'Multiple '
+ .. pyname
+ .. ' executables found. '
+ .. 'Set `g:'
+ .. host_prog_var
+ .. '` to avoid surprises.'
+ info(message)
+ end
+
+ if python_exe:find('shims') then
+ local message = '`' .. python_exe .. '` appears to be a pyenv shim.'
+ local advice = '`pyenv` is not in $PATH, your pyenv installation is broken. Set `g:'
+ .. host_prog_var
+ .. '` to avoid surprises.'
+
+ warn(message, advice)
+ end
+ end
+ end
+ end
+
+ if not is_blank(python_exe) and not vim.g[host_prog_var] then
+ if
+ is_blank(venv)
+ and not is_blank(pyenv)
+ and not is_blank(pyenv_root)
+ and vim.startswith(vim.fn.resolve(python_exe), pyenv_root .. '/')
+ then
+ local advice = 'Create a virtualenv specifically for Nvim using pyenv, and set `g:'
+ .. host_prog_var
+ .. '`. This will avoid the need to install the pynvim module in each version/virtualenv.'
+ warn('pyenv is not set up optimally.', advice)
+ elseif not is_blank(venv) then
+ local venv_root
+ if not is_blank(pyenv_root) then
+ venv_root = pyenv_root
+ else
+ venv_root = vim.fs.dirname(venv)
+ end
+
+ if vim.startswith(vim.fn.resolve(python_exe), venv_root .. '/') then
+ local advice = 'Create a virtualenv specifically for Nvim and use `g:'
+ .. host_prog_var
+ .. '`. This will avoid the need to install the pynvim module in each virtualenv.'
+ warn('Your virtualenv is not set up optimally.', advice)
+ end
+ end
+ end
+
+ if is_blank(python_exe) and not is_blank(pyname) then
+ -- An error message should have already printed.
+ error('`' .. pyname .. '` was not found.')
+ elseif not is_blank(python_exe) and not check_bin(python_exe) then
+ python_exe = ''
+ end
+
+ -- Diagnostic output
+ info('Executable: ' .. (is_blank(python_exe) and 'Not found' or python_exe))
+ if vim.tbl_count(python_multiple) > 0 then
+ for _, path_bin in ipairs(python_multiple) do
+ info('Other python executable: ' .. path_bin)
+ end
+ end
+
+ if is_blank(python_exe) then
+ -- No Python executable can import 'neovim'. Check if any Python executable
+ -- can import 'pynvim'. If so, that Python failed to import 'neovim' as
+ -- well, which is most probably due to a failed pip upgrade:
+ -- https://github.com/neovim/neovim/wiki/Following-HEAD#20181118
+ local pynvim_table = vim.fn['provider#pythonx#DetectByModule']('pynvim', 3)
+ local pynvim_exe = pynvim_table[1]
+ if not is_blank(pynvim_exe) then
+ local message = 'Detected pip upgrade failure: Python executable can import "pynvim" but not "neovim": '
+ .. pynvim_exe
+ local advice = {
+ 'Use that Python version to reinstall "pynvim" and optionally "neovim".',
+ pynvim_exe .. ' -m pip uninstall pynvim neovim',
+ pynvim_exe .. ' -m pip install pynvim',
+ pynvim_exe .. ' -m pip install neovim # only if needed by third-party software',
+ }
+ error(message, advice)
+ end
+ else
+ local version_info_table = version_info(python_exe)
+ local majorpyversion = version_info_table[1]
+ local current = version_info_table[2]
+ local latest = version_info_table[3]
+ local status = version_info_table[4]
+
+ if vim.fn.str2nr(majorpyversion) ~= 3 then
+ warn('Unexpected Python version. This could lead to confusing error messages.')
+ end
+
+ info('Python version: ' .. majorpyversion)
+
+ if is_bad_response(status) then
+ info('pynvim version: ' .. current .. ' (' .. status .. ')')
+ else
+ info('pynvim version: ' .. current)
+ end
+
+ if is_bad_response(current) then
+ error(
+ 'pynvim is not installed.\nError: ' .. current,
+ 'Run in shell: ' .. python_exe .. ' -m pip install pynvim'
+ )
+ end
+
+ if is_bad_response(latest) then
+ warn('Could not contact PyPI to get latest version.')
+ error('HTTP request failed: ' .. latest)
+ elseif is_bad_response(status) then
+ warn('Latest pynvim is NOT installed: ' .. latest)
+ elseif not is_bad_response(current) then
+ ok('Latest pynvim is installed.')
+ end
+ end
+
+ start('Python virtualenv')
+ if not virtual_env then
+ ok('no $VIRTUAL_ENV')
+ return
+ end
+ local errors = {}
+ -- Keep hints as dict keys in order to discard duplicates.
+ local hints = {}
+ -- The virtualenv should contain some Python executables, and those
+ -- executables should be first both on Nvim's $PATH and the $PATH of
+ -- subshells launched from Nvim.
+ local bin_dir = iswin and 'Scripts' or 'bin'
+ local venv_bins = vim.tbl_filter(function(v)
+ -- XXX: Remove irrelevant executables found in bin/.
+ return not v:match('python%-config')
+ end, vim.fn.glob(string.format('%s/%s/python*', virtual_env, bin_dir), true, true))
+ if vim.tbl_count(venv_bins) > 0 then
+ for _, venv_bin in pairs(venv_bins) do
+ venv_bin = vim.fs.normalize(venv_bin)
+ local py_bin_basename = vim.fs.basename(venv_bin)
+ local nvim_py_bin = python_exepath(vim.fn.exepath(py_bin_basename))
+ local subshell_py_bin = python_exepath(py_bin_basename)
+ if venv_bin ~= nvim_py_bin then
+ errors[#errors + 1] = '$PATH yields this '
+ .. py_bin_basename
+ .. ' executable: '
+ .. nvim_py_bin
+ local hint = '$PATH ambiguities arise if the virtualenv is not '
+ .. 'properly activated prior to launching Nvim. Close Nvim, activate the virtualenv, '
+ .. 'check that invoking Python from the command line launches the correct one, '
+ .. 'then relaunch Nvim.'
+ hints[hint] = true
+ end
+ if venv_bin ~= subshell_py_bin then
+ errors[#errors + 1] = '$PATH in subshells yields this '
+ .. py_bin_basename
+ .. ' executable: '
+ .. subshell_py_bin
+ local hint = '$PATH ambiguities in subshells typically are '
+ .. 'caused by your shell config overriding the $PATH previously set by the '
+ .. 'virtualenv. Either prevent them from doing so, or use this workaround: '
+ .. 'https://vi.stackexchange.com/a/34996'
+ hints[hint] = true
+ end
+ end
+ else
+ errors[#errors + 1] = 'no Python executables found in the virtualenv '
+ .. bin_dir
+ .. ' directory.'
+ end
+
+ local msg = '$VIRTUAL_ENV is set to: ' .. virtual_env
+ if vim.tbl_count(errors) > 0 then
+ if vim.tbl_count(venv_bins) > 0 then
+ msg = msg
+ .. '\nAnd its '
+ .. bin_dir
+ .. ' directory contains: '
+ .. vim.fn.join(vim.fn.map(venv_bins, [[fnamemodify(v:val, ':t')]]), ', ')
+ end
+ local conj = '\nBut '
+ for _, err in ipairs(errors) do
+ msg = msg .. conj .. err
+ conj = '\nAnd '
+ end
+ msg = msg .. '\nSo invoking Python may lead to unexpected results.'
+ warn(msg, vim.fn.keys(hints))
+ else
+ info(msg)
+ info(
+ 'Python version: '
+ .. system('python -c "import platform, sys; sys.stdout.write(platform.python_version())"')
+ )
+ ok('$VIRTUAL_ENV provides :!python.')
+ end
+end
+
+local function ruby()
+ start('Ruby provider (optional)')
+
+ if disabled_via_loaded_var('ruby') then
+ return
+ end
+
+ if not executable('ruby') or not executable('gem') then
+ warn(
+ '`ruby` and `gem` must be in $PATH.',
+ 'Install Ruby and verify that `ruby` and `gem` commands work.'
+ )
+ return
+ end
+ info('Ruby: ' .. system({ 'ruby', '-v' }))
+
+ local ruby_detect_table = vim.fn['provider#ruby#Detect']()
+ local host = ruby_detect_table[1]
+ if is_blank(host) then
+ warn('`neovim-ruby-host` not found.', {
+ 'Run `gem install neovim` to ensure the neovim RubyGem is installed.',
+ 'Run `gem environment` to ensure the gem bin directory is in $PATH.',
+ 'If you are using rvm/rbenv/chruby, try "rehashing".',
+ 'See :help g:ruby_host_prog for non-standard gem installations.',
+ 'You may disable this provider (and warning) by adding `let g:loaded_ruby_provider = 0` to your init.vim',
+ })
+ return
+ end
+ info('Host: ' .. host)
+
+ local latest_gem_cmd = (iswin and 'cmd /c gem list -ra "^^neovim$"' or 'gem list -ra ^neovim$')
+ local latest_gem = system(vim.fn.split(latest_gem_cmd))
+ if shell_error() or is_blank(latest_gem) then
+ error(
+ 'Failed to run: ' .. latest_gem_cmd,
+ { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
+ )
+ return
+ end
+ local gem_split = vim.split(latest_gem, [[neovim (\|, \|)$]])
+ latest_gem = gem_split[1] or 'not found'
+
+ local current_gem_cmd = { host, '--version' }
+ local current_gem = system(current_gem_cmd)
+ if shell_error() then
+ error(
+ 'Failed to run: ' .. table.concat(current_gem_cmd, ' '),
+ { 'Report this issue with the output of: ', table.concat(current_gem_cmd, ' ') }
+ )
+ return
+ end
+
+ if vim.version.lt(current_gem, latest_gem) then
+ local message = 'Gem "neovim" is out-of-date. Installed: '
+ .. current_gem
+ .. ', latest: '
+ .. latest_gem
+ warn(message, 'Run in shell: gem update neovim')
+ else
+ ok('Latest "neovim" gem is installed: ' .. current_gem)
+ end
+end
+
+local function node()
+ start('Node.js provider (optional)')
+
+ if disabled_via_loaded_var('node') then
+ return
+ end
+
+ if
+ not executable('node')
+ or (not executable('npm') and not executable('yarn') and not executable('pnpm'))
+ then
+ warn(
+ '`node` and `npm` (or `yarn`, `pnpm`) must be in $PATH.',
+ 'Install Node.js and verify that `node` and `npm` (or `yarn`, `pnpm`) commands work.'
+ )
+ return
+ end
+
+ -- local node_v = vim.fn.split(system({'node', '-v'}), "\n")[1] or ''
+ local node_v = system({ 'node', '-v' })
+ info('Node.js: ' .. node_v)
+ if shell_error() or vim.version.lt(node_v, '6.0.0') then
+ warn('Nvim node.js host does not support Node ' .. node_v)
+ -- Skip further checks, they are nonsense if nodejs is too old.
+ return
+ end
+ if vim.fn['provider#node#can_inspect']() == 0 then
+ warn(
+ 'node.js on this system does not support --inspect-brk so $NVIM_NODE_HOST_DEBUG is ignored.'
+ )
+ end
+
+ local node_detect_table = vim.fn['provider#node#Detect']()
+ local host = node_detect_table[1]
+ if is_blank(host) then
+ warn('Missing "neovim" npm (or yarn, pnpm) package.', {
+ 'Run in shell: npm install -g neovim',
+ 'Run in shell (if you use yarn): yarn global add neovim',
+ 'Run in shell (if you use pnpm): pnpm install -g neovim',
+ 'You may disable this provider (and warning) by adding `let g:loaded_node_provider = 0` to your init.vim',
+ })
+ return
+ end
+ info('Nvim node.js host: ' .. host)
+
+ local manager = 'npm'
+ if executable('yarn') then
+ manager = 'yarn'
+ elseif executable('pnpm') then
+ manager = 'pnpm'
+ end
+
+ local latest_npm_cmd = (
+ iswin and 'cmd /c ' .. manager .. ' info neovim --json' or manager .. ' info neovim --json'
+ )
+ local latest_npm = system(vim.fn.split(latest_npm_cmd))
+ if shell_error() or is_blank(latest_npm) then
+ error(
+ 'Failed to run: ' .. latest_npm_cmd,
+ { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
+ )
+ return
+ end
+
+ local pcall_ok, output = pcall(vim.fn.json_decode, latest_npm)
+ local pkg_data
+ if pcall_ok then
+ pkg_data = output
+ else
+ return 'error: ' .. latest_npm
+ end
+ local latest_npm_subtable = pkg_data['dist-tags'] or {}
+ latest_npm = latest_npm_subtable['latest'] or 'unable to parse'
+
+ local current_npm_cmd = { 'node', host, '--version' }
+ local current_npm = system(current_npm_cmd)
+ if shell_error() then
+ error(
+ 'Failed to run: ' .. table.concat(current_npm_cmd, ' '),
+ { 'Report this issue with the output of: ', table.concat(current_npm_cmd, ' ') }
+ )
+ return
+ end
+
+ if latest_npm ~= 'unable to parse' and vim.version.lt(current_npm, latest_npm) then
+ local message = 'Package "neovim" is out-of-date. Installed: '
+ .. current_npm
+ .. ' latest: '
+ .. latest_npm
+ warn(message({
+ 'Run in shell: npm install -g neovim',
+ 'Run in shell (if you use yarn): yarn global add neovim',
+ 'Run in shell (if you use pnpm): pnpm install -g neovim',
+ }))
+ else
+ ok('Latest "neovim" npm/yarn/pnpm package is installed: ' .. current_npm)
+ end
+end
+
+local function perl()
+ start('Perl provider (optional)')
+
+ if disabled_via_loaded_var('perl') then
+ return
+ end
+
+ local perl_detect_table = vim.fn['provider#perl#Detect']()
+ local perl_exec = perl_detect_table[1]
+ local perl_warnings = perl_detect_table[2]
+
+ if is_blank(perl_exec) then
+ if not is_blank(perl_warnings) then
+ warn(perl_warnings, {
+ 'See :help provider-perl for more information.',
+ 'You may disable this provider (and warning) by adding `let g:loaded_perl_provider = 0` to your init.vim',
+ })
+ else
+ warn('No usable perl executable found')
+ end
+ return
+ end
+
+ info('perl executable: ' .. perl_exec)
+
+ -- we cannot use cpanm that is on the path, as it may not be for the perl
+ -- set with g:perl_host_prog
+ system({ perl_exec, '-W', '-MApp::cpanminus', '-e', '' })
+ if shell_error() then
+ return { perl_exec, '"App::cpanminus" module is not installed' }
+ end
+
+ local latest_cpan_cmd = {
+ perl_exec,
+ '-MApp::cpanminus::fatscript',
+ '-e',
+ 'my $app = App::cpanminus::script->new; $app->parse_options ("--info", "-q", "Neovim::Ext"); exit $app->doit',
+ }
+
+ local latest_cpan = system(latest_cpan_cmd)
+ if shell_error() or is_blank(latest_cpan) then
+ error(
+ 'Failed to run: ' .. table.concat(latest_cpan_cmd, ' '),
+ { "Make sure you're connected to the internet.", 'Are you behind a firewall or proxy?' }
+ )
+ return
+ elseif latest_cpan[1] == '!' then
+ local cpanm_errs = vim.split(latest_cpan, '!')
+ if cpanm_errs[1]:find("Can't write to ") then
+ local advice = {}
+ for i = 2, #cpanm_errs do
+ advice[#advice + 1] = cpanm_errs[i]
+ end
+
+ warn(cpanm_errs[1], advice)
+ -- Last line is the package info
+ latest_cpan = cpanm_errs[#cpanm_errs]
+ else
+ error('Unknown warning from command: ' .. latest_cpan_cmd, cpanm_errs)
+ return
+ end
+ end
+ latest_cpan = vim.fn.matchstr(latest_cpan, [[\(\.\?\d\)\+]])
+ if is_blank(latest_cpan) then
+ error('Cannot parse version number from cpanm output: ' .. latest_cpan)
+ return
+ end
+
+ local current_cpan_cmd = { perl_exec, '-W', '-MNeovim::Ext', '-e', 'print $Neovim::Ext::VERSION' }
+ local current_cpan = system(current_cpan_cmd)
+ if shell_error then
+ error(
+ 'Failed to run: ' .. table.concat(current_cpan_cmd, ' '),
+ { 'Report this issue with the output of: ', table.concat(current_cpan_cmd, ' ') }
+ )
+ return
+ end
+
+ if vim.version.lt(current_cpan, latest_cpan) then
+ local message = 'Module "Neovim::Ext" is out-of-date. Installed: '
+ .. current_cpan
+ .. ', latest: '
+ .. latest_cpan
+ warn(message, 'Run in shell: cpanm -n Neovim::Ext')
+ else
+ ok('Latest "Neovim::Ext" cpan module is installed: ' .. current_cpan)
+ end
+end
+
+function M.check()
+ clipboard()
+ python()
+ ruby()
+ node()
+ perl()
+end
+
+return M
diff --git a/runtime/lua/vim/_editor.lua b/runtime/lua/vim/_editor.lua
index fa0980563a..c922ec93db 100644
--- a/runtime/lua/vim/_editor.lua
+++ b/runtime/lua/vim/_editor.lua
@@ -402,8 +402,8 @@ end
--- Input and output positions are (0,0)-indexed and indicate byte positions.
---
---@param bufnr integer number of buffer
----@param pos1 integer[] (line, column) tuple marking beginning of region
----@param pos2 integer[] (line, column) tuple marking end of region
+---@param pos1 integer[]|string start of region as a (line, column) tuple or string accepted by |getpos()|
+---@param pos2 integer[]|string end of region as a (line, column) tuple or string accepted by |getpos()|
---@param regtype string type of selection, see |setreg()|
---@param inclusive boolean indicating whether column of pos2 is inclusive
---@return table region Table of the form `{linenr = {startcol,endcol}}`.
@@ -414,6 +414,24 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive)
vim.fn.bufload(bufnr)
end
+ if type(pos1) == 'string' then
+ local pos = vim.fn.getpos(pos1)
+ pos1 = { pos[2] - 1, pos[3] - 1 + pos[4] }
+ end
+ if type(pos2) == 'string' then
+ local pos = vim.fn.getpos(pos2)
+ pos2 = { pos[2] - 1, pos[3] - 1 + pos[4] }
+ end
+
+ if pos1[1] > pos2[1] or (pos1[1] == pos2[1] and pos1[2] > pos2[2]) then
+ pos1, pos2 = pos2, pos1
+ end
+
+ -- getpos() may return {0,0,0,0}
+ if pos1[1] < 0 or pos1[2] < 0 then
+ return {}
+ end
+
-- check that region falls within current buffer
local buf_line_count = vim.api.nvim_buf_line_count(bufnr)
pos1[1] = math.min(pos1[1], buf_line_count - 1)
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua
index 714038f8e4..d1b50304c7 100644
--- a/runtime/lua/vim/diagnostic.lua
+++ b/runtime/lua/vim/diagnostic.lua
@@ -744,7 +744,7 @@ function M.get_namespaces()
end
---@class Diagnostic
----@field buffer integer
+---@field bufnr integer
---@field lnum integer 0-indexed
---@field end_lnum nil|integer 0-indexed
---@field col integer 0-indexed
diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua
index d71a806ea8..a6cfcb730f 100644
--- a/runtime/lua/vim/highlight.lua
+++ b/runtime/lua/vim/highlight.lua
@@ -15,8 +15,8 @@ M.priorities = {
---@param bufnr integer Buffer number to apply highlighting to
---@param ns integer Namespace to add highlight to
---@param higroup string Highlight group to use for highlighting
----@param start { [1]: integer, [2]: integer } Start position {line, col}
----@param finish { [1]: integer, [2]: integer } Finish position {line, col}
+---@param start integer[]|string Start of region as a (line, column) tuple or string accepted by |getpos()|
+---@param finish integer[]|string End of region as a (line, column) tuple or string accepted by |getpos()|
---@param opts table|nil Optional parameters
-- - regtype type of range (see |setreg()|, default charwise)
-- - inclusive boolean indicating whether the range is end-inclusive (default false)
@@ -27,11 +27,6 @@ function M.range(bufnr, ns, higroup, start, finish, opts)
local inclusive = opts.inclusive or false
local priority = opts.priority or M.priorities.user
- -- sanity check
- if start[2] < 0 or finish[1] < start[1] then
- return
- end
-
local region = vim.region(bufnr, start, finish, regtype, inclusive)
for linenr, cols in pairs(region) do
local end_row
@@ -104,18 +99,12 @@ function M.on_yank(opts)
yank_timer:close()
end
- local pos1 = vim.fn.getpos("'[")
- local pos2 = vim.fn.getpos("']")
-
- pos1 = { pos1[2] - 1, pos1[3] - 1 + pos1[4] }
- pos2 = { pos2[2] - 1, pos2[3] - 1 + pos2[4] }
-
M.range(
bufnr,
yank_ns,
higroup,
- pos1,
- pos2,
+ "'[",
+ "']",
{ regtype = event.regtype, inclusive = event.inclusive, priority = M.priorities.user }
)
diff --git a/runtime/lua/vim/loader.lua b/runtime/lua/vim/loader.lua
index 38b1e9fc0f..66627fe4e7 100644
--- a/runtime/lua/vim/loader.lua
+++ b/runtime/lua/vim/loader.lua
@@ -5,7 +5,7 @@ local loaders = package.loaders
local M = {}
----@alias CacheHash {mtime: {sec:number, nsec:number}, size:number, type: string}
+---@alias CacheHash {mtime: {nsec: integer, sec: integer}, size: integer, type?: uv.aliases.fs_stat_types}
---@alias CacheEntry {hash:CacheHash, chunk:string}
---@class ModuleFindOpts
@@ -28,12 +28,11 @@ M.enabled = false
---@field _rtp string[]
---@field _rtp_pure string[]
---@field _rtp_key string
+---@field _hashes? table<string, CacheHash>
local Loader = {
VERSION = 3,
---@type table<string, table<string,ModuleInfo>>
_indexed = {},
- ---@type table<string, CacheHash>
- _hashes = {},
---@type table<string, string[]>
_topmods = {},
_loadfile = loadfile,
@@ -44,9 +43,13 @@ local Loader = {
}
--- @param path string
---- @return uv.fs_stat.result
+--- @return CacheHash
--- @private
function Loader.get_hash(path)
+ if not Loader._hashes then
+ return uv.fs_stat(path) --[[@as CacheHash]]
+ end
+
if not Loader._hashes[path] then
-- Note we must never save a stat for a non-existent path.
-- For non-existent paths fs_stat() will return nil.
@@ -163,13 +166,16 @@ end
---@return string|function
---@private
function Loader.loader(modname)
+ Loader._hashes = {}
local ret = M.find(modname)[1]
if ret then
-- Make sure to call the global loadfile so we respect any augmentations done elsewhere.
-- E.g. profiling
local chunk, err = loadfile(ret.modpath)
+ Loader._hashes = nil
return chunk or error(err)
end
+ Loader._hashes = nil
return '\ncache_loader: module ' .. modname .. ' not found'
end
@@ -373,7 +379,9 @@ function M.reset(path)
end
-- Path could be a directory so just clear all the hashes.
- Loader._hashes = {}
+ if Loader._hashes then
+ Loader._hashes = {}
+ end
end
--- Enables the experimental Lua module loader:
@@ -441,7 +449,7 @@ function Loader.lsmod(path)
if topname then
Loader._indexed[path][topname] = { modpath = modpath, modname = topname }
Loader._topmods[topname] = Loader._topmods[topname] or {}
- if not vim.tbl_contains(Loader._topmods[topname], path) then
+ if not vim.list_contains(Loader._topmods[topname], path) then
table.insert(Loader._topmods[topname], path)
end
end
@@ -515,7 +523,7 @@ function M._inspect(opts)
{ ms(Loader._stats[stat].time / Loader._stats[stat].total) .. '\n', 'Bold' },
})
for k, v in pairs(Loader._stats[stat]) do
- if not vim.tbl_contains({ 'time', 'total' }, k) then
+ if not vim.list_contains({ 'time', 'total' }, k) then
chunks[#chunks + 1] = { '* ' .. k .. ':' .. string.rep(' ', 9 - #k) }
chunks[#chunks + 1] = { tostring(v) .. '\n', 'Number' }
end
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua
index 2d39f2d45d..5c78bd7580 100644
--- a/runtime/lua/vim/lsp.lua
+++ b/runtime/lua/vim/lsp.lua
@@ -171,7 +171,7 @@ local function for_each_buffer_client(bufnr, fn, restrict_client_ids)
if restrict_client_ids and #restrict_client_ids > 0 then
local filtered_client_ids = {}
for client_id in pairs(client_ids) do
- if vim.tbl_contains(restrict_client_ids, client_id) then
+ if vim.list_contains(restrict_client_ids, client_id) then
filtered_client_ids[client_id] = true
end
end
@@ -2186,7 +2186,7 @@ function lsp.formatexpr(opts)
opts = opts or {}
local timeout_ms = opts.timeout_ms or 500
- if vim.tbl_contains({ 'i', 'R', 'ic', 'ix' }, vim.fn.mode()) then
+ if vim.list_contains({ 'i', 'R', 'ic', 'ix' }, vim.fn.mode()) then
-- `formatexpr` is also called when exceeding `textwidth` in insert mode
-- fall back to internal formatting
return 1
@@ -2384,4 +2384,3 @@ lsp.commands = setmetatable({}, {
})
return lsp
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/_snippet.lua b/runtime/lua/vim/lsp/_snippet.lua
index 797d8960d5..e7ada5415f 100644
--- a/runtime/lua/vim/lsp/_snippet.lua
+++ b/runtime/lua/vim/lsp/_snippet.lua
@@ -17,14 +17,14 @@ P.take_until = function(targets, specials)
table.insert(raw, '\\')
new_pos = new_pos + 1
c = string.sub(input, new_pos, new_pos)
- if not vim.tbl_contains(targets, c) and not vim.tbl_contains(specials, c) then
+ if not vim.list_contains(targets, c) and not vim.list_contains(specials, c) then
table.insert(esc, '\\')
end
table.insert(raw, c)
table.insert(esc, c)
new_pos = new_pos + 1
else
- if vim.tbl_contains(targets, c) then
+ if vim.list_contains(targets, c) then
break
end
table.insert(raw, c)
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua
index 8bf3764f5e..3d9011656f 100644
--- a/runtime/lua/vim/lsp/buf.lua
+++ b/runtime/lua/vim/lsp/buf.lua
@@ -806,4 +806,3 @@ function M.execute_command(command_params)
end
return M
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/codelens.lua b/runtime/lua/vim/lsp/codelens.lua
index 81cac6a511..005a0047fa 100644
--- a/runtime/lua/vim/lsp/codelens.lua
+++ b/runtime/lua/vim/lsp/codelens.lua
@@ -42,7 +42,7 @@ local function execute_lens(lens, bufnr, client_id)
-- Need to use the client that returned the lens → must not use buf_request
local command_provider = client.server_capabilities.executeCommandProvider
local commands = type(command_provider) == 'table' and command_provider.commands or {}
- if not vim.tbl_contains(commands, command.command) then
+ if not vim.list_contains(commands, command.command) then
vim.notify(
string.format(
'Language server does not support command `%s`. This command may require a client extension.',
diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua
index d01f8e6159..71bef43bc1 100644
--- a/runtime/lua/vim/lsp/handlers.lua
+++ b/runtime/lua/vim/lsp/handlers.lua
@@ -644,4 +644,3 @@ for k, fn in pairs(M) do
end
return M
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua
index 51dcb7d21d..3d5bc06c3f 100644
--- a/runtime/lua/vim/lsp/log.lua
+++ b/runtime/lua/vim/lsp/log.lua
@@ -174,4 +174,3 @@ function log.should_log(level)
end
return log
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/protocol.lua b/runtime/lua/vim/lsp/protocol.lua
index f4489ad17d..2cb8fc7955 100644
--- a/runtime/lua/vim/lsp/protocol.lua
+++ b/runtime/lua/vim/lsp/protocol.lua
@@ -894,4 +894,3 @@ function protocol.resolve_capabilities(server_capabilities)
end
return protocol
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua
index 30b61d01d6..af3190c9bd 100644
--- a/runtime/lua/vim/lsp/rpc.lua
+++ b/runtime/lua/vim/lsp/rpc.lua
@@ -753,4 +753,3 @@ return {
client_errors = client_errors,
create_read_loop = create_read_loop,
}
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua
index ebde7af16c..31af2afb0b 100644
--- a/runtime/lua/vim/lsp/util.lua
+++ b/runtime/lua/vim/lsp/util.lua
@@ -1476,7 +1476,7 @@ end
local function close_preview_window(winnr, bufnrs)
vim.schedule(function()
-- exit if we are in one of ignored buffers
- if bufnrs and vim.tbl_contains(bufnrs, api.nvim_get_current_buf()) then
+ if bufnrs and vim.list_contains(bufnrs, api.nvim_get_current_buf()) then
return
end
@@ -2154,4 +2154,3 @@ M._get_line_byte_from_position = get_line_byte_from_position
M.buf_versions = {}
return M
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua
index eb734fb512..f700f4a6b3 100644
--- a/runtime/lua/vim/shared.lua
+++ b/runtime/lua/vim/shared.lua
@@ -252,12 +252,53 @@ function vim.tbl_filter(func, t)
return rettab
end
---- Checks if a list-like (vector) table contains `value`.
+--- Checks if a table contains a given value, specified either directly or via
+--- a predicate that is checked for each value.
+---
+--- Example:
+--- <pre>lua
+--- vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
+--- return vim.deep_equal(v, { 'b', 'c' })
+--- end, { predicate = true })
+--- -- true
+--- </pre>
+---
+---@see |vim.list_contains()| for checking values in list-like tables
---
---@param t table Table to check
+---@param value any Value to compare or predicate function reference
+---@param opts (table|nil) Keyword arguments |kwargs|:
+--- - predicate: (boolean) `value` is a function reference to be checked (default false)
+---@return boolean `true` if `t` contains `value`
+function vim.tbl_contains(t, value, opts)
+ vim.validate({ t = { t, 't' }, opts = { opts, 't', true } })
+
+ local pred
+ if opts and opts.predicate then
+ vim.validate({ value = { value, 'c' } })
+ pred = value
+ else
+ pred = function(v)
+ return v == value
+ end
+ end
+
+ for _, v in pairs(t) do
+ if pred(v) then
+ return true
+ end
+ end
+ return false
+end
+
+--- Checks if a list-like table (integer keys without gaps) contains `value`.
+---
+---@see |vim.tbl_contains()| for checking values in general tables
+---
+---@param t table Table to check (must be list-like, not validated)
---@param value any Value to compare
---@return boolean `true` if `t` contains `value`
-function vim.tbl_contains(t, value)
+function vim.list_contains(t, value)
vim.validate({ t = { t, 't' } })
for _, v in ipairs(t) do
@@ -279,10 +320,10 @@ function vim.tbl_isempty(t)
return next(t) == nil
end
---- We only merge empty tables or tables that are not a list
+--- We only merge empty tables or tables that are not an array (indexed by integers)
---@private
local function can_merge(v)
- return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_islist(v))
+ return type(v) == 'table' and (vim.tbl_isempty(v) or not vim.tbl_isarray(v))
end
local function tbl_extend(behavior, deep_extend, ...)
@@ -513,15 +554,15 @@ function vim.spairs(t)
end
end
---- Tests if a Lua table can be treated as an array.
+--- Tests if a Lua table can be treated as an array (a table indexed by integers).
---
--- Empty table `{}` is assumed to be an array, unless it was created by
--- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
--- for example from |rpcrequest()| or |vim.fn|.
---
----@param t table Table
----@return boolean `true` if array-like table, else `false`
-function vim.tbl_islist(t)
+---@param t table
+---@return boolean `true` if array-like table, else `false`.
+function vim.tbl_isarray(t)
if type(t) ~= 'table' then
return false
end
@@ -529,7 +570,8 @@ function vim.tbl_islist(t)
local count = 0
for k, _ in pairs(t) do
- if type(k) == 'number' then
+ --- Check if the number k is an integer
+ if type(k) == 'number' and k == math.floor(k) then
count = count + 1
else
return false
@@ -548,6 +590,38 @@ function vim.tbl_islist(t)
end
end
+--- Tests if a Lua table can be treated as a list (a table indexed by consecutive integers starting from 1).
+---
+--- Empty table `{}` is assumed to be an list, unless it was created by
+--- |vim.empty_dict()| or returned as a dict-like |API| or Vimscript result,
+--- for example from |rpcrequest()| or |vim.fn|.
+---
+---@param t table
+---@return boolean `true` if list-like table, else `false`.
+function vim.tbl_islist(t)
+ if type(t) ~= 'table' then
+ return false
+ end
+
+ local num_elem = vim.tbl_count(t)
+
+ if num_elem == 0 then
+ -- TODO(bfredl): in the future, we will always be inside nvim
+ -- then this check can be deleted.
+ if vim._empty_dict_mt == nil then
+ return nil
+ end
+ return getmetatable(t) ~= vim._empty_dict_mt
+ else
+ for i = 1, num_elem do
+ if t[i] == nil then
+ return false
+ end
+ end
+ return true
+ end
+end
+
--- Counts the number of non-nil values in table `t`.
---
--- <pre>lua
@@ -811,4 +885,3 @@ function vim.defaulttable(create)
end
return vim
--- vim:sw=2 ts=2 et
diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua
index 5b87e6ac31..8a747ba14c 100644
--- a/runtime/lua/vim/treesitter/query.lua
+++ b/runtime/lua/vim/treesitter/query.lua
@@ -458,7 +458,7 @@ local directive_handlers = {
metadata[id] = {}
end
- local pattern, replacement = pred[3], pred[3]
+ local pattern, replacement = pred[3], pred[4]
assert(type(pattern) == 'string')
assert(type(replacement) == 'string')
diff --git a/runtime/lua/vim/uri.lua b/runtime/lua/vim/uri.lua
index 38759fcdc0..08ed829114 100644
--- a/runtime/lua/vim/uri.lua
+++ b/runtime/lua/vim/uri.lua
@@ -134,4 +134,3 @@ return {
uri_to_fname = uri_to_fname,
uri_to_bufnr = uri_to_bufnr,
}
--- vim:sw=2 ts=2 et