fix: resolve all remaining LuaLS diagnostics

This commit is contained in:
Lewis Russell
2025-01-24 13:01:25 +00:00
committed by Lewis Russell
parent 83479b95ab
commit 6aa42e8f92
41 changed files with 177 additions and 104 deletions

View File

@ -10,7 +10,8 @@
"${3rd}/luv/library" "${3rd}/luv/library"
], ],
"ignoreDir": [ "ignoreDir": [
"test" "test",
"_vim9script.lua"
], ],
"checkThirdParty": "Disable" "checkThirdParty": "Disable"
}, },

View File

@ -834,6 +834,12 @@ TSNode:range({include_bytes}) *TSNode:range()*
Parameters: ~ Parameters: ~
• {include_bytes} (`boolean?`) • {include_bytes} (`boolean?`)
Return (multiple): ~
(`integer`)
(`integer`)
(`integer`)
(`integer`)
TSNode:sexpr() *TSNode:sexpr()* TSNode:sexpr() *TSNode:sexpr()*
Get an S-expression representing the node as a string. Get an S-expression representing the node as a string.
@ -942,7 +948,7 @@ get_node_range({node_or_range}) *vim.treesitter.get_node_range()*
Returns the node's range or an unpacked range table Returns the node's range or an unpacked range table
Parameters: ~ Parameters: ~
• {node_or_range} (`TSNode|table`) Node or table of positions • {node_or_range} (`TSNode|Range4`) Node or table of positions
Return (multiple): ~ Return (multiple): ~
(`integer`) start_row (`integer`) start_row
@ -1181,7 +1187,7 @@ inspect({lang}) *vim.treesitter.language.inspect()*
• {lang} (`string`) Language • {lang} (`string`) Language
Return: ~ Return: ~
(`table`) (`TSLangInfo`)
register({lang}, {filetype}) *vim.treesitter.language.register()* register({lang}, {filetype}) *vim.treesitter.language.register()*
Register a parser named {lang} to be used for {filetype}(s). Register a parser named {lang} to be used for {filetype}(s).

View File

@ -31,22 +31,23 @@ end
-- No need to do anything if pcall and xpcall are already safe. -- No need to do anything if pcall and xpcall are already safe.
if isCoroutineSafe(pcall) and isCoroutineSafe(xpcall) then if isCoroutineSafe(pcall) and isCoroutineSafe(xpcall) then
copcall = pcall _G.copcall = pcall
coxpcall = xpcall _G.coxpcall = xpcall
return { pcall = pcall, xpcall = xpcall, running = coroutine.running } return { pcall = pcall, xpcall = xpcall, running = coroutine.running }
end end
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
-- Implements xpcall with coroutines -- Implements xpcall with coroutines
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
local performResume, handleReturnValue local performResume
local oldpcall, oldxpcall = pcall, xpcall local oldpcall, oldxpcall = pcall, xpcall
local pack = table.pack or function(...) return {n = select("#", ...), ...} end local pack = table.pack or function(...) return {n = select("#", ...), ...} end
local unpack = table.unpack or unpack local unpack = table.unpack or unpack
local running = coroutine.running local running = coroutine.running
--- @type table<thread,thread>
local coromap = setmetatable({}, { __mode = "k" }) local coromap = setmetatable({}, { __mode = "k" })
function handleReturnValue(err, co, status, ...) local function handleReturnValue(err, co, status, ...)
if not status then if not status then
return false, err(debug.traceback(co, (...)), ...) return false, err(debug.traceback(co, (...)), ...)
end end
@ -61,11 +62,12 @@ function performResume(err, co, ...)
return handleReturnValue(err, co, coroutine.resume(co, ...)) return handleReturnValue(err, co, coroutine.resume(co, ...))
end end
--- @diagnostic disable-next-line: unused-vararg
local function id(trace, ...) local function id(trace, ...)
return trace return trace
end end
function coxpcall(f, err, ...) function _G.coxpcall(f, err, ...)
local current = running() local current = running()
if not current then if not current then
if err == id then if err == id then
@ -88,6 +90,7 @@ function coxpcall(f, err, ...)
end end
end end
--- @param coro? thread
local function corunning(coro) local function corunning(coro)
if coro ~= nil then if coro ~= nil then
assert(type(coro)=="thread", "Bad argument; expected thread, got: "..type(coro)) assert(type(coro)=="thread", "Bad argument; expected thread, got: "..type(coro))
@ -105,7 +108,7 @@ end
-- Implements pcall with coroutines -- Implements pcall with coroutines
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
function copcall(f, ...) function _G.copcall(f, ...)
return coxpcall(f, id, ...) return coxpcall(f, id, ...)
end end

View File

@ -201,6 +201,7 @@ local function highlight_man_page()
api.nvim_buf_set_lines(0, 0, -1, false, lines) api.nvim_buf_set_lines(0, 0, -1, false, lines)
for _, hl in ipairs(hls) do for _, hl in ipairs(hls) do
--- @diagnostic disable-next-line: deprecated
api.nvim_buf_add_highlight(0, -1, HlGroups[hl.attr], hl.row, hl.start, hl.final) api.nvim_buf_add_highlight(0, -1, HlGroups[hl.attr], hl.row, hl.start, hl.final)
end end

View File

@ -317,7 +317,7 @@ end
--- @return nil|integer --- @return nil|integer
local function register_hl(state, hl) local function register_hl(state, hl)
if type(hl) == 'table' then if type(hl) == 'table' then
hl = hl[#hl] hl = hl[#hl] --- @type string|integer
end end
if type(hl) == 'nil' then if type(hl) == 'nil' then
return return
@ -1162,7 +1162,9 @@ local function extend_pre(out, state)
s = s .. _pre_text_to_html(state, row) s = s .. _pre_text_to_html(state, row)
end end
local true_line_len = #line + 1 local true_line_len = #line + 1
for k in pairs(style_line) do for k in
pairs(style_line --[[@as table<string,any>]])
do
if type(k) == 'number' and k > true_line_len then if type(k) == 'number' and k > true_line_len then
true_line_len = k true_line_len = k
end end

View File

@ -425,6 +425,7 @@ local VIM_CMD_ARG_MAX = 20
--- vim.cmd.colorscheme('blue') --- vim.cmd.colorscheme('blue')
--- ``` --- ```
--- ---
---@diagnostic disable-next-line: undefined-doc-param
---@param command string|table Command(s) to execute. ---@param command string|table Command(s) to execute.
--- If a string, executes multiple lines of Vimscript at once. In this --- If a string, executes multiple lines of Vimscript at once. In this
--- case, it is an alias to |nvim_exec2()|, where `opts.output` is set --- case, it is an alias to |nvim_exec2()|, where `opts.output` is set
@ -441,10 +442,12 @@ vim.cmd = setmetatable({}, {
return '' return ''
end end
end, end,
--- @param t table<string,function>
__index = function(t, command) __index = function(t, command)
t[command] = function(...) t[command] = function(...)
local opts local opts --- @type vim.api.keyset.cmd
if select('#', ...) == 1 and type(select(1, ...)) == 'table' then if select('#', ...) == 1 and type(select(1, ...)) == 'table' then
--- @type vim.api.keyset.cmd
opts = select(1, ...) opts = select(1, ...)
-- Move indexed positions in opts to opt.args -- Move indexed positions in opts to opt.args
@ -455,6 +458,7 @@ vim.cmd = setmetatable({}, {
break break
end end
opts.args[i] = opts[i] opts.args[i] = opts[i]
--- @diagnostic disable-next-line: no-unknown
opts[i] = nil opts[i] = nil
end end
end end
@ -529,7 +533,7 @@ function vim.region(bufnr, pos1, pos2, regtype, inclusive)
end end
if pos1[1] > pos2[1] or (pos1[1] == pos2[1] and pos1[2] > pos2[2]) then if pos1[1] > pos2[1] or (pos1[1] == pos2[1] and pos1[2] > pos2[2]) then
pos1, pos2 = pos2, pos1 pos1, pos2 = pos2, pos1 --- @type [integer, integer], [integer, integer]
end end
-- getpos() may return {0,0,0,0} -- getpos() may return {0,0,0,0}
@ -701,6 +705,7 @@ function vim._on_key(buf, typed_buf)
local discard = false local discard = false
for k, v in pairs(on_key_cbs) do for k, v in pairs(on_key_cbs) do
local fn = v[1] local fn = v[1]
--- @type boolean, any
local ok, rv = xpcall(function() local ok, rv = xpcall(function()
return fn(buf, typed_buf) return fn(buf, typed_buf)
end, debug.traceback) end, debug.traceback)
@ -828,6 +833,7 @@ function vim.str_utfindex(s, encoding, index, strict_indexing)
-- Return (multiple): ~ -- Return (multiple): ~
-- (`integer`) UTF-32 index -- (`integer`) UTF-32 index
-- (`integer`) UTF-16 index -- (`integer`) UTF-16 index
--- @diagnostic disable-next-line: redundant-return-value
return col32, col16 return col32, col16
end end
@ -1000,7 +1006,7 @@ function vim._expand_pat(pat, env)
or vim.v == final_env and { 'v:', 'var' } or vim.v == final_env and { 'v:', 'var' }
or { nil, nil } or { nil, nil }
) )
assert(prefix, "Can't resolve final_env") assert(prefix and type, "Can't resolve final_env")
local vars = vim.fn.getcompletion(prefix .. match_part, type) --- @type string[] local vars = vim.fn.getcompletion(prefix .. match_part, type) --- @type string[]
insert_keys(vim insert_keys(vim
.iter(vars) .iter(vars)

View File

@ -1,3 +1,5 @@
--- @diagnostic disable:no-unknown
--- @class vim._inspector.Filter --- @class vim._inspector.Filter
--- @inlinedoc --- @inlinedoc
--- ---
@ -78,6 +80,7 @@ function vim.inspect_pos(bufnr, row, col, filter)
-- treesitter -- treesitter
if filter.treesitter then if filter.treesitter then
for _, capture in pairs(vim.treesitter.get_captures_at_pos(bufnr, row, col)) do for _, capture in pairs(vim.treesitter.get_captures_at_pos(bufnr, row, col)) do
--- @diagnostic disable-next-line: inject-field
capture.hl_group = '@' .. capture.capture .. '.' .. capture.lang capture.hl_group = '@' .. capture.capture .. '.' .. capture.lang
results.treesitter[#results.treesitter + 1] = resolve_hl(capture) results.treesitter[#results.treesitter + 1] = resolve_hl(capture)
end end

View File

@ -3,6 +3,10 @@
-- DO NOT EDIT -- DO NOT EDIT
error('Cannot require a meta file') error('Cannot require a meta file')
--- This file embeds vimdoc as the function descriptions
--- so ignore any doc related errors.
--- @diagnostic disable: undefined-doc-name,luadoc-miss-symbol
vim.api = {} vim.api = {}
--- @private --- @private

View File

@ -688,6 +688,7 @@ local function remove_value(info, current, new)
end end
local function create_option_accessor(scope) local function create_option_accessor(scope)
--- @diagnostic disable-next-line: no-unknown
local option_mt local option_mt
local function make_option(name, value) local function make_option(name, value)
@ -696,6 +697,7 @@ local function create_option_accessor(scope)
if type(value) == 'table' and getmetatable(value) == option_mt then if type(value) == 'table' and getmetatable(value) == option_mt then
assert(name == value._name, "must be the same value, otherwise that's weird.") assert(name == value._name, "must be the same value, otherwise that's weird.")
--- @diagnostic disable-next-line: no-unknown
value = value._value value = value._value
end end
@ -719,6 +721,7 @@ local function create_option_accessor(scope)
end, end,
append = function(self, right) append = function(self, right)
--- @diagnostic disable-next-line: no-unknown
self._value = add_value(self._info, self._value, right) self._value = add_value(self._info, self._value, right)
self:_set() self:_set()
end, end,
@ -728,6 +731,7 @@ local function create_option_accessor(scope)
end, end,
prepend = function(self, right) prepend = function(self, right)
--- @diagnostic disable-next-line: no-unknown
self._value = prepend_value(self._info, self._value, right) self._value = prepend_value(self._info, self._value, right)
self:_set() self:_set()
end, end,
@ -737,6 +741,7 @@ local function create_option_accessor(scope)
end, end,
remove = function(self, right) remove = function(self, right)
--- @diagnostic disable-next-line: no-unknown
self._value = remove_value(self._info, self._value, right) self._value = remove_value(self._info, self._value, right)
self:_set() self:_set()
end, end,

View File

@ -891,6 +891,7 @@ local function set_list(loclist, opts)
if open then if open then
if not loclist then if not loclist then
-- First navigate to the diagnostics quickfix list. -- First navigate to the diagnostics quickfix list.
--- @type integer
local nr = vim.fn.getqflist({ id = qf_id, nr = 0 }).nr local nr = vim.fn.getqflist({ id = qf_id, nr = 0 }).nr
api.nvim_command(('silent %dchistory'):format(nr)) api.nvim_command(('silent %dchistory'):format(nr))
@ -2250,18 +2251,24 @@ function M.open_float(opts, ...)
if not opts.focus_id then if not opts.focus_id then
opts.focus_id = scope opts.focus_id = scope
end end
--- @diagnostic disable-next-line: param-type-mismatch
local float_bufnr, winnr = vim.lsp.util.open_floating_preview(lines, 'plaintext', opts) local float_bufnr, winnr = vim.lsp.util.open_floating_preview(lines, 'plaintext', opts)
vim.bo[float_bufnr].path = vim.bo[bufnr].path vim.bo[float_bufnr].path = vim.bo[bufnr].path
--- @diagnostic disable-next-line: deprecated
local add_highlight = api.nvim_buf_add_highlight
for i, hl in ipairs(highlights) do for i, hl in ipairs(highlights) do
local line = lines[i] local line = lines[i]
local prefix_len = hl.prefix and hl.prefix.length or 0 local prefix_len = hl.prefix and hl.prefix.length or 0
local suffix_len = hl.suffix and hl.suffix.length or 0 local suffix_len = hl.suffix and hl.suffix.length or 0
if prefix_len > 0 then if prefix_len > 0 then
api.nvim_buf_add_highlight(float_bufnr, -1, hl.prefix.hlname, i - 1, 0, prefix_len) add_highlight(float_bufnr, -1, hl.prefix.hlname, i - 1, 0, prefix_len)
end end
api.nvim_buf_add_highlight(float_bufnr, -1, hl.hlname, i - 1, prefix_len, #line - suffix_len) add_highlight(float_bufnr, -1, hl.hlname, i - 1, prefix_len, #line - suffix_len)
if suffix_len > 0 then if suffix_len > 0 then
api.nvim_buf_add_highlight(float_bufnr, -1, hl.suffix.hlname, i - 1, #line - suffix_len, -1) add_highlight(float_bufnr, -1, hl.suffix.hlname, i - 1, #line - suffix_len, -1)
end end
end end

View File

@ -732,8 +732,8 @@ local extension = {
mc = detect.mc, mc = detect.mc,
quake = 'm3quake', quake = 'm3quake',
m4 = function(path, bufnr) m4 = function(path, bufnr)
path = path:lower() local pathl = path:lower()
return not (path:find('html%.m4$') or path:find('fvwm2rc')) and 'm4' or nil return not (pathl:find('html%.m4$') or pathl:find('fvwm2rc')) and 'm4' or nil
end, end,
eml = 'mail', eml = 'mail',
mk = detect.make, mk = detect.make,

View File

@ -881,7 +881,7 @@ end
--- (refactor of filetype.vim since the patterns are case-insensitive) --- (refactor of filetype.vim since the patterns are case-insensitive)
--- @type vim.filetype.mapfn --- @type vim.filetype.mapfn
function M.log(path, _) function M.log(path, _)
path = path:lower() path = path:lower() --- @type string LuaLS bug
if if
findany( findany(
path, path,
@ -1167,7 +1167,7 @@ end
--- @type vim.filetype.mapfn --- @type vim.filetype.mapfn
function M.perl(path, bufnr) function M.perl(path, bufnr)
local dir_name = vim.fs.dirname(path) local dir_name = vim.fs.dirname(path)
if fn.expand(path, '%:e') == 't' and (dir_name == 't' or dir_name == 'xt') then if fn.fnamemodify(path, '%:e') == 't' and (dir_name == 't' or dir_name == 'xt') then
return 'perl' return 'perl'
end end
local first_line = getline(bufnr, 1) local first_line = getline(bufnr, 1)
@ -1375,7 +1375,7 @@ end
local udev_rules_pattern = '^%s*udev_rules%s*=%s*"([%^"]+)/*".*' local udev_rules_pattern = '^%s*udev_rules%s*=%s*"([%^"]+)/*".*'
--- @type vim.filetype.mapfn --- @type vim.filetype.mapfn
function M.rules(path) function M.rules(path)
path = path:lower() path = path:lower() --- @type string LuaLS bug
if if
findany(path, { findany(path, {
'/etc/udev/.*%.rules$', '/etc/udev/.*%.rules$',
@ -1398,7 +1398,7 @@ function M.rules(path)
if not ok then if not ok then
return 'hog' return 'hog'
end end
local dir = fn.expand(path, ':h') local dir = fn.fnamemodify(path, ':h')
for _, line in ipairs(config_lines) do for _, line in ipairs(config_lines) do
local match = line:match(udev_rules_pattern) local match = line:match(udev_rules_pattern)
if match then if match then

View File

@ -546,7 +546,7 @@ local function expand_home(path, sep)
home = home:sub(1, -2) home = home:sub(1, -2)
end end
path = home .. path:sub(2) path = home .. path:sub(2) --- @type string
end end
return path return path
@ -620,7 +620,7 @@ function M.normalize(path, opts)
-- Expand environment variables if `opts.expand_env` isn't `false` -- Expand environment variables if `opts.expand_env` isn't `false`
if opts.expand_env == nil or opts.expand_env then if opts.expand_env == nil or opts.expand_env then
path = path:gsub('%$([%w_]+)', uv.os_getenv) path = path:gsub('%$([%w_]+)', uv.os_getenv) --- @type string
end end
if win then if win then

View File

@ -53,6 +53,7 @@ function M.to_lpeg(pattern)
end end
-- luacheck: pop -- luacheck: pop
--- @diagnostic disable-next-line: missing-fields
local p = P({ local p = P({
'Pattern', 'Pattern',
Pattern = V('Elem') ^ -1 * V('End'), Pattern = V('Elem') ^ -1 * V('End'),

View File

@ -126,7 +126,7 @@ local function filepath_to_healthcheck(path)
-- */health/init.lua -- */health/init.lua
name = vim.fs.dirname(vim.fs.dirname(subpath)) name = vim.fs.dirname(vim.fs.dirname(subpath))
end end
name = name:gsub('/', '.') name = assert(name:gsub('/', '.')) --- @type string
func = 'require("' .. name .. '.health").check()' func = 'require("' .. name .. '.health").check()'
filetype = 'l' filetype = 'l'
@ -235,7 +235,7 @@ local function format_report_message(status, msg, ...)
-- Report each suggestion -- Report each suggestion
for _, v in ipairs(varargs) do for _, v in ipairs(varargs) do
if v then if v then
output = output .. '\n - ' .. indent_after_line1(v, 6) output = output .. '\n - ' .. indent_after_line1(v, 6) --- @type string
end end
end end
end end
@ -445,8 +445,7 @@ function M._check(mods, plugin_names)
-- Quit with 'q' inside healthcheck buffers. -- Quit with 'q' inside healthcheck buffers.
vim.keymap.set('n', 'q', function() vim.keymap.set('n', 'q', function()
local ok, _ = pcall(vim.cmd.close) if not pcall(vim.cmd.close) then
if not ok then
vim.cmd.bdelete() vim.cmd.bdelete()
end end
end, { buffer = bufnr, silent = true, noremap = true, nowait = true }) end, { buffer = bufnr, silent = true, noremap = true, nowait = true })

View File

@ -183,13 +183,16 @@ end
local function check_rplugin_manifest() local function check_rplugin_manifest()
health.start('Remote Plugins') health.start('Remote Plugins')
local existing_rplugins = {} local existing_rplugins = {} --- @type table<string,string>
for _, item in ipairs(vim.fn['remote#host#PluginsForHost']('python3')) do --- @type {path:string}[]
local items = vim.fn['remote#host#PluginsForHost']('python3')
for _, item in ipairs(items) do
existing_rplugins[item.path] = 'python3' existing_rplugins[item.path] = 'python3'
end end
local require_update = false local require_update = false
local handle_path = function(path) local handle_path = function(path)
--- @type string[]
local python_glob = vim.fn.glob(path .. '/rplugin/python*', true, true) local python_glob = vim.fn.glob(path .. '/rplugin/python*', true, true)
if vim.tbl_isempty(python_glob) then if vim.tbl_isempty(python_glob) then
return return
@ -198,6 +201,7 @@ local function check_rplugin_manifest()
local python_dir = python_glob[1] local python_dir = python_glob[1]
local python_version = vim.fs.basename(python_dir) local python_version = vim.fs.basename(python_dir)
--- @type string[]
local scripts = vim.fn.glob(python_dir .. '/*.py', true, true) local scripts = vim.fn.glob(python_dir .. '/*.py', true, true)
vim.list_extend(scripts, vim.fn.glob(python_dir .. '/*/__init__.py', true, true)) vim.list_extend(scripts, vim.fn.glob(python_dir .. '/*/__init__.py', true, true))
@ -227,7 +231,10 @@ local function check_rplugin_manifest()
end end
end end
for _, path in ipairs(vim.fn.map(vim.split(vim.o.runtimepath, ','), 'resolve(v:val)')) do --- @type string[]
local paths = vim.fn.map(vim.split(vim.o.runtimepath, ','), 'resolve(v:val)')
for _, path in ipairs(paths) do
handle_path(path) handle_path(path)
end end

View File

@ -1,3 +1,4 @@
--- @diagnostic disable: no-unknown
local inspect = { local inspect = {
_VERSION = 'inspect.lua 3.1.0', _VERSION = 'inspect.lua 3.1.0',
_URL = 'http://github.com/kikito/inspect.lua', _URL = 'http://github.com/kikito/inspect.lua',

View File

@ -64,7 +64,7 @@ local state_by_group = setmetatable({}, {
---@param client vim.lsp.Client ---@param client vim.lsp.Client
---@return vim.lsp.CTGroup ---@return vim.lsp.CTGroup
local function get_group(client) local function get_group(client)
local allow_inc_sync = vim.F.if_nil(client.flags.allow_incremental_sync, true) --- @type boolean local allow_inc_sync = vim.F.if_nil(client.flags.allow_incremental_sync, true)
local change_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change') local change_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change')
local sync_kind = change_capability or protocol.TextDocumentSyncKind.None local sync_kind = change_capability or protocol.TextDocumentSyncKind.None
if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then

View File

@ -1,8 +1,8 @@
---@meta ---@meta
error('Cannot require a meta file') error('Cannot require a meta file')
---@alias lsp.Handler fun(err: lsp.ResponseError?, result: any, context: lsp.HandlerContext): ...any ---@alias lsp.Handler fun(err: lsp.ResponseError?, result: any, context: lsp.HandlerContext, config?: table): ...any
---@alias lsp.MultiHandler fun(results: table<integer,{err: lsp.ResponseError?, result: any}>, context: lsp.HandlerContext): ...any ---@alias lsp.MultiHandler fun(results: table<integer,{err: lsp.ResponseError?, result: any}>, context: lsp.HandlerContext, config?: table): ...any
---@class lsp.HandlerContext ---@class lsp.HandlerContext
---@field method string ---@field method string

View File

@ -127,6 +127,7 @@ local function node(type)
end end
-- stylua: ignore -- stylua: ignore
--- @diagnostic disable-next-line: missing-fields
local G = P({ local G = P({
'snippet'; 'snippet';
snippet = Ct(Cg( snippet = Ct(Cg(

View File

@ -450,10 +450,10 @@ local function range_from_selection(bufnr, mode)
-- A user can start visual selection at the end and move backwards -- A user can start visual selection at the end and move backwards
-- Normalize the range to start < end -- Normalize the range to start < end
if start_row == end_row and end_col < start_col then if start_row == end_row and end_col < start_col then
end_col, start_col = start_col, end_col end_col, start_col = start_col, end_col --- @type integer, integer
elseif end_row < start_row then elseif end_row < start_row then
start_row, end_row = end_row, start_row start_row, end_row = end_row, start_row --- @type integer, integer
start_col, end_col = end_col, start_col start_col, end_col = end_col, start_col --- @type integer, integer
end end
if mode == 'V' then if mode == 'V' then
start_col = 1 start_col = 1
@ -553,25 +553,30 @@ function M.format(opts)
--- @param client vim.lsp.Client --- @param client vim.lsp.Client
--- @param params lsp.DocumentFormattingParams --- @param params lsp.DocumentFormattingParams
--- @return lsp.DocumentFormattingParams --- @return lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams
local function set_range(client, params) local function set_range(client, params)
local to_lsp_range = function(r) ---@return lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams --- @param r {start:[integer,integer],end:[integer, integer]}
local function to_lsp_range(r)
return util.make_given_range_params(r.start, r['end'], bufnr, client.offset_encoding).range return util.make_given_range_params(r.start, r['end'], bufnr, client.offset_encoding).range
end end
local ret = params --[[@as lsp.DocumentFormattingParams|lsp.DocumentRangeFormattingParams|lsp.DocumentRangesFormattingParams]]
if passed_multiple_ranges then if passed_multiple_ranges then
params.ranges = vim.tbl_map(to_lsp_range, range) ret = params --[[@as lsp.DocumentRangesFormattingParams]]
--- @cast range {start:[integer,integer],end:[integer, integer]}
ret.ranges = vim.tbl_map(to_lsp_range, range)
elseif range then elseif range then
params.range = to_lsp_range(range) ret = params --[[@as lsp.DocumentRangeFormattingParams]]
ret.range = to_lsp_range(range)
end end
return params return ret
end end
if opts.async then if opts.async then
--- @param idx integer --- @param idx? integer
--- @param client vim.lsp.Client --- @param client? vim.lsp.Client
local function do_format(idx, client) local function do_format(idx, client)
if not client then if not idx or not client then
return return
end end
local params = set_range(client, util.make_formatting_params(opts.formatting_options)) local params = set_range(client, util.make_formatting_params(opts.formatting_options))
@ -650,16 +655,16 @@ function M.rename(new_name, opts)
)[1] )[1]
end end
--- @param idx integer --- @param idx? integer
--- @param client? vim.lsp.Client --- @param client? vim.lsp.Client
local function try_use_client(idx, client) local function try_use_client(idx, client)
if not client then if not idx or not client then
return return
end end
--- @param name string --- @param name string
local function rename(name) local function rename(name)
local params = util.make_position_params(win, client.offset_encoding) local params = util.make_position_params(win, client.offset_encoding) --[[@as lsp.RenameParams]]
params.newName = name params.newName = name
local handler = client.handlers[ms.textDocument_rename] local handler = client.handlers[ms.textDocument_rename]
or lsp.handlers[ms.textDocument_rename] or lsp.handlers[ms.textDocument_rename]
@ -1229,6 +1234,7 @@ function M.code_action(opts)
for _, client in ipairs(clients) do for _, client in ipairs(clients) do
---@type lsp.CodeActionParams ---@type lsp.CodeActionParams
local params local params
if opts.range then if opts.range then
assert(type(opts.range) == 'table', 'code_action range must be a table') assert(type(opts.range) == 'table', 'code_action range must be a table')
local start = assert(opts.range.start, 'range must have a `start` property') local start = assert(opts.range.start, 'range must have a `start` property')
@ -1241,6 +1247,9 @@ function M.code_action(opts)
else else
params = util.make_range_params(win, client.offset_encoding) params = util.make_range_params(win, client.offset_encoding)
end end
--- @cast params lsp.CodeActionParams
if context.diagnostics then if context.diagnostics then
params.context = context params.context = context
else else

View File

@ -904,18 +904,20 @@ end
function Client:_get_registration(method, bufnr) function Client:_get_registration(method, bufnr)
bufnr = vim._resolve_bufnr(bufnr) bufnr = vim._resolve_bufnr(bufnr)
for _, reg in ipairs(self.registrations[method] or {}) do for _, reg in ipairs(self.registrations[method] or {}) do
if not reg.registerOptions or not reg.registerOptions.documentSelector then local regoptions = reg.registerOptions --[[@as {documentSelector:lsp.TextDocumentFilter[]}]]
if not regoptions or not regoptions.documentSelector then
return reg return reg
end end
local documentSelector = reg.registerOptions.documentSelector local documentSelector = regoptions.documentSelector
local language = self:_get_language_id(bufnr) local language = self:_get_language_id(bufnr)
local uri = vim.uri_from_bufnr(bufnr) local uri = vim.uri_from_bufnr(bufnr)
local fname = vim.uri_to_fname(uri) local fname = vim.uri_to_fname(uri)
for _, filter in ipairs(documentSelector) do for _, filter in ipairs(documentSelector) do
local flang, fscheme, fpat = filter.language, filter.scheme, filter.pattern
if if
not (filter.language and language ~= filter.language) not (flang and language ~= flang)
and not (filter.scheme and not vim.startswith(uri, filter.scheme .. ':')) and not (fscheme and not vim.startswith(uri, fscheme .. ':'))
and not (filter.pattern and not vim.glob.to_lpeg(filter.pattern):match(fname)) and not (type(fpat) == 'string' and not vim.glob.to_lpeg(fpat):match(fname))
then then
return reg return reg
end end

View File

@ -470,7 +470,7 @@ local function trigger(bufnr, clients)
local server_start_boundary --- @type integer? local server_start_boundary --- @type integer?
for client_id, response in pairs(responses) do for client_id, response in pairs(responses) do
if response.err then if response.err then
vim.notify_once(response.err.message, vim.log.levels.warn) vim.notify_once(response.err.message, vim.log.levels.WARN)
end end
local result = response.result local result = response.result

View File

@ -20,7 +20,7 @@ end
---@return lsp.DiagnosticSeverity ---@return lsp.DiagnosticSeverity
local function severity_vim_to_lsp(severity) local function severity_vim_to_lsp(severity)
if type(severity) == 'string' then if type(severity) == 'string' then
severity = vim.diagnostic.severity[severity] severity = vim.diagnostic.severity[severity] --- @type integer
end end
return severity return severity
end end
@ -89,6 +89,7 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)
string.format('Unsupported Markup message from LSP client %d', client_id), string.format('Unsupported Markup message from LSP client %d', client_id),
vim.lsp.log_levels.ERROR vim.lsp.log_levels.ERROR
) )
--- @diagnostic disable-next-line: undefined-field,no-unknown
message = diagnostic.message.value message = diagnostic.message.value
end end
local line = buf_lines and buf_lines[start.line + 1] or '' local line = buf_lines and buf_lines[start.line + 1] or ''

View File

@ -47,7 +47,7 @@ RSC[ms.dollar_progress] = function(_, params, ctx)
local value = params.value local value = params.value
if type(value) == 'table' then if type(value) == 'table' then
kind = value.kind kind = value.kind --- @type string
-- Carry over title of `begin` messages to `report` and `end` messages -- Carry over title of `begin` messages to `report` and `end` messages
-- So that consumers always have it available, even if they consume a -- So that consumers always have it available, even if they consume a
-- subset of the full sequence -- subset of the full sequence

View File

@ -15,7 +15,6 @@ local sysname = vim.uv.os_uname().sysname
--- @class vim.lsp.protocol.constants --- @class vim.lsp.protocol.constants
--- @nodoc --- @nodoc
local constants = { local constants = {
--- @enum lsp.DiagnosticSeverity
DiagnosticSeverity = { DiagnosticSeverity = {
-- Reports an error. -- Reports an error.
Error = 1, Error = 1,
@ -27,7 +26,6 @@ local constants = {
Hint = 4, Hint = 4,
}, },
--- @enum lsp.DiagnosticTag
DiagnosticTag = { DiagnosticTag = {
-- Unused or unnecessary code -- Unused or unnecessary code
Unnecessary = 1, Unnecessary = 1,
@ -35,7 +33,6 @@ local constants = {
Deprecated = 2, Deprecated = 2,
}, },
---@enum lsp.MessageType
MessageType = { MessageType = {
-- An error message. -- An error message.
Error = 1, Error = 1,
@ -50,7 +47,6 @@ local constants = {
}, },
-- The file event type. -- The file event type.
---@enum lsp.FileChangeType
FileChangeType = { FileChangeType = {
-- The file got created. -- The file got created.
Created = 1, Created = 1,
@ -149,7 +145,6 @@ local constants = {
}, },
-- Represents reasons why a text document is saved. -- Represents reasons why a text document is saved.
---@enum lsp.TextDocumentSaveReason
TextDocumentSaveReason = { TextDocumentSaveReason = {
-- Manually triggered, e.g. by the user pressing save, by starting debugging, -- Manually triggered, e.g. by the user pressing save, by starting debugging,
-- or by an API call. -- or by an API call.
@ -246,7 +241,6 @@ local constants = {
-- Defines whether the insert text in a completion item should be interpreted as -- Defines whether the insert text in a completion item should be interpreted as
-- plain text or a snippet. -- plain text or a snippet.
--- @enum lsp.InsertTextFormat
InsertTextFormat = { InsertTextFormat = {
-- The primary text to be inserted is treated as a plain string. -- The primary text to be inserted is treated as a plain string.
PlainText = 1, PlainText = 1,
@ -305,7 +299,6 @@ local constants = {
SourceOrganizeImports = 'source.organizeImports', SourceOrganizeImports = 'source.organizeImports',
}, },
-- The reason why code actions were requested. -- The reason why code actions were requested.
---@enum lsp.CodeActionTriggerKind
CodeActionTriggerKind = { CodeActionTriggerKind = {
-- Code actions were explicitly requested by the user or by an extension. -- Code actions were explicitly requested by the user or by an extension.
Invoked = 1, Invoked = 1,

View File

@ -139,7 +139,7 @@ local function tokens_to_ranges(data, bufnr, client, request)
if token_type then if token_type then
local modifiers = modifiers_from_number(data[i + 4], token_modifiers) local modifiers = modifiers_from_number(data[i + 4], token_modifiers)
local end_char = start_char + data[i + 2] local end_char = start_char + data[i + 2] --- @type integer LuaLS bug
local buf_line = lines and lines[line + 1] or '' local buf_line = lines and lines[line + 1] or ''
local start_col = vim.str_byteindex(buf_line, encoding, start_char, false) local start_col = vim.str_byteindex(buf_line, encoding, start_char, false)
local end_col = vim.str_byteindex(buf_line, encoding, end_char, false) local end_col = vim.str_byteindex(buf_line, encoding, end_char, false)

View File

@ -49,7 +49,8 @@ local function get_border_size(opts)
if not border_size[border] then if not border_size[border] then
border_error(border) border_error(border)
end end
return unpack(border_size[border]) local r = border_size[border]
return r[1], r[2]
end end
if 8 % #border ~= 0 then if 8 % #border ~= 0 then
@ -1897,6 +1898,7 @@ function M.make_position_params(window, position_encoding)
'position_encoding param is required in vim.lsp.util.make_position_params. Defaulting to position encoding of the first client.', 'position_encoding param is required in vim.lsp.util.make_position_params. Defaulting to position encoding of the first client.',
vim.log.levels.WARN vim.log.levels.WARN
) )
--- @diagnostic disable-next-line: deprecated
position_encoding = M._get_offset_encoding(buf) position_encoding = M._get_offset_encoding(buf)
end end
return { return {
@ -1953,6 +1955,7 @@ function M.make_range_params(window, position_encoding)
'position_encoding param is required in vim.lsp.util.make_range_params. Defaulting to position encoding of the first client.', 'position_encoding param is required in vim.lsp.util.make_range_params. Defaulting to position encoding of the first client.',
vim.log.levels.WARN vim.log.levels.WARN
) )
--- @diagnostic disable-next-line: deprecated
position_encoding = M._get_offset_encoding(buf) position_encoding = M._get_offset_encoding(buf)
end end
local position = make_position_param(window, position_encoding) local position = make_position_param(window, position_encoding)
@ -1982,6 +1985,7 @@ function M.make_given_range_params(start_pos, end_pos, bufnr, position_encoding)
'position_encoding param is required in vim.lsp.util.make_given_range_params. Defaulting to position encoding of the first client.', 'position_encoding param is required in vim.lsp.util.make_given_range_params. Defaulting to position encoding of the first client.',
vim.log.levels.WARN vim.log.levels.WARN
) )
--- @diagnostic disable-next-line: deprecated
position_encoding = M._get_offset_encoding(bufnr) position_encoding = M._get_offset_encoding(bufnr)
end end
--- @type [integer, integer] --- @type [integer, integer]

View File

@ -10,22 +10,20 @@ end
-- Attempts to construct a shell command from an args list. -- Attempts to construct a shell command from an args list.
-- Only for display, to help users debug a failed command. -- Only for display, to help users debug a failed command.
--- @param cmd string|string[]
local function shellify(cmd) local function shellify(cmd)
if type(cmd) ~= 'table' then if type(cmd) ~= 'table' then
return cmd return cmd
end end
local escaped = {} local escaped = {} --- @type string[]
for i, v in ipairs(cmd) do for i, v in ipairs(cmd) do
if v:match('[^A-Za-z_/.-]') then escaped[i] = v:match('[^A-Za-z_/.-]') and vim.fn.shellescape(v) or v
escaped[i] = vim.fn.shellescape(v)
else
escaped[i] = v
end
end end
return table.concat(escaped, ' ') return table.concat(escaped, ' ')
end end
-- Handler for s:system() function. -- Handler for s:system() function.
--- @param self {output: string, stderr: string, add_stderr_to_output: boolean}
local function system_handler(self, _, data, event) local function system_handler(self, _, data, event)
if event == 'stderr' then if event == 'stderr' then
if self.add_stderr_to_output then if self.add_stderr_to_output then
@ -38,7 +36,7 @@ local function system_handler(self, _, data, event)
end end
end end
--- @param cmd table List of command arguments to execute --- @param cmd string|string[] List of command arguments to execute
--- @param args? table Optional arguments: --- @param args? table Optional arguments:
--- - stdin (string): Data to write to the job's stdin --- - stdin (string): Data to write to the job's stdin
--- - stderr (boolean): Append stderr to stdout --- - stderr (boolean): Append stderr to stdout
@ -47,8 +45,8 @@ end
local function system(cmd, args) local function system(cmd, args)
args = args or {} args = args or {}
local stdin = args.stdin or '' local stdin = args.stdin or ''
local stderr = vim.F.if_nil(args.stderr, false) local stderr = args.stderr or false
local ignore_error = vim.F.if_nil(args.ignore_error, false) local ignore_error = args.ignore_error or false
local shell_error_code = 0 local shell_error_code = 0
local opts = { local opts = {
@ -530,13 +528,14 @@ local function version_info(python)
if rc ~= 0 or nvim_version == '' then if rc ~= 0 or nvim_version == '' then
nvim_version = 'unable to find pynvim module version' nvim_version = 'unable to find pynvim module version'
local base = vim.fs.basename(nvim_path) local base = vim.fs.basename(nvim_path)
local metas = vim.fn.glob(base .. '-*/METADATA', true, 1) local metas = vim.fn.glob(base .. '-*/METADATA', true, true)
vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', true, 1)) vim.list_extend(metas, vim.fn.glob(base .. '-*/PKG-INFO', true, true))
vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', true, 1)) vim.list_extend(metas, vim.fn.glob(base .. '.egg-info/PKG-INFO', true, true))
metas = table.sort(metas, compare) metas = table.sort(metas, compare)
if metas and next(metas) ~= nil then if metas and next(metas) ~= nil then
for line in io.lines(metas[1]) do for line in io.lines(metas[1]) do
--- @cast line string
local version = line:match('^Version: (%S+)') local version = line:match('^Version: (%S+)')
if version then if version then
nvim_version = version nvim_version = version
@ -762,6 +761,7 @@ local function python()
-- subshells launched from Nvim. -- subshells launched from Nvim.
local bin_dir = iswin and 'Scripts' or 'bin' local bin_dir = iswin and 'Scripts' or 'bin'
local venv_bins = vim.fn.glob(string.format('%s/%s/python*', virtual_env, bin_dir), true, true) local venv_bins = vim.fn.glob(string.format('%s/%s/python*', virtual_env, bin_dir), true, true)
--- @param v string
venv_bins = vim.tbl_filter(function(v) venv_bins = vim.tbl_filter(function(v)
-- XXX: Remove irrelevant executables found in bin/. -- XXX: Remove irrelevant executables found in bin/.
return not v:match('python.*%-config') return not v:match('python.*%-config')
@ -809,6 +809,7 @@ local function python()
msg, msg,
bin_dir, bin_dir,
table.concat( table.concat(
--- @param v string
vim.tbl_map(function(v) vim.tbl_map(function(v)
return vim.fs.basename(v) return vim.fs.basename(v)
end, venv_bins), end, venv_bins),
@ -817,12 +818,15 @@ local function python()
) )
end end
local conj = '\nBut ' local conj = '\nBut '
local msgs = {} --- @type string[]
for _, err in ipairs(errors) do for _, err in ipairs(errors) do
msg = msg .. conj .. err msgs[#msgs + 1] = msg
msgs[#msgs + 1] = conj
msgs[#msgs + 1] = err
conj = '\nAnd ' conj = '\nAnd '
end end
msg = msg .. '\nSo invoking Python may lead to unexpected results.' msgs[#msgs + 1] = '\nSo invoking Python may lead to unexpected results.'
health.warn(msg, vim.tbl_keys(hints)) health.warn(table.concat(msgs), vim.tbl_keys(hints))
else else
health.info(msg) health.info(msg)
health.info( health.info(

View File

@ -1,3 +1,4 @@
--- @diagnostic disable: no-unknown
-- --
-- Copyright 2007-2023, Lua.org & PUC-Rio (see 'lpeg.html' for license) -- Copyright 2007-2023, Lua.org & PUC-Rio (see 'lpeg.html' for license)
-- written by Roberto Ierusalimschy -- written by Roberto Ierusalimschy

View File

@ -7,8 +7,7 @@
-- so this wouldn't be a separate case to consider) -- so this wouldn't be a separate case to consider)
---@nodoc ---@nodoc
---@diagnostic disable-next-line: lowercase-global _G.vim = _G.vim or {}
vim = vim or {}
---@generic T ---@generic T
---@param orig T ---@param orig T

View File

@ -149,7 +149,7 @@ end
--- Returns the node's range or an unpacked range table --- Returns the node's range or an unpacked range table
--- ---
---@param node_or_range (TSNode | table) Node or table of positions ---@param node_or_range TSNode|Range4 Node or table of positions
--- ---
---@return integer start_row ---@return integer start_row
---@return integer start_col ---@return integer start_col
@ -157,7 +157,8 @@ end
---@return integer end_col ---@return integer end_col
function M.get_node_range(node_or_range) function M.get_node_range(node_or_range)
if type(node_or_range) == 'table' then if type(node_or_range) == 'table' then
return unpack(node_or_range) --- @cast node_or_range -TSNode LuaLS bug
return M._range.unpack4(node_or_range)
else else
return node_or_range:range(false) return node_or_range:range(false)
end end
@ -238,7 +239,9 @@ function M.node_contains(node, range)
-- allow a table so nodes can be mocked -- allow a table so nodes can be mocked
vim.validate('node', node, { 'userdata', 'table' }) vim.validate('node', node, { 'userdata', 'table' })
vim.validate('range', range, M._range.validate, 'integer list with 4 or 6 elements') vim.validate('range', range, M._range.validate, 'integer list with 4 or 6 elements')
return M._range.contains({ node:range() }, range) --- @diagnostic disable-next-line: missing-fields LuaLS bug
local nrange = { node:range() } --- @type Range4
return M._range.contains(nrange, range)
end end
--- Returns a list of highlight captures at the given position --- Returns a list of highlight captures at the given position

View File

@ -20,9 +20,15 @@ error('Cannot require a meta file')
---@class (exact) TSQueryInfo ---@class (exact) TSQueryInfo
---@field captures string[] ---@field captures string[]
---@field patterns table<integer, (integer|string)[][]> ---@field patterns table<integer, (integer|string)[][]>
---
---@class TSLangInfo
---@field fields string[]
---@field symbols table<string,boolean>
---@field _wasm boolean
---@field _abi_version integer
--- @param lang string --- @param lang string
--- @return table --- @return TSLangInfo
vim._ts_inspect_language = function(lang) end vim._ts_inspect_language = function(lang) end
---@return integer ---@return integer

View File

@ -104,6 +104,7 @@ function TSNode:end_() end
--- - end column --- - end column
--- - end byte (if {include_bytes} is `true`) --- - end byte (if {include_bytes} is `true`)
--- @param include_bytes boolean? --- @param include_bytes boolean?
--- @return integer, integer, integer, integer
function TSNode:range(include_bytes) end function TSNode:range(include_bytes) end
--- @nodoc --- @nodoc

View File

@ -138,7 +138,9 @@ local function lint_match(buf, match, query, lang_context, diagnostics)
-- perform language-independent checks only for first lang -- perform language-independent checks only for first lang
if lang_context.is_first_lang and cap_id == 'error' then if lang_context.is_first_lang and cap_id == 'error' then
local node_text = vim.treesitter.get_node_text(node, buf):gsub('\n', ' ') local node_text = vim.treesitter.get_node_text(node, buf):gsub('\n', ' ')
add_lint_for_node(diagnostics, { node:range() }, 'Syntax error: ' .. node_text) ---@diagnostic disable-next-line: missing-fields LuaLS varargs bug
local range = { node:range() } --- @type Range4
add_lint_for_node(diagnostics, range, 'Syntax error: ' .. node_text)
end end
-- other checks rely on Neovim parser introspection -- other checks rely on Neovim parser introspection

View File

@ -137,14 +137,6 @@ end
local decor_ns = api.nvim_create_namespace('nvim.treesitter.dev') local decor_ns = api.nvim_create_namespace('nvim.treesitter.dev')
---@param range Range4
---@return string
local function range_to_string(range)
---@type integer, integer, integer, integer
local row, col, end_row, end_col = unpack(range)
return string.format('[%d, %d] - [%d, %d]', row, col, end_row, end_col)
end
---@param w integer ---@param w integer
---@return boolean closed Whether the window was closed. ---@return boolean closed Whether the window was closed.
local function close_win(w) local function close_win(w)
@ -227,7 +219,7 @@ function TSTreeView:draw(bufnr)
local lang_hl_marks = {} ---@type table[] local lang_hl_marks = {} ---@type table[]
for i, item in self:iter() do for i, item in self:iter() do
local range_str = range_to_string({ item.node:range() }) local range_str = ('[%d, %d] - [%d, %d]'):format(item.node:range())
local lang_str = self.opts.lang and string.format(' %s', item.lang) or '' local lang_str = self.opts.lang and string.format(' %s', item.lang) or ''
local text ---@type string local text ---@type string

View File

@ -175,7 +175,7 @@ end
--- (`"`). --- (`"`).
--- ---
---@param lang string Language ---@param lang string Language
---@return table ---@return TSLangInfo
function M.inspect(lang) function M.inspect(lang)
M.add(lang) M.add(lang)
return vim._ts_inspect_language(lang) return vim._ts_inspect_language(lang)

View File

@ -123,7 +123,7 @@ function LanguageTree.new(source, lang, opts)
local injections = opts.injections or {} local injections = opts.injections or {}
--- @type vim.treesitter.LanguageTree --- @class vim.treesitter.LanguageTree
local self = { local self = {
_source = source, _source = source,
_lang = lang, _lang = lang,
@ -190,7 +190,7 @@ end
---Measure execution time of a function ---Measure execution time of a function
---@generic R1, R2, R3 ---@generic R1, R2, R3
---@param f fun(): R1, R2, R2 ---@param f fun(): R1, R2, R3
---@return number, R1, R2, R3 ---@return number, R1, R2, R3
local function tcall(f, ...) local function tcall(f, ...)
local start = vim.uv.hrtime() local start = vim.uv.hrtime()
@ -198,6 +198,7 @@ local function tcall(f, ...)
local r = { f(...) } local r = { f(...) }
--- @type number --- @type number
local duration = (vim.uv.hrtime() - start) / 1000000 local duration = (vim.uv.hrtime() - start) / 1000000
--- @diagnostic disable-next-line: redundant-return-value
return duration, unpack(r) return duration, unpack(r)
end end
@ -550,14 +551,14 @@ function LanguageTree:_parse(range, timeout)
local no_regions_parsed = 0 local no_regions_parsed = 0
local query_time = 0 local query_time = 0
local total_parse_time = 0 local total_parse_time = 0
local is_finished --- @type boolean
-- At least 1 region is invalid -- At least 1 region is invalid
if not self:is_valid(true) then if not self:is_valid(true) then
local is_finished
changes, no_regions_parsed, total_parse_time, is_finished = self:_parse_regions(range, timeout) changes, no_regions_parsed, total_parse_time, is_finished = self:_parse_regions(range, timeout)
timeout = timeout and math.max(timeout - total_parse_time, 0) timeout = timeout and math.max(timeout - total_parse_time, 0)
if not is_finished then if not is_finished then
return self._trees, is_finished return self._trees, false
end end
-- Need to run injections when we parsed something -- Need to run injections when we parsed something
if no_regions_parsed > 0 then if no_regions_parsed > 0 then
@ -740,6 +741,7 @@ function LanguageTree:set_included_regions(new_regions)
if type(range) == 'table' and #range == 4 then if type(range) == 'table' and #range == 4 then
region[i] = Range.add_bytes(self._source, range --[[@as Range4]]) region[i] = Range.add_bytes(self._source, range --[[@as Range4]])
elseif type(range) == 'userdata' then elseif type(range) == 'userdata' then
--- @diagnostic disable-next-line: missing-fields LuaLS varargs bug
region[i] = { range:range(true) } region[i] = { range:range(true) }
end end
end end

View File

@ -262,6 +262,7 @@ local explicit_queries = setmetatable({}, {
---@param query_name string Name of the query (e.g., "highlights") ---@param query_name string Name of the query (e.g., "highlights")
---@param text string Query text (unparsed). ---@param text string Query text (unparsed).
function M.set(lang, query_name, text) function M.set(lang, query_name, text)
--- @diagnostic disable-next-line: undefined-field LuaLS bad at generics
M.get:clear(lang, query_name) M.get:clear(lang, query_name)
explicit_queries[lang][query_name] = M.parse(lang, text) explicit_queries[lang][query_name] = M.parse(lang, text)
end end
@ -291,6 +292,7 @@ api.nvim_create_autocmd('OptionSet', {
pattern = { 'runtimepath' }, pattern = { 'runtimepath' },
group = api.nvim_create_augroup('nvim.treesitter.query_cache_reset', { clear = true }), group = api.nvim_create_augroup('nvim.treesitter.query_cache_reset', { clear = true }),
callback = function() callback = function()
--- @diagnostic disable-next-line: undefined-field LuaLS bad at generics
M.get:clear() M.get:clear()
end, end,
}) })

View File

@ -60,9 +60,10 @@ end
---@param path string Path to file ---@param path string Path to file
---@return string URI ---@return string URI
function M.uri_from_fname(path) function M.uri_from_fname(path)
local volume_path, fname = path:match('^([a-zA-Z]:)(.*)') ---@type string? local volume_path, fname = path:match('^([a-zA-Z]:)(.*)') ---@type string?, string?
local is_windows = volume_path ~= nil local is_windows = volume_path ~= nil
if is_windows then if is_windows then
assert(fname)
path = volume_path .. M.uri_encode(fname:gsub('\\', '/')) path = volume_path .. M.uri_encode(fname:gsub('\\', '/'))
else else
path = M.uri_encode(path) path = M.uri_encode(path)
@ -111,7 +112,7 @@ function M.uri_to_fname(uri)
uri = M.uri_decode(uri) uri = M.uri_decode(uri)
--TODO improve this. --TODO improve this.
if is_windows_file_uri(uri) then if is_windows_file_uri(uri) then
uri = uri:gsub('^file:/+', ''):gsub('/', '\\') uri = uri:gsub('^file:/+', ''):gsub('/', '\\') --- @type string
else else
uri = uri:gsub('^file:/+', '/') ---@type string uri = uri:gsub('^file:/+', '/') ---@type string
end end

View File

@ -72,6 +72,10 @@ local LUA_API_META_HEADER = {
'-- DO NOT EDIT', '-- DO NOT EDIT',
"error('Cannot require a meta file')", "error('Cannot require a meta file')",
'', '',
'--- This file embeds vimdoc as the function descriptions',
'--- so ignore any doc related errors.',
'--- @diagnostic disable: undefined-doc-name,luadoc-miss-symbol',
'',
'vim.api = {}', 'vim.api = {}',
} }